Exception Fact Sheet for "tomcat"

The goal of an Exception Fact Sheet is to reveal the design of exception handling in an application.

--Maxence, Martin

For feedback, please contact Martin

Table of contents

Basic Statistics

Number of Classes 1787
Number of Domain Exception Types (Thrown or Caught) 39
Number of Domain Checked Exception Types 22
Number of Domain Runtime Exception Types 14
Number of Domain Unknown Exception Types 3
nTh = Number of Throw 2064
nTh = Number of Throw in Catch 818
Number of Catch-Rethrow (may not be correct) 236
nC = Number of Catch 2348
nCTh = Number of Catch with Throw 673
Number of Empty Catch (really Empty) 62
Number of Empty Catch (with comments) 309
Number of Empty Catch 371
nM = Number of Methods 14752
nbFunctionWithCatch = Number of Methods with Catch 1369 / 14752
nbFunctionWithThrow = Number of Methods with Throw 1196 / 14752
nbFunctionWithThrowS = Number of Methods with ThrowS 3016 / 14752
nbFunctionTransmitting = Number of Methods with "Throws" but NO catch, NO throw (only transmitting) 2075 / 14752
P1 = nCTh / nC 28.7% (0.287)
P2 = nMC / nM 9.3% (0.093)
P3 = nbFunctionWithThrow / nbFunction 8.1% (0.081)
P4 = nbFunctionTransmitting / nbFunction 14.1% (0.141)
P5 = nbThrowInCatch / nbThrow 39.6% (0.396)
R2 = nCatch / nThrow 1.138
A1 = Number of Caught Exception Types From External Libraries 94
A2 = Number of Reused Exception Types From External Libraries (thrown from application code) 54

W1 is a rough estimation of the richness of the exception model. It does not take into account the inheritance relationships between domain exceptions.

Proportion P1 measures the overall exception flow. According to our experience, it varies from 5% to 70%. Early-catch design generally yields a low P1, libraries that must warn clients about errors (e.g. databases) generally have a high P1.

Proportion P2 measures the dispersion of catch blocks in the application. According to our experience, it varies from 2% to 15%. A small P2 indicates a rather centralized management of errors.

R1 shows how many exceptions types from libraries (incl. JDK) are thrown from application code. For instance, IllegalArgumentException comes from the JDK but is used in many applications.

A1 measures the awareness of the application to library exceptions. A high value of A1 means either that the application is polluted with checked exceptions or that it is able to apply specific recovery depending on the library exception.

Exception Hierachy

Exception Map

Each exception that is used at least once in the project is a dot. A orange dot represents a domain exception that is defined in the application. A blue dot exception is defined in the JDK or in a library. The x-axis represents the number of times an exception is caught, the y-axis the number of times an exception is thrown.

Exceptions With State

State means fields. Number of exceptions with state: 11
FileUploadIOException
              package org.apache.tomcat.util.http.fileupload;public static class FileUploadIOException extends IOException {
        /** The exceptions UID, for serializing an instance.
         */
        private static final long serialVersionUID = -7047616958165584154L;
        /** The exceptions cause; we overwrite the parent
         * classes field, which is available since Java
         * 1.4 only.
         */
        private final FileUploadException cause;

        /**
         * Creates a <code>FileUploadIOException</code> with the
         * given cause.
         * @param pCause The exceptions cause, if any, or null.
         */
        public FileUploadIOException(FileUploadException pCause) {
            // We're not doing super(pCause) cause of 1.3 compatibility.
            cause = pCause;
        }

        /**
         * Returns the exceptions cause.
         * @return The exceptions cause, if any, or null.
         */
        @Override
        public Throwable getCause() {
            return cause;
        }
    }
            
ClientAbortException
              package org.apache.catalina.connector;public final class ClientAbortException extends IOException {

    private static final long serialVersionUID = 1L;


    //------------------------------------------------------------ Constructors

    /**
     * Construct a new ClientAbortException with no other information.
     */
    public ClientAbortException() {

        this(null, null);

    }


    /**
     * Construct a new ClientAbortException for the specified message.
     *
     * @param message Message describing this exception
     */
    public ClientAbortException(String message) {

        this(message, null);

    }


    /**
     * Construct a new ClientAbortException for the specified throwable.
     *
     * @param throwable Throwable that caused this exception
     */
    public ClientAbortException(Throwable throwable) {

        this(null, throwable);

    }


    /**
     * Construct a new ClientAbortException for the specified message
     * and throwable.
     *
     * @param message Message describing this exception
     * @param throwable Throwable that caused this exception
     */
    public ClientAbortException(String message, Throwable throwable) {

        super();
        this.message = message;
        this.throwable = throwable;

    }


    //------------------------------------------------------ Instance Variables


    /**
     * The error message passed to our constructor (if any)
     */
    protected String message = null;


    /**
     * The underlying exception or error passed to our constructor (if any)
     */
    protected Throwable throwable = null;


    //---------------------------------------------------------- Public Methods


    /**
     * Returns the message associated with this exception, if any.
     */
    @Override
    public String getMessage() {

        return (message);

    }


    /**
     * Returns the cause that caused this exception, if any.
     */
    @Override
    public Throwable getCause() {

        return (throwable);

    }


    /**
     * Return a formatted string that describes this exception.
     */
    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder("ClientAbortException:  ");
        if (message != null) {
            sb.append(message);
            if (throwable != null) {
                sb.append(":  ");
            }
        }
        if (throwable != null) {
            sb.append(throwable.toString());
        }
        return (sb.toString());

    }


}
            
Error
              package org.apache.tomcat.jni;public class Error extends Exception {

    private static final long serialVersionUID = 1L;

    /**
     * APR error type.
     */
    private int error;

    /**
     * A description of the problem.
     */
    private String description;

    /**
     * Construct an APRException.
     *
     * @param error one of the value in Error
     * @param description error message
     */
    private Error(int error, String description)
    {
        super(error + ": " + description);
        this.error = error;
        this.description = description;
    }

    /**
     * Get the APR error code of the exception.
     *
     * @return error of the Exception
     */
    public int getError()
    {
        return error;
    }

    /**
     * Get the APR description of the exception.
     *
     * @return description of the Exception
     */
    public String getDescription()
    {
        return description;
    }

    /**
     * Get the last platform error.
     * @return apr_status_t the last platform error, folded into apr_status_t, on most platforms
     * This retrieves errno, or calls a GetLastError() style function, and
     *      folds it with APR_FROM_OS_ERROR.  Some platforms (such as OS2) have no
     *      such mechanism, so this call may be unsupported.  Do NOT use this
     *      call for socket errors from socket, send, recv etc!
     */
    public static native int osError();

    /**
     * Get the last platform socket error.
     * @return the last socket error, folded into apr_status_t, on all platforms
     * This retrieves errno or calls a GetLastSocketError() style function,
     *      and folds it with APR_FROM_OS_ERROR.
     */
    public static native int netosError();

    /**
     * Return a human readable string describing the specified error.
     * @param statcode The error code the get a string for.
     * @return The error string.
    */
    public static native String strerror(int statcode);

}
            
ParseException
              package org.apache.tomcat.util.http.parser;public class ParseException extends Exception {

  /**
   * The version identifier for this Serializable class.
   * Increment only if the <i>serialized</i> form of the
   * class changes.
   */
  private static final long serialVersionUID = 1L;

  /**
   * This constructor is used by the method "generateParseException"
   * in the generated parser.  Calling this constructor generates
   * a new object of this type with the fields "currentToken",
   * "expectedTokenSequences", and "tokenImage" set.
   */
  public ParseException(Token currentTokenVal,
                        int[][] expectedTokenSequencesVal,
                        String[] tokenImageVal
                       )
  {
    super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));
    currentToken = currentTokenVal;
    expectedTokenSequences = expectedTokenSequencesVal;
    tokenImage = tokenImageVal;
  }

  /**
   * The following constructors are for use by you for whatever
   * purpose you can think of.  Constructing the exception in this
   * manner makes the exception behave in the normal way - i.e., as
   * documented in the class "Throwable".  The fields "errorToken",
   * "expectedTokenSequences", and "tokenImage" do not contain
   * relevant information.  The JavaCC generated code does not use
   * these constructors.
   */

  public ParseException() {
    super();
  }

  /** Constructor with message. */
  public ParseException(String message) {
    super(message);
  }


  /**
   * This is the last token that has been consumed successfully.  If
   * this object has been created due to a parse error, the token
   * followng this token will (therefore) be the first error token.
   */
  public Token currentToken;

  /**
   * Each entry in this array is an array of integers.  Each array
   * of integers represents a sequence of tokens (by their ordinal
   * values) that is expected at this point of the parse.
   */
  public int[][] expectedTokenSequences;

  /**
   * This is a reference to the "tokenImage" array of the generated
   * parser within which the parse error occurred.  This array is
   * defined in the generated ...Constants interface.
   */
  public String[] tokenImage;

  /**
   * It uses "currentToken" and "expectedTokenSequences" to generate a parse
   * error message and returns it.  If this object has been created
   * due to a parse error, and you do not catch it (it gets thrown
   * from the parser) the correct error message
   * gets displayed.
   */
  private static String initialise(Token currentToken,
                           int[][] expectedTokenSequences,
                           String[] tokenImage) {
    String eol = System.getProperty("line.separator", "\n");
    StringBuffer expected = new StringBuffer();
    int maxSize = 0;
    for (int i = 0; i < expectedTokenSequences.length; i++) {
      if (maxSize < expectedTokenSequences[i].length) {
        maxSize = expectedTokenSequences[i].length;
      }
      for (int j = 0; j < expectedTokenSequences[i].length; j++) {
        expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
      }
      if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
        expected.append("...");
      }
      expected.append(eol).append("    ");
    }
    String retval = "Encountered \"";
    Token tok = currentToken.next;
    for (int i = 0; i < maxSize; i++) {
      if (i != 0) retval += " ";
      if (tok.kind == 0) {
        retval += tokenImage[0];
        break;
      }
      retval += " " + tokenImage[tok.kind];
      retval += " \"";
      retval += add_escapes(tok.image);
      retval += " \"";
      tok = tok.next;
    }
    retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
    retval += "." + eol;
    if (expectedTokenSequences.length == 1) {
      retval += "Was expecting:" + eol + "    ";
    } else {
      retval += "Was expecting one of:" + eol + "    ";
    }
    retval += expected.toString();
    return retval;
  }

  /**
   * The end of line string for this machine.
   */
  protected String eol = System.getProperty("line.separator", "\n");

  /**
   * Used to convert raw characters to their escaped version
   * when these raw version cannot be used as part of an ASCII
   * string literal.
   */
  static String add_escapes(String str) {
      StringBuffer retval = new StringBuffer();
      char ch;
      for (int i = 0; i < str.length(); i++) {
        switch (str.charAt(i))
        {
           case 0 :
              continue;
           case '\b':
              retval.append("\\b");
              continue;
           case '\t':
              retval.append("\\t");
              continue;
           case '\n':
              retval.append("\\n");
              continue;
           case '\f':
              retval.append("\\f");
              continue;
           case '\r':
              retval.append("\\r");
              continue;
           case '\"':
              retval.append("\\\"");
              continue;
           case '\'':
              retval.append("\\\'");
              continue;
           case '\\':
              retval.append("\\\\");
              continue;
           default:
              if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
                 String s = "0000" + Integer.toString(ch, 16);
                 retval.append("\\u" + s.substring(s.length() - 4, s.length()));
              } else {
                 retval.append(ch);
              }
              continue;
        }
      }
      return retval.toString();
   }

}
              package org.apache.el.parser;public class ParseException extends Exception {

  /**
   * The version identifier for this Serializable class.
   * Increment only if the <i>serialized</i> form of the
   * class changes.
   */
  private static final long serialVersionUID = 1L;

  /**
   * This constructor is used by the method "generateParseException"
   * in the generated parser.  Calling this constructor generates
   * a new object of this type with the fields "currentToken",
   * "expectedTokenSequences", and "tokenImage" set.
   */
  public ParseException(Token currentTokenVal,
                        int[][] expectedTokenSequencesVal,
                        String[] tokenImageVal
                       )
  {
    super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));
    currentToken = currentTokenVal;
    expectedTokenSequences = expectedTokenSequencesVal;
    tokenImage = tokenImageVal;
  }

  /**
   * The following constructors are for use by you for whatever
   * purpose you can think of.  Constructing the exception in this
   * manner makes the exception behave in the normal way - i.e., as
   * documented in the class "Throwable".  The fields "errorToken",
   * "expectedTokenSequences", and "tokenImage" do not contain
   * relevant information.  The JavaCC generated code does not use
   * these constructors.
   */

  public ParseException() {
    super();
  }

  /** Constructor with message. */
  public ParseException(String message) {
    super(message);
  }


  /**
   * This is the last token that has been consumed successfully.  If
   * this object has been created due to a parse error, the token
   * followng this token will (therefore) be the first error token.
   */
  public Token currentToken;

  /**
   * Each entry in this array is an array of integers.  Each array
   * of integers represents a sequence of tokens (by their ordinal
   * values) that is expected at this point of the parse.
   */
  public int[][] expectedTokenSequences;

  /**
   * This is a reference to the "tokenImage" array of the generated
   * parser within which the parse error occurred.  This array is
   * defined in the generated ...Constants interface.
   */
  public String[] tokenImage;

  /**
   * It uses "currentToken" and "expectedTokenSequences" to generate a parse
   * error message and returns it.  If this object has been created
   * due to a parse error, and you do not catch it (it gets thrown
   * from the parser) the correct error message
   * gets displayed.
   */
  private static String initialise(Token currentToken,
                           int[][] expectedTokenSequences,
                           String[] tokenImage) {
    String eol = System.getProperty("line.separator", "\n");
    StringBuffer expected = new StringBuffer();
    int maxSize = 0;
    for (int i = 0; i < expectedTokenSequences.length; i++) {
      if (maxSize < expectedTokenSequences[i].length) {
        maxSize = expectedTokenSequences[i].length;
      }
      for (int j = 0; j < expectedTokenSequences[i].length; j++) {
        expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
      }
      if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
        expected.append("...");
      }
      expected.append(eol).append("    ");
    }
    String retval = "Encountered \"";
    Token tok = currentToken.next;
    for (int i = 0; i < maxSize; i++) {
      if (i != 0) retval += " ";
      if (tok.kind == 0) {
        retval += tokenImage[0];
        break;
      }
      retval += " " + tokenImage[tok.kind];
      retval += " \"";
      retval += add_escapes(tok.image);
      retval += " \"";
      tok = tok.next;
    }
    retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
    retval += "." + eol;
    if (expectedTokenSequences.length == 1) {
      retval += "Was expecting:" + eol + "    ";
    } else {
      retval += "Was expecting one of:" + eol + "    ";
    }
    retval += expected.toString();
    return retval;
  }

  /**
   * The end of line string for this machine.
   */
  protected String eol = System.getProperty("line.separator", "\n");

  /**
   * Used to convert raw characters to their escaped version
   * when these raw version cannot be used as part of an ASCII
   * string literal.
   */
  static String add_escapes(String str) {
      StringBuffer retval = new StringBuffer();
      char ch;
      for (int i = 0; i < str.length(); i++) {
        switch (str.charAt(i))
        {
           case 0 :
              continue;
           case '\b':
              retval.append("\\b");
              continue;
           case '\t':
              retval.append("\\t");
              continue;
           case '\n':
              retval.append("\\n");
              continue;
           case '\f':
              retval.append("\\f");
              continue;
           case '\r':
              retval.append("\\r");
              continue;
           case '\"':
              retval.append("\\\"");
              continue;
           case '\'':
              retval.append("\\\'");
              continue;
           case '\\':
              retval.append("\\\\");
              continue;
           default:
              if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
                 String s = "0000" + Integer.toString(ch, 16);
                 retval.append("\\u" + s.substring(s.length() - 4, s.length()));
              } else {
                 retval.append(ch);
              }
              continue;
        }
      }
      return retval.toString();
   }

}
            
FileUploadException
              package org.apache.tomcat.util.http.fileupload;public class FileUploadException extends Exception {
    /**
     * Serial version UID, being used, if the exception
     * is serialized.
     */
    private static final long serialVersionUID = 8881893724388807504L;
    /**
     * The exceptions cause. We overwrite the cause of
     * the super class, which isn't available in Java 1.3.
     */
    private final Throwable cause;

    /**
     * Constructs a new <code>FileUploadException</code> without message.
     */
    public FileUploadException() {
        this(null, null);
    }

    /**
     * Constructs a new <code>FileUploadException</code> with specified detail
     * message.
     *
     * @param msg the error message.
     */
    public FileUploadException(final String msg) {
        this(msg, null);
    }

    /**
     * Creates a new <code>FileUploadException</code> with the given
     * detail message and cause.
     * @param msg The exceptions detail message.
     * @param cause The exceptions cause.
     */
    public FileUploadException(String msg, Throwable cause) {
        super(msg);
        this.cause = cause;
    }

    /**
     * Prints this throwable and its backtrace to the specified print stream.
     *
     * @param stream <code>PrintStream</code> to use for output
     */
    @Override
    public void printStackTrace(PrintStream stream) {
        super.printStackTrace(stream);
        if (cause != null) {
            stream.println("Caused by:");
            cause.printStackTrace(stream);
        }
    }

    /**
     * Prints this throwable and its backtrace to the specified
     * print writer.
     *
     * @param writer <code>PrintWriter</code> to use for output
     */
    @Override
    public void printStackTrace(PrintWriter writer) {
        super.printStackTrace(writer);
        if (cause != null) {
            writer.println("Caused by:");
            cause.printStackTrace(writer);
        }
    }

    @Override
    public Throwable getCause() {
        return cause;
    }
}
            
IOFileUploadException
              package org.apache.tomcat.util.http.fileupload;public static class IOFileUploadException extends FileUploadException {
        /** The exceptions UID, for serializing an instance.
         */
        private static final long serialVersionUID = 1749796615868477269L;
        /** The exceptions cause; we overwrite the parent
         * classes field, which is available since Java
         * 1.4 only.
         */
        private final IOException cause;

        /**
         * Creates a new instance with the given cause.
         * @param pMsg The detail message.
         * @param pException The exceptions cause.
         */
        public IOFileUploadException(String pMsg, IOException pException) {
            super(pMsg);
            cause = pException;
        }

        /**
         * Returns the exceptions cause.
         * @return The exceptions cause, if any, or null.
         */
        @Override
        public Throwable getCause() {
            return cause;
        }
    }
            
SizeException
              package org.apache.tomcat.util.http.fileupload;public abstract static class SizeException extends FileUploadException {

        private static final long serialVersionUID = -8776225574705254126L;

        /**
         * The actual size of the request.
         */
        private final long actual;

        /**
         * The maximum permitted size of the request.
         */
        private final long permitted;

        /**
         * Creates a new instance.
         * @param message The detail message.
         * @param actual The actual number of bytes in the request.
         * @param permitted The requests size limit, in bytes.
         */
        protected SizeException(String message, long actual, long permitted) {
            super(message);
            this.actual = actual;
            this.permitted = permitted;
        }

        /**
         * Retrieves the actual size of the request.
         *
         * @return The actual size of the request.
         */
        public long getActualSize() {
            return actual;
        }

        /**
         * Retrieves the permitted size of the request.
         *
         * @return The permitted size of the request.
         */
        public long getPermittedSize() {
            return permitted;
        }
    }
            
FileSizeLimitExceededException
              package org.apache.tomcat.util.http.fileupload;public static class FileSizeLimitExceededException
            extends SizeException {
        /** The exceptions UID, for serializing an instance.
         */
        private static final long serialVersionUID = 8150776562029630058L;

        /**
         * File name of the item, which caused the exception.
         */
        private String fileName;

        /**
         * Field name of the item, which caused the exception.
         */
        private String fieldName;

        /**
         * Constructs a <code>SizeExceededException</code> with
         * the specified detail message, and actual and permitted sizes.
         *
         * @param message   The detail message.
         * @param actual    The actual request size.
         * @param permitted The maximum permitted request size.
         */
        public FileSizeLimitExceededException(String message, long actual,
                long permitted) {
            super(message, actual, permitted);
        }

        /**
         * Returns the file name of the item, which caused the
         * exception.
         * @return File name, if known, or null.
         */
        public String getFileName() {
            return fileName;
        }

        /**
         * Sets the file name of the item, which caused the
         * exception.
         */
        public void setFileName(String pFileName) {
            fileName = pFileName;
        }

        /**
         * Returns the field name of the item, which caused the
         * exception.
         * @return Field name, if known, or null.
         */
        public String getFieldName() {
            return fieldName;
        }

        /**
         * Sets the field name of the item, which caused the
         * exception.
         */
        public void setFieldName(String pFieldName) {
            fieldName = pFieldName;
        }
    }
            
ChannelException
              package org.apache.catalina.tribes;public class ChannelException extends Exception {
    private static final long serialVersionUID = 1L;
    /**
     * Empty list to avoid reinstatiating lists
     */
    protected static final FaultyMember[] EMPTY_LIST = new FaultyMember[0];
    /*
     * Holds a list of faulty members
     */
    private ArrayList<FaultyMember> faultyMembers=null;

    /**
     * Constructor, creates a ChannelException
     * @see java.lang.Exception#Exception()
     */
    public ChannelException() {
        super();
    }

    /**
     * Constructor, creates a ChannelException with an error message
     * @see java.lang.Exception#Exception(String)
     */
    public ChannelException(String message) {
        super(message);
    }

    /**
     * Constructor, creates a ChannelException with an error message and a cause
     * @param message String
     * @param cause Throwable
     * @see java.lang.Exception#Exception(String,Throwable)
     */
    public ChannelException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Constructor, creates a ChannelException with a cause
     * @param cause Throwable
     * @see java.lang.Exception#Exception(Throwable)
     */
    public ChannelException(Throwable cause) {
        super(cause);
    }

    /**
     * Returns the message for this exception
     * @return String
     * @see java.lang.Exception#getMessage()
     */
    @Override
    public String getMessage() {
        StringBuilder buf = new StringBuilder(super.getMessage());
        if (faultyMembers==null || faultyMembers.size() == 0 ) {
            buf.append("; No faulty members identified.");
        } else {
            buf.append("; Faulty members:");
            for ( int i=0; i<faultyMembers.size(); i++ ) {
                FaultyMember mbr = faultyMembers.get(i);
                buf.append(mbr.getMember().getName());
                buf.append("; ");
            }
        }
        return buf.toString();
    }

    /**
     * Adds a faulty member, and the reason the member failed.
     * @param mbr Member
     * @param x Exception
     */
    public boolean addFaultyMember(Member mbr, Exception x ) {
        return addFaultyMember(new FaultyMember(mbr,x));
    }

    /**
     * Adds a list of faulty members
     * @param mbrs FaultyMember[]
     */
    public int addFaultyMember(FaultyMember[] mbrs) {
        int result = 0;
        for (int i=0; mbrs!=null && i<mbrs.length; i++ ) {
            if ( addFaultyMember(mbrs[i]) ) result++;
        }
        return result;
    }

    /**
     * Adds a faulty member
     * @param mbr FaultyMember
     */
    public boolean addFaultyMember(FaultyMember mbr) {
        if ( this.faultyMembers==null ) this.faultyMembers = new ArrayList<FaultyMember>();
        if ( !faultyMembers.contains(mbr) ) return faultyMembers.add(mbr);
        else return false;
    }

    /**
     * Returns an array of members that failed and the reason they failed.
     * @return FaultyMember[]
     */
    public FaultyMember[] getFaultyMembers() {
        if ( this.faultyMembers==null ) return EMPTY_LIST;
        return faultyMembers.toArray(new FaultyMember[faultyMembers.size()]);
    }

    /**
     *
     * <p>Title: FaultyMember class</p>
     *
     * <p>Description: Represent a failure to a specific member when a message was sent
     * to more than one member</p>
     *
     * @author Filip Hanik
     * @version 1.0
     */
    public static class FaultyMember {
        protected Exception cause;
        protected Member member;
        public FaultyMember(Member mbr, Exception x) {
            this.member = mbr;
            this.cause = x;
        }

        public Member getMember() {
            return member;
        }

        public Exception getCause() {
            return cause;
        }

        @Override
        public String toString() {
            return "FaultyMember:"+member.toString();
        }

        @Override
        public int hashCode() {
            return (member!=null)?member.hashCode():0;
        }

        @Override
        public boolean equals(Object o) {
            if (member==null || (!(o instanceof FaultyMember)) || (((FaultyMember)o).member==null)) return false;
            return member.equals(((FaultyMember)o).member);
        }
    }

}
            
UnavailableException
              package javax.servlet;public class UnavailableException extends ServletException {

    private static final long serialVersionUID = 1L;

    private final Servlet servlet; // what's unavailable
    private final boolean permanent; // needs admin action?
    private final int seconds; // unavailability estimate

    /**
     * @param servlet
     *            the <code>Servlet</code> instance that is unavailable
     * @param msg
     *            a <code>String</code> specifying the descriptive message
     * @deprecated As of Java Servlet API 2.2, use
     *             {@link #UnavailableException(String)} instead.
     */
    @SuppressWarnings("dep-ann")
    // Spec API does not use @Deprecated
    public UnavailableException(Servlet servlet, String msg) {
        super(msg);
        this.servlet = servlet;
        permanent = true;
        this.seconds = 0;
    }

    /**
     * @param seconds
     *            an integer specifying the number of seconds the servlet
     *            expects to be unavailable; if zero or negative, indicates that
     *            the servlet can't make an estimate
     * @param servlet
     *            the <code>Servlet</code> that is unavailable
     * @param msg
     *            a <code>String</code> specifying the descriptive message,
     *            which can be written to a log file or displayed for the user.
     * @deprecated As of Java Servlet API 2.2, use
     *             {@link #UnavailableException(String, int)} instead.
     */
    @SuppressWarnings("dep-ann")
    // Spec API does not use @Deprecated
    public UnavailableException(int seconds, Servlet servlet, String msg) {
        super(msg);
        this.servlet = servlet;
        if (seconds <= 0)
            this.seconds = -1;
        else
            this.seconds = seconds;
        permanent = false;
    }
            
InvalidFileNameException
              package org.apache.tomcat.util.http.fileupload;public class InvalidFileNameException extends RuntimeException {
    private static final long serialVersionUID = 7922042602454350470L;
    private final String name;

    /**
     * Creates a new instance.
     * @param pName The file name causing the exception.
     * @param pMessage A human readable error message.
     */
    public InvalidFileNameException(String pName, String pMessage) {
        super(pMessage);
        name = pName;
    }

    /**
     * Returns the invalid file name.
     */
    public String getName() {
        return name;
    }
}
            

Thrown Exceptions Summary

A (Domain) exception is defined in the application. A (Lib) exception is defined in the JDK or in a library. An exception can be thrown, thrown from within a catch, or declared in the signature of a method (usually for checked exceptions). Hovering over a number triggers showing code snippets from the application code.

Type Exception Thrown Thrown
from Catch
Declared
- Unknown 449
              
//in java/org/apache/jasper/runtime/PageContextImpl.java
throw ise;

              
//in java/org/apache/jasper/runtime/PageContextImpl.java
throw (IOException) ex;

              
//in java/org/apache/jasper/runtime/PageContextImpl.java
throw (ServletException) ex;

              
//in java/org/apache/jasper/runtime/PageContextImpl.java
throw (IOException) ex;

              
//in java/org/apache/jasper/runtime/PageContextImpl.java
throw (ServletException) ex;

              
//in java/org/apache/jasper/runtime/PageContextImpl.java
throw ise;

              
//in java/org/apache/jasper/runtime/PageContextImpl.java
throw (IOException) ex;

              
//in java/org/apache/jasper/runtime/PageContextImpl.java
throw (ServletException) ex;

              
//in java/org/apache/jasper/runtime/PageContextImpl.java
throw (IOException) t;

              
//in java/org/apache/jasper/runtime/PageContextImpl.java
throw (ServletException) t;

              
//in java/org/apache/jasper/runtime/PageContextImpl.java
throw (RuntimeException) t;

              
//in java/org/apache/jasper/runtime/PageContextImpl.java
throw (ELException) realEx;

              
//in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
throw (JasperException)e;

              
//in java/org/apache/jasper/compiler/Compiler.java
throw e;

              
//in java/org/apache/jasper/compiler/JspDocumentParser.java
throw e;

              
//in java/org/apache/jasper/compiler/JspDocumentParser.java
throw e;

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw compileException;

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw compileException;

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw ex;

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw fnfe;

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw ex;

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw ex;

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw ex;

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw ex;

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw ex;

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw ex;

              
//in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
//in java/org/apache/jasper/servlet/JspServlet.java
throw (ServletException)t;

              
//in java/org/apache/jasper/servlet/JspServlet.java
throw e;

              
//in java/org/apache/jasper/servlet/JspServlet.java
throw e;

              
//in java/org/apache/jasper/servlet/JspServlet.java
throw e;

              
//in java/org/apache/jasper/el/JspMethodExpression.java
throw e;

              
//in java/org/apache/jasper/el/JspMethodExpression.java
throw e;

              
//in java/org/apache/jasper/el/JspMethodExpression.java
throw e;

              
//in java/org/apache/jasper/el/JspMethodExpression.java
throw e;

              
//in java/org/apache/jasper/el/JspMethodExpression.java
throw e;

              
//in java/org/apache/jasper/el/JspMethodExpression.java
throw e;

              
//in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
//in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
//in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
//in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
//in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
//in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
//in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
//in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
//in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
//in java/org/apache/jasper/JspCompilationContext.java
throw ex;

              
//in java/org/apache/jasper/JspCompilationContext.java
throw fnfe;

              
//in java/org/apache/jasper/JspCompilationContext.java
throw je;

              
//in java/org/apache/jasper/xmlparser/ParserUtils.java
throw ex;

              
//in java/org/apache/jasper/xmlparser/ParserUtils.java
throw ex;

              
//in java/org/apache/jasper/JspC.java
throw je;

              
//in java/org/apache/jasper/JspC.java
throw je;

              
//in java/org/apache/jasper/JspC.java
throw ex;

              
//in java/org/apache/jasper/JspC.java
throw ex;

              
//in java/org/apache/jasper/util/ExceptionUtils.java
throw (ThreadDeath) t;

              
//in java/org/apache/jasper/util/ExceptionUtils.java
throw (VirtualMachineError) t;

              
//in java/org/apache/naming/factory/ResourceEnvFactory.java
throw ex;

              
//in java/org/apache/naming/factory/ResourceEnvFactory.java
throw ex;

              
//in java/org/apache/naming/factory/ResourceEnvFactory.java
throw (NamingException) t;

              
//in java/org/apache/naming/factory/ResourceEnvFactory.java
throw ex;

              
//in java/org/apache/naming/factory/BeanFactory.java
throw ne;

              
//in java/org/apache/naming/factory/BeanFactory.java
throw ne;

              
//in java/org/apache/naming/factory/BeanFactory.java
throw ne;

              
//in java/org/apache/naming/factory/BeanFactory.java
throw (ThreadDeath) cause;

              
//in java/org/apache/naming/factory/BeanFactory.java
throw (VirtualMachineError) cause;

              
//in java/org/apache/naming/factory/BeanFactory.java
throw ne;

              
//in java/org/apache/naming/factory/webservices/ServiceProxy.java
throw ite.getTargetException();

              
//in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
throw ex;

              
//in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
throw ex;

              
//in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
throw ex;

              
//in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
throw (ThreadDeath) cause;

              
//in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
throw (VirtualMachineError) cause;

              
//in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
throw ex;

              
//in java/org/apache/naming/factory/DataSourceLinkFactory.java
throw (ThreadDeath) cause;

              
//in java/org/apache/naming/factory/DataSourceLinkFactory.java
throw (VirtualMachineError) cause;

              
//in java/org/apache/naming/factory/DataSourceLinkFactory.java
throw (NamingException)x;

              
//in java/org/apache/naming/factory/DataSourceLinkFactory.java
throw nx;

              
//in java/org/apache/naming/factory/DataSourceLinkFactory.java
throw t.getCause();

              
//in java/org/apache/naming/factory/DataSourceLinkFactory.java
throw t;

              
//in java/org/apache/naming/factory/ResourceFactory.java
throw ex;

              
//in java/org/apache/naming/factory/ResourceFactory.java
throw ex;

              
//in java/org/apache/naming/factory/ResourceFactory.java
throw (NamingException) e;

              
//in java/org/apache/naming/factory/ResourceFactory.java
throw ex;

              
//in java/org/apache/naming/factory/ResourceFactory.java
throw ex;

              
//in java/org/apache/naming/factory/ResourceFactory.java
throw ex;

              
//in java/org/apache/naming/factory/EjbFactory.java
throw ex;

              
//in java/org/apache/naming/factory/EjbFactory.java
throw ex;

              
//in java/org/apache/naming/factory/EjbFactory.java
throw ex;

              
//in java/org/apache/naming/factory/EjbFactory.java
throw (NamingException) t;

              
//in java/org/apache/naming/factory/EjbFactory.java
throw ex;

              
//in java/org/apache/naming/factory/TransactionFactory.java
throw ex;

              
//in java/org/apache/naming/factory/TransactionFactory.java
throw ex;

              
//in java/org/apache/naming/factory/TransactionFactory.java
throw (NamingException) t;

              
//in java/org/apache/naming/factory/TransactionFactory.java
throw ex;

              
//in java/org/apache/naming/NamingContextBindingsEnumeration.java
throw e;

              
//in java/org/apache/naming/NamingContextBindingsEnumeration.java
throw ne;

              
//in java/org/apache/naming/NamingContext.java
throw e;

              
//in java/org/apache/naming/resources/FileDirContext.java
throw ne;

              
//in java/org/apache/naming/resources/ProxyDirContext.java
throw NOT_FOUND_EXCEPTION;

              
//in java/org/apache/naming/resources/ProxyDirContext.java
throw NOT_FOUND_EXCEPTION;

              
//in java/org/apache/naming/resources/ProxyDirContext.java
throw NOT_FOUND_EXCEPTION;

              
//in java/org/apache/naming/resources/ProxyDirContext.java
throw NOT_FOUND_EXCEPTION;

              
//in java/org/apache/naming/resources/VirtualDirContext.java
throw initialException;

              
//in java/org/apache/coyote/AbstractProtocol.java
throw ex;

              
//in java/org/apache/coyote/AbstractProtocol.java
throw ex;

              
//in java/org/apache/coyote/AbstractProtocol.java
throw ex;

              
//in java/org/apache/coyote/AbstractProtocol.java
throw ex;

              
//in java/org/apache/coyote/AbstractProtocol.java
throw ex;

              
//in java/org/apache/tomcat/jni/socket/AprSocketContext.java
throw e;

              
//in java/org/apache/tomcat/jni/socket/AprSocketContext.java
throw noApr;

              
//in java/org/apache/tomcat/jni/socket/AprSocketContext.java
throw e;

              
//in java/org/apache/tomcat/jni/socket/AprSocket.java
throw e;

              
//in java/org/apache/tomcat/jni/Library.java
throw (ThreadDeath) t;

              
//in java/org/apache/tomcat/jni/Library.java
throw (VirtualMachineError) t;

              
//in java/org/apache/tomcat/spdy/NetSupportSocket.java
throw ex;

              
//in java/org/apache/tomcat/util/net/URL.java
throw e;

              
//in java/org/apache/tomcat/util/net/SecureNioChannel.java
throw x;

              
//in java/org/apache/tomcat/util/net/SecureNioChannel.java
throw x;

              
//in java/org/apache/tomcat/util/net/NioBlockingSelector.java
throw x;

              
//in java/org/apache/tomcat/util/net/NioEndpoint.java
throw ioe;

              
//in java/org/apache/tomcat/util/net/NioEndpoint.java
throw x;

              
//in java/org/apache/tomcat/util/net/NioEndpoint.java
throw x;

              
//in java/org/apache/tomcat/util/net/AprEndpoint.java
throw e;

              
//in java/org/apache/tomcat/util/net/JIoEndpoint.java
throw ioe;

              
//in java/org/apache/tomcat/util/net/JIoEndpoint.java
throw be;

              
//in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
throw sslex;

              
//in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw ioe;

              
//in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw fnfe;

              
//in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw ioe;

              
//in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw (IOException)e;

              
//in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw iex;

              
//in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw crle;

              
//in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw ce;

              
//in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw ioe;

              
//in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
throw e;

              
//in java/org/apache/tomcat/util/http/parser/HttpParser.java
throw (RuntimeException)jjte000;

              
//in java/org/apache/tomcat/util/http/parser/HttpParser.java
throw (ParseException)jjte000;

              
//in java/org/apache/tomcat/util/http/parser/HttpParser.java
throw (Error)jjte000;

              
//in java/org/apache/tomcat/util/http/parser/HttpParser.java
throw (RuntimeException)jjte000;

              
//in java/org/apache/tomcat/util/http/parser/HttpParser.java
throw (ParseException)jjte000;

              
//in java/org/apache/tomcat/util/http/parser/HttpParser.java
throw (Error)jjte000;

              
//in java/org/apache/tomcat/util/http/parser/HttpParser.java
throw generateParseException();

              
//in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
throw (FileUploadException) e.getCause();

              
//in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
throw (FileUploadException) e.getCause();

              
//in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
throw exception;

              
//in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
throw exception;

              
//in java/org/apache/tomcat/util/buf/B2CConverter.java
throw ex;

              
//in java/org/apache/tomcat/util/buf/UDecoder.java
throw EXCEPTION_EOF;

              
//in java/org/apache/tomcat/util/buf/UDecoder.java
throw EXCEPTION_NOT_HEX_DIGIT;

              
//in java/org/apache/tomcat/util/buf/UDecoder.java
throw EXCEPTION_SLASH;

              
//in java/org/apache/tomcat/util/buf/UDecoder.java
throw EXCEPTION_EOF;

              
//in java/org/apache/tomcat/util/buf/UDecoder.java
throw EXCEPTION_NOT_HEX_DIGIT;

              
//in java/org/apache/tomcat/util/buf/UDecoder.java
throw EXCEPTION_SLASH;

              
//in java/org/apache/tomcat/util/scan/StandardJarScanner.java
throw ioe;

              
//in java/org/apache/tomcat/util/modeler/ManagedBean.java
throw e;

              
//in java/org/apache/tomcat/util/modeler/ManagedBean.java
throw e;

              
//in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsSerSource.java
throw ex;

              
//in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java
throw e;

              
//in java/org/apache/tomcat/util/modeler/Registry.java
throw t;

              
//in java/org/apache/tomcat/util/modeler/Registry.java
throw ex;

              
//in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
throw rx;

              
//in java/org/apache/tomcat/util/IntrospectionUtils.java
throw biae;

              
//in java/org/apache/tomcat/util/IntrospectionUtils.java
throw ie;

              
//in java/org/apache/tomcat/util/IntrospectionUtils.java
throw ie;

              
//in java/org/apache/tomcat/util/digester/Digester.java
throw createSAXException(e);

              
//in java/org/apache/tomcat/util/digester/Digester.java
throw e;

              
//in java/org/apache/tomcat/util/digester/Digester.java
throw createSAXException(e);

              
//in java/org/apache/tomcat/util/digester/Digester.java
throw e;

              
//in java/org/apache/tomcat/util/digester/Digester.java
throw createSAXException(e);

              
//in java/org/apache/tomcat/util/digester/Digester.java
throw e;

              
//in java/org/apache/tomcat/util/digester/Digester.java
throw createSAXException("endPrefixMapping popped too many times");

              
//in java/org/apache/tomcat/util/digester/Digester.java
throw createSAXException(e);

              
//in java/org/apache/tomcat/util/digester/Digester.java
throw e;

              
//in java/org/apache/tomcat/util/digester/Digester.java
throw createSAXException(e);

              
//in java/org/apache/tomcat/util/digester/Digester.java
throw (ThreadDeath) t;

              
//in java/org/apache/tomcat/util/digester/Digester.java
throw (VirtualMachineError) t;

              
//in java/org/apache/tomcat/util/digester/Digester.java
throw (ThreadDeath) t;

              
//in java/org/apache/tomcat/util/digester/Digester.java
throw (VirtualMachineError) t;

              
//in java/org/apache/tomcat/util/ExceptionUtils.java
throw (ThreadDeath) t;

              
//in java/org/apache/tomcat/util/ExceptionUtils.java
throw (VirtualMachineError) t;

              
//in java/org/apache/el/lang/ExpressionBuilder.java
throw (ELException) e;

              
//in java/org/apache/el/lang/ExpressionBuilder.java
throw (new ELException(e));

              
//in java/org/apache/el/parser/AstFunction.java
throw (ThreadDeath) cause;

              
//in java/org/apache/el/parser/AstFunction.java
throw (VirtualMachineError) cause;

              
//in java/org/apache/el/parser/SimpleCharStream.java
throw e;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte002;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte002;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte002;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte002;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte002;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte002;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte003;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte003;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte003;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte004;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte004;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte004;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte002;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte002;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte002;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte002;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte002;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte002;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte003;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte003;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte003;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte002;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte002;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte002;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte003;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte003;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte003;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw (Error)jjte000;

              
//in java/org/apache/el/parser/ELParser.java
throw generateParseException();

              
//in java/org/apache/el/parser/ELParser.java
throw jj_ls;

              
//in java/org/apache/el/parser/AstValue.java
throw (ThreadDeath) cause;

              
//in java/org/apache/el/parser/AstValue.java
throw (VirtualMachineError) cause;

              
//in java/org/apache/catalina/startup/CatalinaProperties.java
throw (ThreadDeath) t;

              
//in java/org/apache/catalina/startup/CatalinaProperties.java
throw (VirtualMachineError) t;

              
//in java/org/apache/catalina/startup/XmlErrorHandler.java
throw exception;

              
//in java/org/apache/catalina/startup/ExpandWar.java
throw e;

              
//in java/org/apache/catalina/startup/ExpandWar.java
throw e;

              
//in java/org/apache/catalina/startup/Bootstrap.java
throw (ThreadDeath) t;

              
//in java/org/apache/catalina/startup/Bootstrap.java
throw (VirtualMachineError) t;

              
//in java/org/apache/catalina/loader/WebappClassLoader.java
throw iae;

              
//in java/org/apache/catalina/loader/WebappClassLoader.java
throw e;

              
//in java/org/apache/catalina/loader/WebappClassLoader.java
throw cnfe;

              
//in java/org/apache/catalina/loader/WebappClassLoader.java
throw e;

              
//in java/org/apache/catalina/loader/WebappClassLoader.java
throw e;

              
//in java/org/apache/catalina/loader/WebappClassLoader.java
throw e;

              
//in java/org/apache/catalina/loader/WebappLoader.java
throw ioe;

              
//in java/org/apache/catalina/loader/WebappLoader.java
throw ioe;

              
//in java/org/apache/catalina/realm/CombinedRealm.java
throw uoe;

              
//in java/org/apache/catalina/realm/CombinedRealm.java
throw uoe;

              
//in java/org/apache/catalina/realm/JNDIRealm.java
throw ex;

              
//in java/org/apache/catalina/realm/JNDIRealm.java
throw ex;

              
//in java/org/apache/catalina/realm/JNDIRealm.java
throw ex;

              
//in java/org/apache/catalina/realm/JNDIRealm.java
throw ex;

              
//in java/org/apache/catalina/realm/JNDIRealm.java
throw ex;

              
//in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
throw new
                FailedLoginException("Username or password is incorrect");

              
//in java/org/apache/catalina/mbeans/UserMBean.java
throw iae;

              
//in java/org/apache/catalina/mbeans/UserMBean.java
throw iae;

              
//in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
//in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
//in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
//in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
//in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
//in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
//in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
//in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
//in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
//in java/org/apache/catalina/mbeans/GroupMBean.java
throw iae;

              
//in java/org/apache/catalina/mbeans/GroupMBean.java
throw iae;

              
//in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
throw iae;

              
//in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
throw iae;

              
//in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
throw iae;

              
//in java/org/apache/catalina/filters/CsrfPreventionFilter.java
throw se;

              
//in java/org/apache/catalina/filters/CsrfPreventionFilter.java
throw se;

              
//in java/org/apache/catalina/filters/CsrfPreventionFilter.java
throw se;

              
//in java/org/apache/catalina/users/MemoryUserDatabase.java
throw e;

              
//in java/org/apache/catalina/manager/ManagerServlet.java
throw e;

              
//in java/org/apache/catalina/tribes/group/GroupChannel.java
throw (ChannelException)x;

              
//in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
throw cx;

              
//in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
throw cx;

              
//in java/org/apache/catalina/tribes/group/interceptors/OrderInterceptor.java
throw cx;

              
//in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
throw x;

              
//in java/org/apache/catalina/tribes/group/interceptors/ThroughputInterceptor.java
throw x;

              
//in java/org/apache/catalina/tribes/io/ReplicationStream.java
throw cnfe;

              
//in java/org/apache/catalina/tribes/transport/bio/BioSender.java
throw exception;

              
//in java/org/apache/catalina/tribes/transport/bio/BioSender.java
throw (ex1);

              
//in java/org/apache/catalina/tribes/transport/bio/BioSender.java
throw x;

              
//in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
throw (IOException)x;

              
//in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
throw (IOException)x;

              
//in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
throw x;

              
//in java/org/apache/catalina/tribes/transport/bio/PooledMultiSender.java
throw cx;

              
//in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
throw cx;

              
//in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
throw cx;

              
//in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
throw x;

              
//in java/org/apache/catalina/tribes/transport/ReceiverBase.java
throw x;

              
//in java/org/apache/catalina/tribes/transport/ReceiverBase.java
throw x;

              
//in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
throw cx;

              
//in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
throw x;

              
//in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw cx;

              
//in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw cx;

              
//in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw cx;

              
//in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw (ChannelException)x;

              
//in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw cx;

              
//in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw cx;

              
//in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw x;

              
//in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw x;

              
//in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw cx;

              
//in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw x;

              
//in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
throw (IOException)x;

              
//in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
throw (IOException)x;

              
//in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
throw (ThreadDeath) t;

              
//in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
throw (VirtualMachineError) t;

              
//in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
throw iox;

              
//in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
throw (ThreadDeath) t;

              
//in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
throw (VirtualMachineError) t;

              
//in java/org/apache/catalina/session/StandardManager.java
throw (ClassNotFoundException)exception;

              
//in java/org/apache/catalina/session/StandardManager.java
throw (IOException)exception;

              
//in java/org/apache/catalina/session/StandardManager.java
throw e;

              
//in java/org/apache/catalina/session/StandardManager.java
throw e;

              
//in java/org/apache/catalina/session/StandardManager.java
throw e;

              
//in java/org/apache/catalina/session/StandardManager.java
throw (IOException)exception;

              
//in java/org/apache/catalina/session/StandardManager.java
throw e;

              
//in java/org/apache/catalina/session/StandardManager.java
throw e;

              
//in java/org/apache/catalina/session/FileStore.java
throw e;

              
//in java/org/apache/catalina/session/FileStore.java
throw e;

              
//in java/org/apache/catalina/session/PersistentManagerBase.java
throw (IOException)e;

              
//in java/org/apache/catalina/session/PersistentManagerBase.java
throw (ClassNotFoundException)e;

              
//in java/org/apache/catalina/session/PersistentManagerBase.java
throw (IOException) exception;

              
//in java/org/apache/catalina/session/PersistentManagerBase.java
throw e;

              
//in java/org/apache/catalina/servlets/DefaultServlet.java
throw e;

              
//in java/org/apache/catalina/servlets/DefaultServlet.java
throw exception;

              
//in java/org/apache/catalina/servlets/DefaultServlet.java
throw exception;

              
//in java/org/apache/catalina/servlets/DefaultServlet.java
throw exception;

              
//in java/org/apache/catalina/servlets/DefaultServlet.java
throw exception;

              
//in java/org/apache/catalina/servlets/CGIServlet.java
throw e;

              
//in java/org/apache/catalina/ha/backend/CollectedInfo.java
throw(new Exception("Can't find connector for " + host + ":" + port));

              
//in java/org/apache/catalina/ha/backend/CollectedInfo.java
throw(new Exception("Not initialized!!!"));

              
//in java/org/apache/catalina/ha/session/SerializablePrincipal.java
throw e;

              
//in java/org/apache/catalina/ha/session/DeltaManager.java
throw e;

              
//in java/org/apache/catalina/ha/session/DeltaManager.java
throw e;

              
//in java/org/apache/catalina/ha/session/DeltaManager.java
throw e;

              
//in java/org/apache/catalina/connector/OutputBuffer.java
throw (IOException)e;

              
//in java/org/apache/catalina/connector/Request.java
throw (IOException) partsParseException;

              
//in java/org/apache/catalina/connector/Request.java
throw (IllegalStateException) partsParseException;

              
//in java/org/apache/catalina/connector/Request.java
throw (ServletException) partsParseException;

              
//in java/org/apache/catalina/connector/Response.java
throw iae;

              
//in java/org/apache/catalina/connector/Response.java
throw iae;

              
//in java/org/apache/catalina/connector/Response.java
throw iae;

              
//in java/org/apache/catalina/connector/CoyoteInputStream.java
throw (IOException)e;

              
//in java/org/apache/catalina/connector/CoyoteInputStream.java
throw (IOException)e;

              
//in java/org/apache/catalina/connector/CoyoteInputStream.java
throw (IOException)e;

              
//in java/org/apache/catalina/connector/CoyoteInputStream.java
throw (IOException)e;

              
//in java/org/apache/catalina/connector/CoyoteInputStream.java
throw (IOException)e;

              
//in java/org/apache/catalina/connector/InputBuffer.java
throw (IOException)e;

              
//in java/org/apache/catalina/connector/ResponseFacade.java
throw (IOException)ex;

              
//in java/org/apache/catalina/core/AprLifecycleListener.java
throw e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw (ServletException) e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw (IOException) e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw (RuntimeException) e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw (ServletException) e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw (IOException) e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw (RuntimeException) e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
//in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
//in java/org/apache/catalina/core/DefaultInstanceManager.java
throw (ClassNotFoundException) t;

              
//in java/org/apache/catalina/core/AsyncContextImpl.java
throw se;

              
//in java/org/apache/catalina/core/AsyncContextImpl.java
throw se;

              
//in java/org/apache/catalina/core/AsyncContextImpl.java
throw se;

              
//in java/org/apache/catalina/core/AsyncContextImpl.java
throw se;

              
//in java/org/apache/catalina/core/AsyncContextImpl.java
throw se;

              
//in java/org/apache/catalina/core/AsyncContextImpl.java
throw (ServletException)x.getCause();

              
//in java/org/apache/catalina/core/AsyncContextImpl.java
throw (IOException)x.getCause();

              
//in java/org/apache/catalina/core/ApplicationContextFacade.java
throw (MalformedURLException)t;

              
//in java/org/apache/catalina/core/ApplicationContextFacade.java
throw (ServletException) t;

              
//in java/org/apache/catalina/core/ApplicationContextFacade.java
throw (ServletException) t;

              
//in java/org/apache/catalina/core/ApplicationContextFacade.java
throw (ServletException) t;

              
//in java/org/apache/catalina/core/ApplicationContextFacade.java
throw (ServletException) t;

              
//in java/org/apache/catalina/core/ApplicationContextFacade.java
throw realException;

              
//in java/org/apache/catalina/core/StandardWrapper.java
throw e;

              
//in java/org/apache/catalina/core/StandardWrapper.java
throw e;

              
//in java/org/apache/catalina/core/StandardWrapper.java
throw f;

              
//in java/org/apache/catalina/core/StandardWrapper.java
throw f;

              
//in java/org/apache/catalina/core/ApplicationDispatcher.java
throw (ServletException) e;

              
//in java/org/apache/catalina/core/ApplicationDispatcher.java
throw (IOException) e;

              
//in java/org/apache/catalina/core/ApplicationDispatcher.java
throw e;

              
//in java/org/apache/catalina/core/ApplicationDispatcher.java
throw (ServletException) e;

              
//in java/org/apache/catalina/core/ApplicationDispatcher.java
throw (IOException) e;

              
//in java/org/apache/catalina/core/ApplicationDispatcher.java
throw ioException;

              
//in java/org/apache/catalina/core/ApplicationDispatcher.java
throw servletException;

              
//in java/org/apache/catalina/core/ApplicationDispatcher.java
throw runtimeException;

              
//in java/org/apache/catalina/util/CustomObjectInputStream.java
throw e;

              
//in java/org/apache/catalina/security/SecurityUtil.java
throw (UnavailableException) e;

              
//in java/org/apache/catalina/security/SecurityUtil.java
throw (ServletException) e;

              
//in java/org/apache/catalina/security/SecurityUtil.java
throw (IOException) e;

              
//in java/org/apache/catalina/security/SecurityUtil.java
throw (RuntimeException) e;

              
//in java/javax/el/ExpressionFactory.java
throw (ThreadDeath) cause;

              
//in java/javax/el/ExpressionFactory.java
throw (VirtualMachineError) cause;

              
//in java/javax/el/BeanELResolver.java
throw (ThreadDeath) cause;

              
//in java/javax/el/BeanELResolver.java
throw (VirtualMachineError) cause;

              
//in java/javax/el/BeanELResolver.java
throw (ThreadDeath) cause;

              
//in java/javax/el/BeanELResolver.java
throw (VirtualMachineError) cause;

              
//in java/javax/el/BeanELResolver.java
throw (ThreadDeath) cause;

              
//in java/javax/el/BeanELResolver.java
throw (VirtualMachineError) cause;

            
- -
- Builder 26
              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw handleJspException(ex);

              
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
throw ite.getTargetException();

              
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
throw t.getCause();

              
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
throw generateParseException();

              
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
throw (FileUploadException) e.getCause();

              
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
throw (FileUploadException) e.getCause();

              
// in java/org/apache/tomcat/util/digester/Digester.java
throw createSAXException(e);

              
// in java/org/apache/tomcat/util/digester/Digester.java
throw createSAXException(e);

              
// in java/org/apache/tomcat/util/digester/Digester.java
throw createSAXException(e);

              
// in java/org/apache/tomcat/util/digester/Digester.java
throw createSAXException("endPrefixMapping popped too many times");

              
// in java/org/apache/tomcat/util/digester/Digester.java
throw createSAXException(e);

              
// in java/org/apache/tomcat/util/digester/Digester.java
throw createSAXException(e);

              
// in java/org/apache/el/lang/ExpressionBuilder.java
throw (new ELException(e));

              
// in java/org/apache/el/parser/ELParser.java
throw generateParseException();

              
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
throw new
                FailedLoginException("Username or password is incorrect");

              
// in java/org/apache/catalina/ha/backend/CollectedInfo.java
throw(new Exception("Can't find connector for " + host + ":" + port));

              
// in java/org/apache/catalina/ha/backend/CollectedInfo.java
throw(new Exception("Not initialized!!!"));

              
// in java/org/apache/catalina/core/AsyncContextImpl.java
throw (ServletException)x.getCause();

              
// in java/org/apache/catalina/core/AsyncContextImpl.java
throw (IOException)x.getCause();

            
- -
- Variable 427
              
// in java/org/apache/jasper/runtime/PageContextImpl.java
throw ise;

              
// in java/org/apache/jasper/runtime/PageContextImpl.java
throw (IOException) ex;

              
// in java/org/apache/jasper/runtime/PageContextImpl.java
throw (ServletException) ex;

              
// in java/org/apache/jasper/runtime/PageContextImpl.java
throw (IOException) ex;

              
// in java/org/apache/jasper/runtime/PageContextImpl.java
throw (ServletException) ex;

              
// in java/org/apache/jasper/runtime/PageContextImpl.java
throw ise;

              
// in java/org/apache/jasper/runtime/PageContextImpl.java
throw (IOException) ex;

              
// in java/org/apache/jasper/runtime/PageContextImpl.java
throw (ServletException) ex;

              
// in java/org/apache/jasper/runtime/PageContextImpl.java
throw (IOException) t;

              
// in java/org/apache/jasper/runtime/PageContextImpl.java
throw (ServletException) t;

              
// in java/org/apache/jasper/runtime/PageContextImpl.java
throw (RuntimeException) t;

              
// in java/org/apache/jasper/runtime/PageContextImpl.java
throw (ELException) realEx;

              
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
throw (JasperException)e;

              
// in java/org/apache/jasper/compiler/Compiler.java
throw e;

              
// in java/org/apache/jasper/compiler/JspDocumentParser.java
throw e;

              
// in java/org/apache/jasper/compiler/JspDocumentParser.java
throw e;

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw compileException;

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw compileException;

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw ex;

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw fnfe;

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw ex;

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw ex;

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw ex;

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw ex;

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw ex;

              
// in java/org/apache/jasper/servlet/JspServletWrapper.java
throw ex;

              
// in java/org/apache/jasper/servlet/JspServlet.java
throw (ServletException)t;

              
// in java/org/apache/jasper/servlet/JspServlet.java
throw e;

              
// in java/org/apache/jasper/servlet/JspServlet.java
throw e;

              
// in java/org/apache/jasper/servlet/JspServlet.java
throw e;

              
// in java/org/apache/jasper/el/JspMethodExpression.java
throw e;

              
// in java/org/apache/jasper/el/JspMethodExpression.java
throw e;

              
// in java/org/apache/jasper/el/JspMethodExpression.java
throw e;

              
// in java/org/apache/jasper/el/JspMethodExpression.java
throw e;

              
// in java/org/apache/jasper/el/JspMethodExpression.java
throw e;

              
// in java/org/apache/jasper/el/JspMethodExpression.java
throw e;

              
// in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
// in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
// in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
// in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
// in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
// in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
// in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
// in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
// in java/org/apache/jasper/el/JspValueExpression.java
throw e;

              
// in java/org/apache/jasper/JspCompilationContext.java
throw ex;

              
// in java/org/apache/jasper/JspCompilationContext.java
throw fnfe;

              
// in java/org/apache/jasper/JspCompilationContext.java
throw je;

              
// in java/org/apache/jasper/xmlparser/ParserUtils.java
throw ex;

              
// in java/org/apache/jasper/xmlparser/ParserUtils.java
throw ex;

              
// in java/org/apache/jasper/JspC.java
throw je;

              
// in java/org/apache/jasper/JspC.java
throw je;

              
// in java/org/apache/jasper/JspC.java
throw ex;

              
// in java/org/apache/jasper/JspC.java
throw ex;

              
// in java/org/apache/jasper/util/ExceptionUtils.java
throw (ThreadDeath) t;

              
// in java/org/apache/jasper/util/ExceptionUtils.java
throw (VirtualMachineError) t;

              
// in java/org/apache/naming/factory/ResourceEnvFactory.java
throw ex;

              
// in java/org/apache/naming/factory/ResourceEnvFactory.java
throw ex;

              
// in java/org/apache/naming/factory/ResourceEnvFactory.java
throw (NamingException) t;

              
// in java/org/apache/naming/factory/ResourceEnvFactory.java
throw ex;

              
// in java/org/apache/naming/factory/BeanFactory.java
throw ne;

              
// in java/org/apache/naming/factory/BeanFactory.java
throw ne;

              
// in java/org/apache/naming/factory/BeanFactory.java
throw ne;

              
// in java/org/apache/naming/factory/BeanFactory.java
throw (ThreadDeath) cause;

              
// in java/org/apache/naming/factory/BeanFactory.java
throw (VirtualMachineError) cause;

              
// in java/org/apache/naming/factory/BeanFactory.java
throw ne;

              
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
throw ex;

              
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
throw ex;

              
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
throw ex;

              
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
throw (ThreadDeath) cause;

              
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
throw (VirtualMachineError) cause;

              
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
throw ex;

              
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
throw (ThreadDeath) cause;

              
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
throw (VirtualMachineError) cause;

              
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
throw (NamingException)x;

              
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
throw nx;

              
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
throw t;

              
// in java/org/apache/naming/factory/ResourceFactory.java
throw ex;

              
// in java/org/apache/naming/factory/ResourceFactory.java
throw ex;

              
// in java/org/apache/naming/factory/ResourceFactory.java
throw (NamingException) e;

              
// in java/org/apache/naming/factory/ResourceFactory.java
throw ex;

              
// in java/org/apache/naming/factory/ResourceFactory.java
throw ex;

              
// in java/org/apache/naming/factory/ResourceFactory.java
throw ex;

              
// in java/org/apache/naming/factory/EjbFactory.java
throw ex;

              
// in java/org/apache/naming/factory/EjbFactory.java
throw ex;

              
// in java/org/apache/naming/factory/EjbFactory.java
throw ex;

              
// in java/org/apache/naming/factory/EjbFactory.java
throw (NamingException) t;

              
// in java/org/apache/naming/factory/EjbFactory.java
throw ex;

              
// in java/org/apache/naming/factory/TransactionFactory.java
throw ex;

              
// in java/org/apache/naming/factory/TransactionFactory.java
throw ex;

              
// in java/org/apache/naming/factory/TransactionFactory.java
throw (NamingException) t;

              
// in java/org/apache/naming/factory/TransactionFactory.java
throw ex;

              
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
throw e;

              
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
throw ne;

              
// in java/org/apache/naming/NamingContext.java
throw e;

              
// in java/org/apache/naming/resources/FileDirContext.java
throw ne;

              
// in java/org/apache/naming/resources/ProxyDirContext.java
throw NOT_FOUND_EXCEPTION;

              
// in java/org/apache/naming/resources/ProxyDirContext.java
throw NOT_FOUND_EXCEPTION;

              
// in java/org/apache/naming/resources/ProxyDirContext.java
throw NOT_FOUND_EXCEPTION;

              
// in java/org/apache/naming/resources/ProxyDirContext.java
throw NOT_FOUND_EXCEPTION;

              
// in java/org/apache/naming/resources/VirtualDirContext.java
throw initialException;

              
// in java/org/apache/coyote/AbstractProtocol.java
throw ex;

              
// in java/org/apache/coyote/AbstractProtocol.java
throw ex;

              
// in java/org/apache/coyote/AbstractProtocol.java
throw ex;

              
// in java/org/apache/coyote/AbstractProtocol.java
throw ex;

              
// in java/org/apache/coyote/AbstractProtocol.java
throw ex;

              
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
throw e;

              
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
throw noApr;

              
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
throw e;

              
// in java/org/apache/tomcat/jni/socket/AprSocket.java
throw e;

              
// in java/org/apache/tomcat/jni/Library.java
throw (ThreadDeath) t;

              
// in java/org/apache/tomcat/jni/Library.java
throw (VirtualMachineError) t;

              
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
throw ex;

              
// in java/org/apache/tomcat/util/net/URL.java
throw e;

              
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
throw x;

              
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
throw x;

              
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
throw x;

              
// in java/org/apache/tomcat/util/net/NioEndpoint.java
throw ioe;

              
// in java/org/apache/tomcat/util/net/NioEndpoint.java
throw x;

              
// in java/org/apache/tomcat/util/net/NioEndpoint.java
throw x;

              
// in java/org/apache/tomcat/util/net/AprEndpoint.java
throw e;

              
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
throw ioe;

              
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
throw be;

              
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
throw sslex;

              
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw ioe;

              
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw fnfe;

              
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw ioe;

              
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw (IOException)e;

              
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw iex;

              
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw crle;

              
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw ce;

              
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
throw ioe;

              
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
throw e;

              
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
throw (RuntimeException)jjte000;

              
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
throw (ParseException)jjte000;

              
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
throw (Error)jjte000;

              
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
throw (RuntimeException)jjte000;

              
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
throw (ParseException)jjte000;

              
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
throw (Error)jjte000;

              
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
throw (FileUploadException) e.getCause();

              
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
throw (FileUploadException) e.getCause();

              
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
throw exception;

              
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
throw exception;

              
// in java/org/apache/tomcat/util/buf/B2CConverter.java
throw ex;

              
// in java/org/apache/tomcat/util/buf/UDecoder.java
throw EXCEPTION_EOF;

              
// in java/org/apache/tomcat/util/buf/UDecoder.java
throw EXCEPTION_NOT_HEX_DIGIT;

              
// in java/org/apache/tomcat/util/buf/UDecoder.java
throw EXCEPTION_SLASH;

              
// in java/org/apache/tomcat/util/buf/UDecoder.java
throw EXCEPTION_EOF;

              
// in java/org/apache/tomcat/util/buf/UDecoder.java
throw EXCEPTION_NOT_HEX_DIGIT;

              
// in java/org/apache/tomcat/util/buf/UDecoder.java
throw EXCEPTION_SLASH;

              
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
throw ioe;

              
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
throw e;

              
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
throw e;

              
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsSerSource.java
throw ex;

              
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java
throw e;

              
// in java/org/apache/tomcat/util/modeler/Registry.java
throw t;

              
// in java/org/apache/tomcat/util/modeler/Registry.java
throw ex;

              
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
throw rx;

              
// in java/org/apache/tomcat/util/IntrospectionUtils.java
throw biae;

              
// in java/org/apache/tomcat/util/IntrospectionUtils.java
throw ie;

              
// in java/org/apache/tomcat/util/IntrospectionUtils.java
throw ie;

              
// in java/org/apache/tomcat/util/digester/Digester.java
throw e;

              
// in java/org/apache/tomcat/util/digester/Digester.java
throw e;

              
// in java/org/apache/tomcat/util/digester/Digester.java
throw e;

              
// in java/org/apache/tomcat/util/digester/Digester.java
throw e;

              
// in java/org/apache/tomcat/util/digester/Digester.java
throw (ThreadDeath) t;

              
// in java/org/apache/tomcat/util/digester/Digester.java
throw (VirtualMachineError) t;

              
// in java/org/apache/tomcat/util/digester/Digester.java
throw (ThreadDeath) t;

              
// in java/org/apache/tomcat/util/digester/Digester.java
throw (VirtualMachineError) t;

              
// in java/org/apache/tomcat/util/ExceptionUtils.java
throw (ThreadDeath) t;

              
// in java/org/apache/tomcat/util/ExceptionUtils.java
throw (VirtualMachineError) t;

              
// in java/org/apache/el/lang/ExpressionBuilder.java
throw (ELException) e;

              
// in java/org/apache/el/parser/AstFunction.java
throw (ThreadDeath) cause;

              
// in java/org/apache/el/parser/AstFunction.java
throw (VirtualMachineError) cause;

              
// in java/org/apache/el/parser/SimpleCharStream.java
throw e;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte002;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte002;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte002;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte002;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte002;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte002;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte003;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte003;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte003;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte004;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte004;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte004;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte002;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte002;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte002;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte002;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte002;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte002;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte003;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte003;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte003;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte002;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte002;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte002;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte003;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte003;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte003;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte001;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (RuntimeException)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (ParseException)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw (Error)jjte000;

              
// in java/org/apache/el/parser/ELParser.java
throw jj_ls;

              
// in java/org/apache/el/parser/AstValue.java
throw (ThreadDeath) cause;

              
// in java/org/apache/el/parser/AstValue.java
throw (VirtualMachineError) cause;

              
// in java/org/apache/catalina/startup/CatalinaProperties.java
throw (ThreadDeath) t;

              
// in java/org/apache/catalina/startup/CatalinaProperties.java
throw (VirtualMachineError) t;

              
// in java/org/apache/catalina/startup/XmlErrorHandler.java
throw exception;

              
// in java/org/apache/catalina/startup/ExpandWar.java
throw e;

              
// in java/org/apache/catalina/startup/ExpandWar.java
throw e;

              
// in java/org/apache/catalina/startup/Bootstrap.java
throw (ThreadDeath) t;

              
// in java/org/apache/catalina/startup/Bootstrap.java
throw (VirtualMachineError) t;

              
// in java/org/apache/catalina/loader/WebappClassLoader.java
throw iae;

              
// in java/org/apache/catalina/loader/WebappClassLoader.java
throw e;

              
// in java/org/apache/catalina/loader/WebappClassLoader.java
throw cnfe;

              
// in java/org/apache/catalina/loader/WebappClassLoader.java
throw e;

              
// in java/org/apache/catalina/loader/WebappClassLoader.java
throw e;

              
// in java/org/apache/catalina/loader/WebappClassLoader.java
throw e;

              
// in java/org/apache/catalina/loader/WebappLoader.java
throw ioe;

              
// in java/org/apache/catalina/loader/WebappLoader.java
throw ioe;

              
// in java/org/apache/catalina/realm/CombinedRealm.java
throw uoe;

              
// in java/org/apache/catalina/realm/CombinedRealm.java
throw uoe;

              
// in java/org/apache/catalina/realm/JNDIRealm.java
throw ex;

              
// in java/org/apache/catalina/realm/JNDIRealm.java
throw ex;

              
// in java/org/apache/catalina/realm/JNDIRealm.java
throw ex;

              
// in java/org/apache/catalina/realm/JNDIRealm.java
throw ex;

              
// in java/org/apache/catalina/realm/JNDIRealm.java
throw ex;

              
// in java/org/apache/catalina/mbeans/UserMBean.java
throw iae;

              
// in java/org/apache/catalina/mbeans/UserMBean.java
throw iae;

              
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
throw iae;

              
// in java/org/apache/catalina/mbeans/GroupMBean.java
throw iae;

              
// in java/org/apache/catalina/mbeans/GroupMBean.java
throw iae;

              
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
throw iae;

              
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
throw iae;

              
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
throw iae;

              
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
throw se;

              
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
throw se;

              
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
throw se;

              
// in java/org/apache/catalina/users/MemoryUserDatabase.java
throw e;

              
// in java/org/apache/catalina/manager/ManagerServlet.java
throw e;

              
// in java/org/apache/catalina/tribes/group/GroupChannel.java
throw (ChannelException)x;

              
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
throw cx;

              
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
throw cx;

              
// in java/org/apache/catalina/tribes/group/interceptors/OrderInterceptor.java
throw cx;

              
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
throw x;

              
// in java/org/apache/catalina/tribes/group/interceptors/ThroughputInterceptor.java
throw x;

              
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
throw cnfe;

              
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
throw exception;

              
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
throw (ex1);

              
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
throw x;

              
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
throw (IOException)x;

              
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
throw (IOException)x;

              
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
throw x;

              
// in java/org/apache/catalina/tribes/transport/bio/PooledMultiSender.java
throw cx;

              
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
throw cx;

              
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
throw cx;

              
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
throw x;

              
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
throw x;

              
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
throw x;

              
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
throw cx;

              
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
throw x;

              
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw cx;

              
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw cx;

              
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw cx;

              
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw (ChannelException)x;

              
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw cx;

              
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw cx;

              
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw x;

              
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw x;

              
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw cx;

              
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
throw x;

              
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
throw (IOException)x;

              
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
throw (IOException)x;

              
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
throw (ThreadDeath) t;

              
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
throw (VirtualMachineError) t;

              
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
throw iox;

              
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
throw (ThreadDeath) t;

              
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
throw (VirtualMachineError) t;

              
// in java/org/apache/catalina/session/StandardManager.java
throw (ClassNotFoundException)exception;

              
// in java/org/apache/catalina/session/StandardManager.java
throw (IOException)exception;

              
// in java/org/apache/catalina/session/StandardManager.java
throw e;

              
// in java/org/apache/catalina/session/StandardManager.java
throw e;

              
// in java/org/apache/catalina/session/StandardManager.java
throw e;

              
// in java/org/apache/catalina/session/StandardManager.java
throw (IOException)exception;

              
// in java/org/apache/catalina/session/StandardManager.java
throw e;

              
// in java/org/apache/catalina/session/StandardManager.java
throw e;

              
// in java/org/apache/catalina/session/FileStore.java
throw e;

              
// in java/org/apache/catalina/session/FileStore.java
throw e;

              
// in java/org/apache/catalina/session/PersistentManagerBase.java
throw (IOException)e;

              
// in java/org/apache/catalina/session/PersistentManagerBase.java
throw (ClassNotFoundException)e;

              
// in java/org/apache/catalina/session/PersistentManagerBase.java
throw (IOException) exception;

              
// in java/org/apache/catalina/session/PersistentManagerBase.java
throw e;

              
// in java/org/apache/catalina/servlets/DefaultServlet.java
throw e;

              
// in java/org/apache/catalina/servlets/DefaultServlet.java
throw exception;

              
// in java/org/apache/catalina/servlets/DefaultServlet.java
throw exception;

              
// in java/org/apache/catalina/servlets/DefaultServlet.java
throw exception;

              
// in java/org/apache/catalina/servlets/DefaultServlet.java
throw exception;

              
// in java/org/apache/catalina/servlets/CGIServlet.java
throw e;

              
// in java/org/apache/catalina/ha/session/SerializablePrincipal.java
throw e;

              
// in java/org/apache/catalina/ha/session/DeltaManager.java
throw e;

              
// in java/org/apache/catalina/ha/session/DeltaManager.java
throw e;

              
// in java/org/apache/catalina/ha/session/DeltaManager.java
throw e;

              
// in java/org/apache/catalina/connector/OutputBuffer.java
throw (IOException)e;

              
// in java/org/apache/catalina/connector/Request.java
throw (IOException) partsParseException;

              
// in java/org/apache/catalina/connector/Request.java
throw (IllegalStateException) partsParseException;

              
// in java/org/apache/catalina/connector/Request.java
throw (ServletException) partsParseException;

              
// in java/org/apache/catalina/connector/Response.java
throw iae;

              
// in java/org/apache/catalina/connector/Response.java
throw iae;

              
// in java/org/apache/catalina/connector/Response.java
throw iae;

              
// in java/org/apache/catalina/connector/CoyoteInputStream.java
throw (IOException)e;

              
// in java/org/apache/catalina/connector/CoyoteInputStream.java
throw (IOException)e;

              
// in java/org/apache/catalina/connector/CoyoteInputStream.java
throw (IOException)e;

              
// in java/org/apache/catalina/connector/CoyoteInputStream.java
throw (IOException)e;

              
// in java/org/apache/catalina/connector/CoyoteInputStream.java
throw (IOException)e;

              
// in java/org/apache/catalina/connector/InputBuffer.java
throw (IOException)e;

              
// in java/org/apache/catalina/connector/ResponseFacade.java
throw (IOException)ex;

              
// in java/org/apache/catalina/core/AprLifecycleListener.java
throw e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw (ServletException) e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw (IOException) e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw (RuntimeException) e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw (ServletException) e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw (IOException) e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw (RuntimeException) e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
// in java/org/apache/catalina/core/ApplicationFilterChain.java
throw e;

              
// in java/org/apache/catalina/core/DefaultInstanceManager.java
throw (ClassNotFoundException) t;

              
// in java/org/apache/catalina/core/AsyncContextImpl.java
throw se;

              
// in java/org/apache/catalina/core/AsyncContextImpl.java
throw se;

              
// in java/org/apache/catalina/core/AsyncContextImpl.java
throw se;

              
// in java/org/apache/catalina/core/AsyncContextImpl.java
throw se;

              
// in java/org/apache/catalina/core/AsyncContextImpl.java
throw se;

              
// in java/org/apache/catalina/core/AsyncContextImpl.java
throw (ServletException)x.getCause();

              
// in java/org/apache/catalina/core/AsyncContextImpl.java
throw (IOException)x.getCause();

              
// in java/org/apache/catalina/core/ApplicationContextFacade.java
throw (MalformedURLException)t;

              
// in java/org/apache/catalina/core/ApplicationContextFacade.java
throw (ServletException) t;

              
// in java/org/apache/catalina/core/ApplicationContextFacade.java
throw (ServletException) t;

              
// in java/org/apache/catalina/core/ApplicationContextFacade.java
throw (ServletException) t;

              
// in java/org/apache/catalina/core/ApplicationContextFacade.java
throw (ServletException) t;

              
// in java/org/apache/catalina/core/ApplicationContextFacade.java
throw realException;

              
// in java/org/apache/catalina/core/StandardWrapper.java
throw e;

              
// in java/org/apache/catalina/core/StandardWrapper.java
throw e;

              
// in java/org/apache/catalina/core/StandardWrapper.java
throw f;

              
// in java/org/apache/catalina/core/StandardWrapper.java
throw f;

              
// in java/org/apache/catalina/core/ApplicationDispatcher.java
throw (ServletException) e;

              
// in java/org/apache/catalina/core/ApplicationDispatcher.java
throw (IOException) e;

              
// in java/org/apache/catalina/core/ApplicationDispatcher.java
throw e;

              
// in java/org/apache/catalina/core/ApplicationDispatcher.java
throw (ServletException) e;

              
// in java/org/apache/catalina/core/ApplicationDispatcher.java
throw (IOException) e;

              
// in java/org/apache/catalina/core/ApplicationDispatcher.java
throw ioException;

              
// in java/org/apache/catalina/core/ApplicationDispatcher.java
throw servletException;

              
// in java/org/apache/catalina/core/ApplicationDispatcher.java
throw runtimeException;

              
// in java/org/apache/catalina/util/CustomObjectInputStream.java
throw e;

              
// in java/org/apache/catalina/security/SecurityUtil.java
throw (UnavailableException) e;

              
// in java/org/apache/catalina/security/SecurityUtil.java
throw (ServletException) e;

              
// in java/org/apache/catalina/security/SecurityUtil.java
throw (IOException) e;

              
// in java/org/apache/catalina/security/SecurityUtil.java
throw (RuntimeException) e;

              
// in java/javax/el/ExpressionFactory.java
throw (ThreadDeath) cause;

              
// in java/javax/el/ExpressionFactory.java
throw (VirtualMachineError) cause;

              
// in java/javax/el/BeanELResolver.java
throw (ThreadDeath) cause;

              
// in java/javax/el/BeanELResolver.java
throw (VirtualMachineError) cause;

              
// in java/javax/el/BeanELResolver.java
throw (ThreadDeath) cause;

              
// in java/javax/el/BeanELResolver.java
throw (VirtualMachineError) cause;

              
// in java/javax/el/BeanELResolver.java
throw (ThreadDeath) cause;

              
// in java/javax/el/BeanELResolver.java
throw (VirtualMachineError) cause;

            
- -
(Lib) IllegalArgumentException 226
              
// in java/org/apache/jasper/runtime/PageContextImpl.java
private Object doGetAttribute(String name, int scope) { switch (scope) { case PAGE_SCOPE: return attributes.get(name); case REQUEST_SCOPE: return request.getAttribute(name); case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } return session.getAttribute(name); case APPLICATION_SCOPE: return context.getAttribute(name); default: throw new IllegalArgumentException("Invalid scope"); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doSetAttribute(String name, Object o, int scope) { if (o != null) { switch (scope) { case PAGE_SCOPE: attributes.put(name, o); break; case REQUEST_SCOPE: request.setAttribute(name, o); break; case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } session.setAttribute(name, o); break; case APPLICATION_SCOPE: context.setAttribute(name, o); break; default: throw new IllegalArgumentException("Invalid scope"); } } else { removeAttribute(name, scope); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doRemoveAttribute(String name, int scope) { switch (scope) { case PAGE_SCOPE: attributes.remove(name); break; case REQUEST_SCOPE: request.removeAttribute(name); break; case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } session.removeAttribute(name); break; case APPLICATION_SCOPE: context.removeAttribute(name); break; default: throw new IllegalArgumentException("Invalid scope"); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private Enumeration<String> doGetAttributeNamesInScope(int scope) { switch (scope) { case PAGE_SCOPE: return Collections.enumeration(attributes.keySet()); case REQUEST_SCOPE: return request.getAttributeNames(); case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } return session.getAttributeNames(); case APPLICATION_SCOPE: return context.getAttributeNames(); default: throw new IllegalArgumentException("Invalid scope"); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object getValueFromPropertyEditorManager( Class<?> attrClass, String attrName, String attrValue) throws JasperException { try { PropertyEditor propEditor = PropertyEditorManager.findEditor(attrClass); if (propEditor != null) { propEditor.setAsText(attrValue); return propEditor.getValue(); } else { throw new IllegalArgumentException( Localizer.getMessage("jsp.error.beans.propertyeditor.notregistered")); } } catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); } }
// in java/org/apache/jasper/runtime/JspApplicationContextImpl.java
Override public void addELContextListener(ELContextListener listener) { if (listener == null) { throw new IllegalArgumentException("ELConextListener was null"); } this.contextListeners.add(listener); }
// in java/org/apache/jasper/runtime/JspApplicationContextImpl.java
public static JspApplicationContextImpl getInstance(ServletContext context) { if (context == null) { throw new IllegalArgumentException("ServletContext was null"); } JspApplicationContextImpl impl = (JspApplicationContextImpl) context .getAttribute(KEY); if (impl == null) { impl = new JspApplicationContextImpl(); context.setAttribute(KEY, impl); } return impl; }
// in java/org/apache/jasper/runtime/JspApplicationContextImpl.java
public ELContextImpl createELContext(JspContext context) { if (context == null) { throw new IllegalArgumentException("JspContext was null"); } // create ELContext for JspContext final ELResolver r = this.createELResolver(); ELContextImpl ctx; if (Constants.IS_SECURITY_ENABLED) { ctx = AccessController.doPrivileged( new PrivilegedAction<ELContextImpl>() { @Override public ELContextImpl run() { return new ELContextImpl(r); } }); }
// in java/org/apache/jasper/runtime/JspApplicationContextImpl.java
Override public void addELResolver(ELResolver resolver) throws IllegalStateException { if (resolver == null) { throw new IllegalArgumentException("ELResolver was null"); } if (this.instantiated) { throw new IllegalStateException( "cannot call addELResolver after the first request has been made"); } this.resolvers.add(resolver); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
public static synchronized TldLocationsCache getInstance( ServletContext ctxt) { if (ctxt == null) { throw new IllegalArgumentException("ServletContext was null"); } TldLocationsCache cache = (TldLocationsCache) ctxt.getAttribute(KEY); if (cache == null) { cache = new TldLocationsCache(ctxt); ctxt.setAttribute(KEY, cache); } return cache; }
// in java/org/apache/jasper/compiler/SmapStratum.java
public void setInputStartLine(int inputStartLine) { if (inputStartLine < 0) throw new IllegalArgumentException("" + inputStartLine); this.inputStartLine = inputStartLine; }
// in java/org/apache/jasper/compiler/SmapStratum.java
public void setOutputStartLine(int outputStartLine) { if (outputStartLine < 0) throw new IllegalArgumentException("" + outputStartLine); this.outputStartLine = outputStartLine; }
// in java/org/apache/jasper/compiler/SmapStratum.java
public void setLineFileID(int lineFileID) { if (lineFileID < 0) throw new IllegalArgumentException("" + lineFileID); this.lineFileID = lineFileID; this.lineFileIDSet = true; }
// in java/org/apache/jasper/compiler/SmapStratum.java
public void setInputLineCount(int inputLineCount) { if (inputLineCount < 0) throw new IllegalArgumentException("" + inputLineCount); this.inputLineCount = inputLineCount; }
// in java/org/apache/jasper/compiler/SmapStratum.java
public void setOutputLineIncrement(int outputLineIncrement) { if (outputLineIncrement < 0) throw new IllegalArgumentException("" + outputLineIncrement); this.outputLineIncrement = outputLineIncrement; }
// in java/org/apache/jasper/compiler/SmapStratum.java
public void addLineData( int inputStartLine, String inputFileName, int inputLineCount, int outputStartLine, int outputLineIncrement) { // check the input - what are you doing here?? int fileIndex = filePathList.indexOf(inputFileName); if (fileIndex == -1) // still throw new IllegalArgumentException( "inputFileName: " + inputFileName); //Jasper incorrectly SMAPs certain Nodes, giving them an //outputStartLine of 0. This can cause a fatal error in //optimizeLineSection, making it impossible for Jasper to //compile the JSP. Until we can fix the underlying //SMAPping problem, we simply ignore the flawed SMAP entries. if (outputStartLine == 0) return; // build the LineInfo LineInfo li = new LineInfo(); li.setInputStartLine(inputStartLine); li.setInputLineCount(inputLineCount); li.setOutputStartLine(outputStartLine); li.setOutputLineIncrement(outputLineIncrement); if (fileIndex != lastFileID) li.setLineFileID(fileIndex); lastFileID = fileIndex; // save it lineData.add(li); }
// in java/org/apache/jasper/compiler/AttributeParser.java
private char nextChar() { lastChEscaped = false; char ch = input.charAt(i); if (ch == '&') { if (i + 5 < size && input.charAt(i + 1) == 'a' && input.charAt(i + 2) == 'p' && input.charAt(i + 3) == 'o' && input.charAt(i + 4) == 's' && input.charAt(i + 5) == ';') { ch = '\''; i += 6; } else if (i + 5 < size && input.charAt(i + 1) == 'q' && input.charAt(i + 2) == 'u' && input.charAt(i + 3) == 'o' && input.charAt(i + 4) == 't' && input.charAt(i + 5) == ';') { ch = '\"'; i += 6; } else { ++i; } } else if (ch == '\\' && i + 1 < size) { ch = input.charAt(i + 1); if (ch == '\\' || ch == '\"' || ch == '\'' || (!isELIgnored && (ch == '$' || (!isDeferredSyntaxAllowedAsLiteral && ch == '#')))) { i += 2; lastChEscaped = true; } else { ch = '\\'; ++i; } } else if (ch == '<' && (i + 2 < size) && input.charAt(i + 1) == '\\' && input.charAt(i + 2) == '%') { // Note this is a hack since nextChar only returns a single char // It is safe since <% does not require special treatment for EL // or for literals result.append('<'); i+=3; return '%'; } else if (ch == '%' && i + 2 < size && input.charAt(i + 1) == '\\' && input.charAt(i + 2) == '>') { // Note this is a hack since nextChar only returns a single char // It is safe since %> does not require special treatment for EL // or for literals result.append('%'); i+=3; return '>'; } else if (ch == quote && strict) { String msg = Localizer.getMessage("jsp.error.attribute.noescape", input, ""+ quote); throw new IllegalArgumentException(msg); } else { ++i; } return ch; }
// in java/org/apache/jasper/util/UniqueAttributesImpl.java
private void handleDuplicate(String qName, String value) { if (pageDirective) { if (IMPORT.equalsIgnoreCase(qName)) { // Always merge imports int i = super.getIndex(IMPORT); String v = super.getValue(i); super.setValue(i, v + "," + value); return; } else if (PAGE_ENCODING.equalsIgnoreCase(qName)) { // Page encoding can only occur once per file so a second // attribute - even one with a duplicate value - is an error } else { // Other attributes can be repeated if and only if the values // are identical String v = super.getValue(qName); if (v.equals(value)) { return; } } } // Ordinary tag attributes can't be repeated, even with identical values throw new IllegalArgumentException( Localizer.getMessage("jsp.error.duplicateqname", qName)); }
// in java/org/apache/naming/StringManager.java
public String getString(String key) { if(key == null){ String msg = "key may not have a null value"; throw new IllegalArgumentException(msg); } String str = null; try { str = bundle.getString(key); } catch(MissingResourceException mre) { //bad: shouldn't mask an exception the following way: // str = "[cannot find message associated with key '" + key + "' due to " + mre + "]"; // because it hides the fact that the String was missing // from the calling code. //good: could just throw the exception (or wrap it in another) // but that would probably cause much havoc on existing // code. //better: consistent with container pattern to // simply return null. Calling code can then do // a null check. str = null; } return str; }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void setDocBase(String docBase) { // Validate the format of the proposed document root if (docBase == null) throw new IllegalArgumentException (sm.getString("resources.null")); if (!(docBase.endsWith(".war"))) throw new IllegalArgumentException (sm.getString("warResources.notWar")); // Calculate a File object referencing this document base directory File base = new File(docBase); // Validate that the document base is an existing directory if (!base.exists() || !base.canRead() || base.isDirectory()) throw new IllegalArgumentException (sm.getString("warResources.invalidWar", docBase)); try { this.base = new ZipFile(base); } catch (Exception e) { throw new IllegalArgumentException (sm.getString("warResources.invalidWar", e.getMessage())); } super.setDocBase(docBase); loadEntries(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void setDocBase(String docBase) { // Validate the format of the proposed document root if (docBase == null) throw new IllegalArgumentException (sm.getString("resources.null")); // Calculate a File object referencing this document base directory base = new File(docBase); try { base = base.getCanonicalFile(); } catch (IOException e) { // Ignore } // Validate that the document base is an existing directory if (!base.exists() || !base.isDirectory() || !base.canRead()) throw new IllegalArgumentException (sm.getString("fileResources.base", docBase)); this.absoluteBase = base.getAbsolutePath(); super.setDocBase(docBase); }
// in java/org/apache/naming/resources/BaseDirContext.java
public void addAlias(String path, BaseDirContext dirContext) { if (!path.startsWith("/")) { throw new IllegalArgumentException( sm.getString("resources.invalidAliasPath", path)); } aliases.put(path, dirContext); }
// in java/org/apache/naming/resources/BaseDirContext.java
public void removeAlias(String path) { if (!path.startsWith("/")) { throw new IllegalArgumentException( sm.getString("resources.invalidAliasPath", path)); } aliases.remove(path); }
// in java/org/apache/naming/resources/BaseDirContext.java
public void setAliases(String theAliases) { // Overwrite whatever is currently set aliases.clear(); if (theAliases == null || theAliases.length() == 0) return; String[] kvps = theAliases.split(","); for (String kvp : kvps) { String[] kv = kvp.split("="); if (kv.length != 2 || kv[0].length() == 0 || kv[1].length() == 0) throw new IllegalArgumentException( sm.getString("resources.invalidAliasMapping", kvp)); if (kv[0].equals("/")) { throw new IllegalArgumentException( sm.getString("resources.invalidAliasNotAllowed", kv[0])); } File aliasLoc = new File(kv[1]); if (!aliasLoc.exists()) { throw new IllegalArgumentException( sm.getString("resources.invalidAliasNotExist", kv[1])); } BaseDirContext context; if (kv[1].endsWith(".war") && !(aliasLoc.isDirectory())) { context = new WARDirContext(); } else if (aliasLoc.isDirectory()) { context = new FileDirContext(); } else { throw new IllegalArgumentException( sm.getString("resources.invalidAliasFile", kv[1])); } context.setDocBase(kv[1]); addAlias(kv[0], context); } }
// in java/org/apache/naming/resources/BaseDirContext.java
public void setDocBase(String docBase) { // Validate the format of the proposed document root if (docBase == null) throw new IllegalArgumentException (sm.getString("resources.null")); // Change the document root property this.docBase = docBase; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
protected boolean readMessage(AjpMessage message, boolean first, boolean useAvailableData) throws IOException { int headerLength = message.getHeaderLength(); if (first) { if (!readt(headerLength, useAvailableData)) { return false; } } else { read(headerLength); } inputBuffer.get(message.getBuffer(), 0, headerLength); int messageLength = message.processHeader(true); if (messageLength < 0) { // Invalid AJP header signature // TODO: Throw some exception and close the connection to frontend. return false; } else if (messageLength == 0) { // Zero length message. return true; } else { if (messageLength > message.getBuffer().length) { // Message too long for the buffer // Need to trigger a 400 response throw new IllegalArgumentException(sm.getString( "ajpprocessor.header.tooLong", Integer.valueOf(messageLength), Integer.valueOf(message.getBuffer().length))); } read(messageLength); inputBuffer.get(message.getBuffer(), headerLength, messageLength); return true; } }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
protected int readMessage(AjpMessage message, boolean blockFirstRead) throws IOException { byte[] buf = message.getBuffer(); int headerLength = message.getHeaderLength(); int bytesRead = read(buf, 0, headerLength, blockFirstRead); if (bytesRead == 0) { return 0; } int messageLength = message.processHeader(true); if (messageLength < 0) { // Invalid AJP header signature throw new IOException(sm.getString("ajpmessage.invalidLength", Integer.valueOf(messageLength))); } else if (messageLength == 0) { // Zero length message. return bytesRead; } else { if (messageLength > buf.length) { // Message too long for the buffer // Need to trigger a 400 response throw new IllegalArgumentException(sm.getString( "ajpprocessor.header.tooLong", Integer.valueOf(messageLength), Integer.valueOf(buf.length))); } bytesRead += read(buf, headerLength, messageLength, true); return bytesRead; } }
// in java/org/apache/coyote/ajp/AjpProcessor.java
protected boolean readMessage(AjpMessage message) throws IOException { byte[] buf = message.getBuffer(); int headerLength = message.getHeaderLength(); read(buf, 0, headerLength); int messageLength = message.processHeader(true); if (messageLength < 0) { // Invalid AJP header signature // TODO: Throw some exception and close the connection to frontend. return false; } else if (messageLength == 0) { // Zero length message. return true; } else { if (messageLength > buf.length) { // Message too long for the buffer // Need to trigger a 400 response throw new IllegalArgumentException(sm.getString( "ajpprocessor.header.tooLong", Integer.valueOf(messageLength), Integer.valueOf(buf.length))); } read(buf, headerLength, messageLength); return true; } }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableDataOnly) throws IOException { //check state if ( !parsingRequestLine ) return true; // // Skipping blank lines // if ( parsingRequestLinePhase == 0 ) { byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (useAvailableDataOnly) { return false; } // Ignore bytes that were read pos = lastValid = 0; // Do a simple read with a short timeout if ( readSocket(true, false)==0 ) return false; } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; if (pos >= skipBlankLinesSize) { // Move data, to have enough space for further reading // of headers and body System.arraycopy(buf, pos, buf, 0, lastValid - pos); lastValid -= pos; pos = 0; } skipBlankLinesBytes = pos; parsingRequestLineStart = pos; parsingRequestLinePhase = 2; if (log.isDebugEnabled()) { log.debug("Received [" + new String(buf, pos, lastValid - pos, DEFAULT_CHARSET) + "]"); } } if ( parsingRequestLinePhase == 2 ) { // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, parsingRequestLineStart, pos - parsingRequestLineStart); } pos++; } parsingRequestLinePhase = 3; } if ( parsingRequestLinePhase == 3 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 4; } if (parsingRequestLinePhase == 4) { // Mark the current buffer position int end = 0; // // Reading the URI // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request parsingRequestLineEol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (parsingRequestLineQPos == -1)) { parsingRequestLineQPos = pos; } pos++; } request.unparsedURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); if (parsingRequestLineQPos >= 0) { request.queryString().setBytes(buf, parsingRequestLineQPos + 1, end - parsingRequestLineQPos - 1); request.requestURI().setBytes(buf, parsingRequestLineStart, parsingRequestLineQPos - parsingRequestLineStart); } else { request.requestURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } parsingRequestLinePhase = 5; } if ( parsingRequestLinePhase == 5 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 6; } if (parsingRequestLinePhase == 6) { // Mark the current buffer position end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!parsingRequestLineEol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; parsingRequestLineEol = true; } pos++; } if ( (end - parsingRequestLineStart) > 0) { request.protocol().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } else { request.protocol().setString(""); } parsingRequestLine = false; parsingRequestLinePhase = 0; parsingRequestLineEol = false; parsingRequestLineStart = 0; return true; } throw new IllegalStateException("Invalid request line parse phase:"+parsingRequestLinePhase); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
private void expand(int newsize) { if ( newsize > buf.length ) { if (parsingHeader) { throw new IllegalArgumentException( sm.getString("iib.requestheadertoolarge.error")); } // Should not happen log.warn("Expanding buffer size. Old size: " + buf.length + ", new size: " + newsize, new Exception()); byte[] tmp = new byte[newsize]; System.arraycopy(buf,0,tmp,0,buf.length); buf = tmp; } }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } HeaderParseStatus status = HeaderParseStatus.HAVE_MORE_HEADERS; do { status = parseHeader(); } while ( status == HeaderParseStatus.HAVE_MORE_HEADERS ); if (status == HeaderParseStatus.DONE) { parsingHeader = false; end = pos; // Checking that // (1) Headers plus request line size does not exceed its limit // (2) There are enough bytes to avoid expanding the buffer when // reading body // Technically, (2) is technical limitation, (1) is logical // limitation to enforce the meaning of headerBufferSize // From the way how buf is allocated and how blank lines are being // read, it should be enough to check (1) only. if (end - skipBlankLinesBytes > headerBufferSize || buf.length - end < socketReadBufferSize) { throw new IllegalArgumentException( sm.getString("iib.requestheadertoolarge.error")); } return true; } else { return false; } }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
protected boolean fill(boolean timeout, boolean block) throws IOException, EOFException { boolean read = false; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } // Do a simple read with a short timeout read = readSocket(timeout,block)>0; } else { lastValid = pos = end; // Do a simple read with a short timeout read = readSocket(timeout, block)>0; } return read; }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableDataOnly) throws IOException { int start = 0; // // Skipping blank lines // byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; // Mark the current buffer position start = pos; // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, start, pos - start); } pos++; } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; int end = 0; int questionPos = -1; // // Reading the URI // boolean eol = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request eol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (questionPos == -1)) { questionPos = pos; } pos++; } request.unparsedURI().setBytes(buf, start, end - start); if (questionPos >= 0) { request.queryString().setBytes(buf, questionPos + 1, end - questionPos - 1); request.requestURI().setBytes(buf, start, questionPos - start); } else { request.requestURI().setBytes(buf, start, end - start); } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; eol = true; } pos++; } if ((end - start) > 0) { request.protocol().setBytes(buf, start, end - start); } else { request.protocol().setString(""); } return true; }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override protected boolean fill(boolean block) throws IOException { int nRead = 0; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } nRead = inputStream.read(buf, pos, buf.length - lastValid); if (nRead > 0) { lastValid = pos + nRead; } } else { if (buf.length - end < 4500) { // In this case, the request header was really large, so we allocate a // brand new one; the old one will get GCed when subsequent requests // clear all references buf = new byte[buf.length]; end = 0; } pos = end; lastValid = pos; nRead = inputStream.read(buf, pos, buf.length - lastValid); if (nRead > 0) { lastValid = pos + nRead; } } return (nRead > 0); }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableData) throws IOException { int start = 0; // // Skipping blank lines // byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (useAvailableData) { return false; } if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; // Mark the current buffer position start = pos; if (pos >= lastValid) { if (useAvailableData) { return false; } if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, start, pos - start); } pos++; } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; int end = 0; int questionPos = -1; // // Reading the URI // boolean eol = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request eol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (questionPos == -1)) { questionPos = pos; } pos++; } request.unparsedURI().setBytes(buf, start, end - start); if (questionPos >= 0) { request.queryString().setBytes(buf, questionPos + 1, end - questionPos - 1); request.requestURI().setBytes(buf, start, questionPos - start); } else { request.requestURI().setBytes(buf, start, end - start); } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; eol = true; } pos++; } if ((end - start) > 0) { request.protocol().setBytes(buf, start, end - start); } else { request.protocol().setString(""); } return true; }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
protected boolean fill() throws IOException { int nRead = 0; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.EAGAIN) { return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } else { if (buf.length - end < 4500) { // In this case, the request header was really large, so we allocate a // brand new one; the old one will get GCed when subsequent requests // clear all references buf = new byte[buf.length]; end = 0; } pos = end; lastValid = pos; bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.ETIMEDOUT || (-nRead) == Status.TIMEUP) { throw new SocketTimeoutException(sm.getString("iib.failedread")); } else if (nRead == 0) { // APR_STATUS_IS_EOF, since native 1.1.22 return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } return (nRead > 0); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int read(ByteBuffer dst) throws IOException { //if we want to take advantage of the expand function, make sure we only use the ApplicationBufferHandler's buffers if ( dst != bufHandler.getReadBuffer() ) throw new IllegalArgumentException("You can only read using the application read buffer provided by the handler."); //are we in the middle of closing or closed? if ( closing || closed) return -1; //did we finish our handshake? if (!handshakeComplete) throw new IllegalStateException("Handshake incomplete, you must complete handshake before reading data."); //read from the network int netread = sc.read(netInBuffer); //did we reach EOF? if so send EOF up one layer. if (netread == -1) return -1; //the data read int read = 0; //the SSL engine result SSLEngineResult unwrap; do { //prepare the buffer netInBuffer.flip(); //unwrap the data unwrap = sslEngine.unwrap(netInBuffer, dst); //compact the buffer netInBuffer.compact(); if ( unwrap.getStatus()==Status.OK || unwrap.getStatus()==Status.BUFFER_UNDERFLOW ) { //we did receive some data, add it to our total read += unwrap.bytesProduced(); //perform any tasks if needed if (unwrap.getHandshakeStatus() == HandshakeStatus.NEED_TASK) tasks(); //if we need more network data, then bail out for now. if ( unwrap.getStatus() == Status.BUFFER_UNDERFLOW ) break; }else if ( unwrap.getStatus()==Status.BUFFER_OVERFLOW && read>0 ) { //buffer overflow can happen, if we have read data, then //empty out the dst buffer before we do another read break; }else { //here we should trap BUFFER_OVERFLOW and call expand on the buffer //for now, throw an exception, as we initialized the buffers //in the constructor throw new IOException("Unable to unwrap data, invalid status: " + unwrap.getStatus()); } } while ( (netInBuffer.position() != 0)); //continue to unwrapping as long as the input buffer has stuff return (read); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int write(ByteBuffer src) throws IOException { if ( src == this.netOutBuffer ) { //we can get here through a recursive call //by using the NioBlockingSelector int written = sc.write(src); return written; } else { //make sure we can handle expand, and that we only use on buffer if ( (!this.isSendFile()) && (src != bufHandler.getWriteBuffer()) ) throw new IllegalArgumentException("You can only write using the application write buffer provided by the handler."); //are we closing or closed? if ( closing || closed) throw new IOException("Channel is in closing state."); //the number of bytes written int written = 0; if (!flush(netOutBuffer)) { //we haven't emptied out the buffer yet return written; } /* * The data buffer is empty, we can reuse the entire buffer. */ netOutBuffer.clear(); SSLEngineResult result = sslEngine.wrap(src, netOutBuffer); written = result.bytesConsumed(); netOutBuffer.flip(); if (result.getStatus() == Status.OK) { if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) tasks(); } else { throw new IOException("Unable to wrap data, invalid engine state: " +result.getStatus()); } //force a flush flush(netOutBuffer); return written; } }
// in java/org/apache/tomcat/util/http/MimeHeaders.java
public MessageBytes getUniqueValue(String name) { MessageBytes result = null; for (int i = 0; i < count; i++) { if (headers[i].getName().equalsIgnoreCase(name)) { if (result == null) { result = headers[i].getValue(); } else { throw new IllegalArgumentException(); } } } return result; }
// in java/org/apache/tomcat/util/http/CookieSupport.java
public static final boolean isV0Separator(final char c) { if (c < 0x20 || c >= 0x7f) { if (c != 0x09) { throw new IllegalArgumentException( "Control character in cookie value or attribute."); } } return V0_SEPARATOR_FLAGS[c]; }
// in java/org/apache/tomcat/util/http/CookieSupport.java
public static final boolean isHttpSeparator(final char c) { if (c < 0x20 || c >= 0x7f) { if (c != 0x09) { throw new IllegalArgumentException( "Control character in cookie value or attribute."); } } return HTTP_SEPARATOR_FLAGS[c]; }
// in java/org/apache/tomcat/util/http/ServerCookie.java
private static String escapeDoubleQuotes(String s, int beginIndex, int endIndex) { if (s == null || s.length() == 0 || s.indexOf('"') == -1) { return s; } StringBuffer b = new StringBuffer(); for (int i = beginIndex; i < endIndex; i++) { char c = s.charAt(i); if (c == '\\' ) { b.append(c); //ignore the character after an escape, just append it if (++i>=endIndex) { throw new IllegalArgumentException("Invalid escape character in cookie value."); } b.append(s.charAt(i)); } else if (c == '"') { b.append('\\').append('"'); } else { b.append(c); } } return b.toString(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void cleanDirectory(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (int i = 0; i < files.length; i++) { File file = files[i]; try { forceDelete(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
private static void cleanDirectoryOnExit(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (int i = 0; i < files.length; i++) { File file = files[i]; try { forceDeleteOnExit(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } }
// in java/org/apache/tomcat/util/buf/UDecoder.java
public final String convert(String str, boolean query) { if (str == null) { return null; } if( (!query || str.indexOf( '+' ) < 0) && str.indexOf( '%' ) < 0 ) { return str; } final boolean noSlash = !(ALLOW_ENCODED_SLASH || query); StringBuilder dec = new StringBuilder(); // decoded string output int strPos = 0; int strLen = str.length(); dec.ensureCapacity(str.length()); while (strPos < strLen) { int laPos; // lookahead position // look ahead to next URLencoded metacharacter, if any for (laPos = strPos; laPos < strLen; laPos++) { char laChar = str.charAt(laPos); if ((laChar == '+' && query) || (laChar == '%')) { break; } } // if there were non-metacharacters, copy them all as a block if (laPos > strPos) { dec.append(str.substring(strPos,laPos)); strPos = laPos; } // shortcut out of here if we're at the end of the string if (strPos >= strLen) { break; } // process next metacharacter char metaChar = str.charAt(strPos); if (metaChar == '+') { dec.append(' '); strPos++; continue; } else if (metaChar == '%') { // We throw the original exception - the super will deal with // it // try { char res = (char) Integer.parseInt( str.substring(strPos + 1, strPos + 3), 16); if (noSlash && (res == '/')) { throw new IllegalArgumentException("noSlash"); } dec.append(res); strPos += 3; } } return dec.toString(); }
// in java/org/apache/tomcat/util/res/StringManager.java
public String getString(String key) { if(key == null){ String msg = "key may not have a null value"; throw new IllegalArgumentException(msg); } String str = null; try { // Avoid NPE if bundle is null and treat it like an MRE if (bundle != null) { str = bundle.getString(key); } } catch(MissingResourceException mre) { //bad: shouldn't mask an exception the following way: // str = "[cannot find message associated with key '" + key + // "' due to " + mre + "]"; // because it hides the fact that the String was missing // from the calling code. //good: could just throw the exception (or wrap it in another) // but that would probably cause much havoc on existing // code. //better: consistent with container pattern to // simply return null. Calling code can then do // a null check. str = null; } return str; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void addAttributeChangeNotificationListener (NotificationListener listener, String name, Object handback) throws IllegalArgumentException { if (listener == null) throw new IllegalArgumentException("Listener is null"); if (attributeBroadcaster == null) attributeBroadcaster = new BaseNotificationBroadcaster(); if( log.isDebugEnabled() ) log.debug("addAttributeNotificationListener " + listener); BaseAttributeFilter filter = new BaseAttributeFilter(name); attributeBroadcaster.addNotificationListener (listener, filter, handback); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void removeAttributeChangeNotificationListener (NotificationListener listener, String name) throws ListenerNotFoundException { if (listener == null) throw new IllegalArgumentException("Listener is null"); if (attributeBroadcaster == null) attributeBroadcaster = new BaseNotificationBroadcaster(); // FIXME - currently this removes *all* notifications for this listener attributeBroadcaster.removeNotificationListener(listener); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException { if (listener == null) throw new IllegalArgumentException("Listener is null"); if( log.isDebugEnabled() ) log.debug("addNotificationListener " + listener); if (generalBroadcaster == null) generalBroadcaster = new BaseNotificationBroadcaster(); generalBroadcaster.addNotificationListener (listener, filter, handback); // We'll send the attribute change notifications to all listeners ( who care ) // The normal filtering can be used. // The problem is that there is no other way to add attribute change listeners // to a model mbean ( AFAIK ). I suppose the spec should be fixed. if (attributeBroadcaster == null) attributeBroadcaster = new BaseNotificationBroadcaster(); if( log.isDebugEnabled() ) log.debug("addAttributeNotificationListener " + listener); attributeBroadcaster.addNotificationListener (listener, filter, handback); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { if (listener == null) throw new IllegalArgumentException("Listener is null"); if (generalBroadcaster == null) generalBroadcaster = new BaseNotificationBroadcaster(); generalBroadcaster.removeNotificationListener(listener); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
public static Object convert(String object, Class<?> paramType) { Object result = null; if ("java.lang.String".equals(paramType.getName())) { result = object; } else if ("java.lang.Integer".equals(paramType.getName()) || "int".equals(paramType.getName())) { try { result = new Integer(object); } catch (NumberFormatException ex) { } // Try a setFoo ( boolean ) } else if ("java.lang.Boolean".equals(paramType.getName()) || "boolean".equals(paramType.getName())) { result = Boolean.valueOf(object); // Try a setFoo ( InetAddress ) } else if ("java.net.InetAddress".equals(paramType .getName())) { try { result = InetAddress.getByName(object); } catch (UnknownHostException exc) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Unable to resolve host name:" + object); } // Unknown type } else { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Unknown type " + paramType.getName()); } if (result == null) { throw new IllegalArgumentException("Can't convert argument: " + object); } return result; }
// in java/org/apache/el/lang/ELArithmetic.java
protected final Number coerce(final Object obj) { if (isNumber(obj)) { return coerce((Number) obj); } if (obj == null || "".equals(obj)) { return coerce(ZERO); } if (obj instanceof String) { return coerce((String) obj); } if (obj instanceof Character) { return coerce(Short.valueOf((short) ((Character) obj).charValue())); } throw new IllegalArgumentException(MessageFactory.get("error.convert", obj, obj.getClass(), "Number")); }
// in java/org/apache/catalina/startup/ContextConfig.java
private void convertJsp(ServletDef servletDef, Map<String,String> jspInitParams) { servletDef.setServletClass(org.apache.catalina.core.Constants.JSP_SERVLET_CLASS); String jspFile = servletDef.getJspFile(); if ((jspFile != null) && !jspFile.startsWith("/")) { if (context.isServlet22()) { if(log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.jspFile.warning", jspFile)); } jspFile = "/" + jspFile; } else { throw new IllegalArgumentException (sm.getString("contextConfig.jspFile.error", jspFile)); } } servletDef.getParameterMap().put("jspFile", jspFile); servletDef.setJspFile(null); for (Map.Entry<String, String> initParam: jspInitParams.entrySet()) { servletDef.addInitParameter(initParam.getKey(), initParam.getValue()); } }
// in java/org/apache/catalina/startup/ContextConfig.java
protected void processAnnotationWebServlet(String className, AnnotationEntry ae, WebXml fragment) { String servletName = null; // must search for name s. Spec Servlet API 3.0 - 8.2.3.3.n.ii page 81 ElementValuePair[] evps = ae.getElementValuePairs(); for (ElementValuePair evp : evps) { String name = evp.getNameString(); if ("name".equals(name)) { servletName = evp.getValue().stringifyValue(); break; } } if (servletName == null) { // classname is default servletName as annotation has no name! servletName = className; } ServletDef servletDef = fragment.getServlets().get(servletName); boolean isWebXMLservletDef; if (servletDef == null) { servletDef = new ServletDef(); servletDef.setServletName(servletName); servletDef.setServletClass(className); isWebXMLservletDef = false; } else { isWebXMLservletDef = true; } boolean urlPatternsSet = false; String[] urlPatterns = null; // ElementValuePair[] evps = ae.getElementValuePairs(); for (ElementValuePair evp : evps) { String name = evp.getNameString(); if ("value".equals(name) || "urlPatterns".equals(name)) { if (urlPatternsSet) { throw new IllegalArgumentException(sm.getString( "contextConfig.urlPatternValue", className)); } urlPatternsSet = true; urlPatterns = processAnnotationsStringArray(evp.getValue()); } else if ("description".equals(name)) { if (servletDef.getDescription() == null) { servletDef.setDescription(evp.getValue().stringifyValue()); } } else if ("displayName".equals(name)) { if (servletDef.getDisplayName() == null) { servletDef.setDisplayName(evp.getValue().stringifyValue()); } } else if ("largeIcon".equals(name)) { if (servletDef.getLargeIcon() == null) { servletDef.setLargeIcon(evp.getValue().stringifyValue()); } } else if ("smallIcon".equals(name)) { if (servletDef.getSmallIcon() == null) { servletDef.setSmallIcon(evp.getValue().stringifyValue()); } } else if ("asyncSupported".equals(name)) { if (servletDef.getAsyncSupported() == null) { servletDef.setAsyncSupported(evp.getValue() .stringifyValue()); } } else if ("loadOnStartup".equals(name)) { if (servletDef.getLoadOnStartup() == null) { servletDef .setLoadOnStartup(evp.getValue().stringifyValue()); } } else if ("initParams".equals(name)) { Map<String, String> initParams = processAnnotationWebInitParams(evp .getValue()); if (isWebXMLservletDef) { Map<String, String> webXMLInitParams = servletDef .getParameterMap(); for (Map.Entry<String, String> entry : initParams .entrySet()) { if (webXMLInitParams.get(entry.getKey()) == null) { servletDef.addInitParameter(entry.getKey(), entry .getValue()); } } } else { for (Map.Entry<String, String> entry : initParams .entrySet()) { servletDef.addInitParameter(entry.getKey(), entry .getValue()); } } } } if (!isWebXMLservletDef && urlPatterns != null) { fragment.addServlet(servletDef); } if (urlPatterns != null) { if (!fragment.getServletMappings().containsValue(servletName)) { for (String urlPattern : urlPatterns) { fragment.addServletMapping(urlPattern, servletName); } } } }
// in java/org/apache/catalina/startup/ContextConfig.java
protected void processAnnotationWebFilter(String className, AnnotationEntry ae, WebXml fragment) { String filterName = null; // must search for name s. Spec Servlet API 3.0 - 8.2.3.3.n.ii page 81 ElementValuePair[] evps = ae.getElementValuePairs(); for (ElementValuePair evp : evps) { String name = evp.getNameString(); if ("filterName".equals(name)) { filterName = evp.getValue().stringifyValue(); break; } } if (filterName == null) { // classname is default filterName as annotation has no name! filterName = className; } FilterDef filterDef = fragment.getFilters().get(filterName); FilterMap filterMap = new FilterMap(); boolean isWebXMLfilterDef; if (filterDef == null) { filterDef = new FilterDef(); filterDef.setFilterName(filterName); filterDef.setFilterClass(className); isWebXMLfilterDef = false; } else { isWebXMLfilterDef = true; } boolean urlPatternsSet = false; boolean dispatchTypesSet = false; String[] urlPatterns = null; for (ElementValuePair evp : evps) { String name = evp.getNameString(); if ("value".equals(name) || "urlPatterns".equals(name)) { if (urlPatternsSet) { throw new IllegalArgumentException(sm.getString( "contextConfig.urlPatternValue", className)); } urlPatterns = processAnnotationsStringArray(evp.getValue()); urlPatternsSet = urlPatterns.length > 0; for (String urlPattern : urlPatterns) { filterMap.addURLPattern(urlPattern); } } else if ("servletNames".equals(name)) { String[] servletNames = processAnnotationsStringArray(evp .getValue()); for (String servletName : servletNames) { filterMap.addServletName(servletName); } } else if ("dispatcherTypes".equals(name)) { String[] dispatcherTypes = processAnnotationsStringArray(evp .getValue()); dispatchTypesSet = dispatcherTypes.length > 0; for (String dispatcherType : dispatcherTypes) { filterMap.setDispatcher(dispatcherType); } } else if ("description".equals(name)) { if (filterDef.getDescription() == null) { filterDef.setDescription(evp.getValue().stringifyValue()); } } else if ("displayName".equals(name)) { if (filterDef.getDisplayName() == null) { filterDef.setDisplayName(evp.getValue().stringifyValue()); } } else if ("largeIcon".equals(name)) { if (filterDef.getLargeIcon() == null) { filterDef.setLargeIcon(evp.getValue().stringifyValue()); } } else if ("smallIcon".equals(name)) { if (filterDef.getSmallIcon() == null) { filterDef.setSmallIcon(evp.getValue().stringifyValue()); } } else if ("asyncSupported".equals(name)) { if (filterDef.getAsyncSupported() == null) { filterDef .setAsyncSupported(evp.getValue().stringifyValue()); } } else if ("initParams".equals(name)) { Map<String, String> initParams = processAnnotationWebInitParams(evp .getValue()); if (isWebXMLfilterDef) { Map<String, String> webXMLInitParams = filterDef .getParameterMap(); for (Map.Entry<String, String> entry : initParams .entrySet()) { if (webXMLInitParams.get(entry.getKey()) == null) { filterDef.addInitParameter(entry.getKey(), entry .getValue()); } } } else { for (Map.Entry<String, String> entry : initParams .entrySet()) { filterDef.addInitParameter(entry.getKey(), entry .getValue()); } } } } if (!isWebXMLfilterDef) { fragment.addFilter(filterDef); filterMap.setFilterName(filterName); fragment.addFilterMapping(filterMap); } if (urlPatternsSet || dispatchTypesSet) { Set<FilterMap> fmap = fragment.getFilterMappings(); FilterMap descMap = null; for (FilterMap map : fmap) { if (filterName.equals(map.getFilterName())) { descMap = map; break; } } if (descMap != null) { String[] urlsPatterns = descMap.getURLPatterns(); if (urlPatternsSet && (urlsPatterns == null || urlsPatterns.length == 0)) { for (String urlPattern : filterMap.getURLPatterns()) { descMap.addURLPattern(urlPattern); } } String[] dispatcherNames = descMap.getDispatcherNames(); if (dispatchTypesSet && (dispatcherNames == null || dispatcherNames.length == 0)) { for (String dis : filterMap.getDispatcherNames()) { descMap.setDispatcher(dis); } } } } }
// in java/org/apache/catalina/startup/WebAnnotationSet.java
private static void checkBeanNamingConventions(Method method) { if (!method.getName().startsWith("set") || method.getName().length() < 4 || method.getParameterTypes().length != 1 || !method.getReturnType().getName().equals("void")) { throw new IllegalArgumentException("Invalid method resource injection annotation."); } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isLoginConfigSet){ throw new IllegalArgumentException( "<login-config> element is limited to 1 occurrence"); } isLoginConfigSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isJspConfigSet){ throw new IllegalArgumentException( "<jsp-config> element is limited to 1 occurrence"); } isJspConfigSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isSessionConfigSet){ throw new IllegalArgumentException( "<session-config> element is limited to 1 occurrence"); } isSessionConfigSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isNameSet){ throw new IllegalArgumentException(WebRuleSet.sm.getString( "webRuleSet.nameCount")); } isNameSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (fragment) { digester.getLogger().warn( WebRuleSet.sm.getString("webRuleSet.absoluteOrdering")); } if (isAbsoluteOrderingSet) { throw new IllegalArgumentException(WebRuleSet.sm.getString( "webRuleSet.absoluteOrderingCount")); } else { isAbsoluteOrderingSet = true; } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (!fragment) { digester.getLogger().warn( WebRuleSet.sm.getString("webRuleSet.relativeOrdering")); } if (isRelativeOrderingSet) { throw new IllegalArgumentException(WebRuleSet.sm.getString( "webRuleSet.relativeOrderingCount")); } else { isRelativeOrderingSet = true; } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { WebXml webXml = (WebXml) digester.peek(digester.getCount() - 1); // If we have a public ID, this is not a 2.4 or later webapp boolean havePublicId = (webXml.getPublicId() != null); // havePublicId and isServlet24OrLater should be mutually exclusive if (havePublicId == isServlet24OrLater) { throw new IllegalArgumentException( "taglib definition not consistent with specification version"); } }
// in java/org/apache/catalina/startup/ExpandWar.java
public static String expand(Host host, URL war, String pathname) throws IOException { // Make sure that there is no such directory already existing File docBase = new File(host.getAppBaseFile(), pathname); if (docBase.exists()) { // War file is already installed return (docBase.getAbsolutePath()); } // Create the new document base directory docBase.mkdir(); // Expand the WAR into the new document base directory String canonicalDocBasePrefix = docBase.getCanonicalPath(); if (!canonicalDocBasePrefix.endsWith(File.separator)) { canonicalDocBasePrefix += File.separator; } JarURLConnection juc = (JarURLConnection) war.openConnection(); juc.setUseCaches(false); JarFile jarFile = null; InputStream input = null; boolean success = false; try { jarFile = juc.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String name = jarEntry.getName(); File expandedFile = new File(docBase, name); if (!expandedFile.getCanonicalPath().startsWith( canonicalDocBasePrefix)) { // Trying to expand outside the docBase // Throw an exception to stop the deployment throw new IllegalArgumentException( sm.getString("expandWar.illegalPath",war, name, expandedFile.getCanonicalPath(), canonicalDocBasePrefix)); } int last = name.lastIndexOf('/'); if (last >= 0) { File parent = new File(docBase, name.substring(0, last)); if (!parent.mkdirs() && !parent.isDirectory()) { throw new IOException( sm.getString("expandWar.createFailed", parent)); } } if (name.endsWith("/")) { continue; } input = jarFile.getInputStream(jarEntry); if(null == input) throw new ZipException(sm.getString("expandWar.missingJarEntry", jarEntry.getName())); // Bugzilla 33636 expand(input, expandedFile); long lastModified = jarEntry.getTime(); if ((lastModified != -1) && (lastModified != 0)) { expandedFile.setLastModified(lastModified); } input.close(); input = null; } success = true; } catch (IOException e) { throw e; } finally { if (!success) { // If something went wrong, delete expanded dir to keep things // clean deleteDir(docBase); } if (input != null) { try { input.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } input = null; } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } } // Return the absolute path to our new document base directory return (docBase.getAbsolutePath()); }
// in java/org/apache/catalina/startup/ExpandWar.java
public static void validate(Host host, URL war, String pathname) throws IOException { File docBase = new File(host.getAppBaseFile(), pathname); // Calculate the document base directory String canonicalDocBasePrefix = docBase.getCanonicalPath(); if (!canonicalDocBasePrefix.endsWith(File.separator)) { canonicalDocBasePrefix += File.separator; } JarURLConnection juc = (JarURLConnection) war.openConnection(); juc.setUseCaches(false); JarFile jarFile = null; try { jarFile = juc.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String name = jarEntry.getName(); File expandedFile = new File(docBase, name); if (!expandedFile.getCanonicalPath().startsWith( canonicalDocBasePrefix)) { // Entry located outside the docBase // Throw an exception to stop the deployment throw new IllegalArgumentException( sm.getString("expandWar.illegalPath",war, name, expandedFile.getCanonicalPath(), canonicalDocBasePrefix)); } } } catch (IOException e) { throw e; } finally { if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } } }
// in java/org/apache/catalina/realm/RealmBase.java
Override public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce, String qop, String realm, String md5a2) { // In digest auth, digests are always lower case String md5a1 = getDigest(username, realm).toLowerCase(Locale.ENGLISH); if (md5a1 == null) return null; String serverDigestValue; if (qop == null) { serverDigestValue = md5a1 + ":" + nonce + ":" + md5a2; } else { serverDigestValue = md5a1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + md5a2; } byte[] valueBytes = null; try { valueBytes = serverDigestValue.getBytes(getDigestCharset()); } catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); } String serverDigest = null; // Bugzilla 32137 synchronized(md5Helper) { serverDigest = md5Encoder.encode(md5Helper.digest(valueBytes)); } if (log.isDebugEnabled()) { log.debug("Digest : " + clientDigest + " Username:" + username + " ClientSigest:" + clientDigest + " nonce:" + nonce + " nc:" + nc + " cnonce:" + cnonce + " qop:" + qop + " realm:" + realm + "md5a2:" + md5a2 + " Server digest:" + serverDigest); } if (serverDigest.equals(clientDigest)) { return getPrincipal(username); } return null; }
// in java/org/apache/catalina/realm/RealmBase.java
protected String digest(String credentials) { // If no MessageDigest instance is specified, return unchanged if (hasMessageDigest() == false) return (credentials); // Digest the user credentials and return as hexadecimal synchronized (this) { try { md.reset(); byte[] bytes = null; try { bytes = credentials.getBytes(getDigestCharset()); } catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); } md.update(bytes); return (HexUtils.toHexString(md.digest())); } catch (Exception e) { log.error(sm.getString("realmBase.digest"), e); return (credentials); } } }
// in java/org/apache/catalina/realm/RealmBase.java
protected String getDigest(String username, String realmName) { if (md5Helper == null) { try { md5Helper = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("Couldn't get MD5 digest: ", e); throw new IllegalStateException(e.getMessage()); } } if (hasMessageDigest()) { // Use pre-generated digest return getPassword(username); } String digestValue = username + ":" + realmName + ":" + getPassword(username); byte[] valueBytes = null; try { valueBytes = digestValue.getBytes(getDigestCharset()); } catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); } byte[] digest = null; // Bugzilla 32137 synchronized(md5Helper) { digest = md5Helper.digest(valueBytes); } return md5Encoder.encode(digest); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createValve(String className, String parent) throws Exception { // Look for the parent ObjectName parentName = new ObjectName(parent); Container container = getParentContainerFromParent(parentName); if (container == null) { // TODO throw new IllegalArgumentException(); } Valve valve = (Valve) Class.forName(className).newInstance(); container.getPipeline().addValve(valve); if (valve instanceof JmxEnabled) { return ((JmxEnabled) valve).getObjectName().toString(); } else { return null; } }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
protected void createMBeans(String name, UserDatabase database) throws Exception { // Create the MBean for the UserDatabase itself if (log.isDebugEnabled()) { log.debug("Creating UserDatabase MBeans for resource " + name); log.debug("Database=" + database); } if (MBeanUtils.createMBean(database) == null) { throw new IllegalArgumentException ("Cannot create UserDatabase MBean for resource " + name); } // Create the MBeans for each defined Role Iterator<Role> roles = database.getRoles(); while (roles.hasNext()) { Role role = roles.next(); if (log.isDebugEnabled()) { log.debug(" Creating Role MBean for role " + role); } if (MBeanUtils.createMBean(role) == null) { throw new IllegalArgumentException ("Cannot create Role MBean for role " + role); } } // Create the MBeans for each defined Group Iterator<Group> groups = database.getGroups(); while (groups.hasNext()) { Group group = groups.next(); if (log.isDebugEnabled()) { log.debug(" Creating Group MBean for group " + group); } if (MBeanUtils.createMBean(group) == null) { throw new IllegalArgumentException ("Cannot create Group MBean for group " + group); } } // Create the MBeans for each defined User Iterator<User> users = database.getUsers(); while (users.hasNext()) { User user = users.next(); if (log.isDebugEnabled()) { log.debug(" Creating User MBean for user " + user); } if (MBeanUtils.createMBean(user) == null) { throw new IllegalArgumentException ("Cannot create User MBean for user " + user); } } }
// in java/org/apache/catalina/mbeans/UserMBean.java
public void addGroup(String groupname) { User user = (User) this.resource; if (user == null) { return; } Group group = user.getUserDatabase().findGroup(groupname); if (group == null) { throw new IllegalArgumentException ("Invalid group name '" + groupname + "'"); } user.addGroup(group); }
// in java/org/apache/catalina/mbeans/UserMBean.java
public void addRole(String rolename) { User user = (User) this.resource; if (user == null) { return; } Role role = user.getUserDatabase().findRole(rolename); if (role == null) { throw new IllegalArgumentException ("Invalid role name '" + rolename + "'"); } user.addRole(role); }
// in java/org/apache/catalina/mbeans/UserMBean.java
public void removeGroup(String groupname) { User user = (User) this.resource; if (user == null) { return; } Group group = user.getUserDatabase().findGroup(groupname); if (group == null) { throw new IllegalArgumentException ("Invalid group name '" + groupname + "'"); } user.removeGroup(group); }
// in java/org/apache/catalina/mbeans/UserMBean.java
public void removeRole(String rolename) { User user = (User) this.resource; if (user == null) { return; } Role role = user.getUserDatabase().findRole(rolename); if (role == null) { throw new IllegalArgumentException ("Invalid role name '" + rolename + "'"); } user.removeRole(role); }
// in java/org/apache/catalina/mbeans/GroupMBean.java
public void addRole(String rolename) { Group group = (Group) this.resource; if (group == null) { return; } Role role = group.getUserDatabase().findRole(rolename); if (role == null) { throw new IllegalArgumentException ("Invalid role name '" + rolename + "'"); } group.addRole(role); }
// in java/org/apache/catalina/mbeans/GroupMBean.java
public void removeRole(String rolename) { Group group = (Group) this.resource; if (group == null) { return; } Role role = group.getUserDatabase().findRole(rolename); if (role == null) { throw new IllegalArgumentException ("Invalid role name '" + rolename + "'"); } group.removeRole(role); }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
public String addEnvironment(String envName, String type, String value) throws MalformedObjectNameException { NamingResources nresources = (NamingResources) this.resource; if (nresources == null) { return null; } ContextEnvironment env = nresources.findEnvironment(envName); if (env != null) { throw new IllegalArgumentException ("Invalid environment name - already exists '" + envName + "'"); } env = new ContextEnvironment(); env.setName(envName); env.setType(type); env.setValue(value); nresources.addEnvironment(env); // Return the corresponding MBean name ManagedBean managed = registry.findManagedBean("ContextEnvironment"); ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), env); return (oname.toString()); }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
public String addResource(String resourceName, String type) throws MalformedObjectNameException { NamingResources nresources = (NamingResources) this.resource; if (nresources == null) { return null; } ContextResource resource = nresources.findResource(resourceName); if (resource != null) { throw new IllegalArgumentException ("Invalid resource name - already exists'" + resourceName + "'"); } resource = new ContextResource(); resource.setName(resourceName); resource.setType(type); nresources.addResource(resource); // Return the corresponding MBean name ManagedBean managed = registry.findManagedBean("ContextResource"); ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), resource); return (oname.toString()); }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
public String addResourceLink(String resourceLinkName, String type) throws MalformedObjectNameException { NamingResources nresources = (NamingResources) this.resource; if (nresources == null) { return null; } ContextResourceLink resourceLink = nresources.findResourceLink(resourceLinkName); if (resourceLink != null) { throw new IllegalArgumentException ("Invalid resource link name - already exists'" + resourceLinkName + "'"); } resourceLink = new ContextResourceLink(); resourceLink.setName(resourceLinkName); resourceLink.setType(type); nresources.addResourceLink(resourceLink); // Return the corresponding MBean name ManagedBean managed = registry.findManagedBean("ContextResourceLink"); ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), resourceLink); return (oname.toString()); }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
public void removeEnvironment(String envName) { NamingResources nresources = (NamingResources) this.resource; if (nresources == null) { return; } ContextEnvironment env = nresources.findEnvironment(envName); if (env == null) { throw new IllegalArgumentException ("Invalid environment name '" + envName + "'"); } nresources.removeEnvironment(envName); }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
public void removeResource(String resourceName) { resourceName = ObjectName.unquote(resourceName); NamingResources nresources = (NamingResources) this.resource; if (nresources == null) { return; } ContextResource resource = nresources.findResource(resourceName); if (resource == null) { throw new IllegalArgumentException ("Invalid resource name '" + resourceName + "'"); } nresources.removeResource(resourceName); }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
public void removeResourceLink(String resourceLinkName) { resourceLinkName = ObjectName.unquote(resourceLinkName); NamingResources nresources = (NamingResources) this.resource; if (nresources == null) { return; } ContextResourceLink resourceLink = nresources.findResourceLink(resourceLinkName); if (resourceLink == null) { throw new IllegalArgumentException ("Invalid resource Link name '" + resourceLinkName + "'"); } nresources.removeResourceLink(resourceLinkName); }
// in java/org/apache/catalina/filters/AddDefaultCharsetFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { super.init(filterConfig); if (encoding == null || encoding.length() == 0 || encoding.equalsIgnoreCase("default")) { encoding = DEFAULT_ENCODING; } else if (encoding.equalsIgnoreCase("system")) { encoding = Charset.defaultCharset().name(); } else if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException(sm.getString( "addDefaultCharset.unsupportedCharset", encoding)); } }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
Override public Group createGroup(String groupname, String description) { if (groupname == null || groupname.length() == 0) { String msg = sm.getString("memoryUserDatabase.nullGroup"); log.warn(msg); throw new IllegalArgumentException(msg); } MemoryGroup group = new MemoryGroup(this, groupname, description); synchronized (groups) { groups.put(group.getGroupname(), group); } return (group); }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
Override public Role createRole(String rolename, String description) { if (rolename == null || rolename.length() == 0) { String msg = sm.getString("memoryUserDatabase.nullRole"); log.warn(msg); throw new IllegalArgumentException(msg); } MemoryRole role = new MemoryRole(this, rolename, description); synchronized (roles) { roles.put(role.getRolename(), role); } return (role); }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
Override public User createUser(String username, String password, String fullName) { if (username == null || username.length() == 0) { String msg = sm.getString("memoryUserDatabase.nullUser"); log.warn(msg); throw new IllegalArgumentException(msg); } MemoryUser user = new MemoryUser(this, username, password, fullName); synchronized (users) { users.put(user.getUsername(), user); } return (user); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected List<Session> getSessionsForName(ContextName cn, StringManager smClient) { if ((cn == null) || !(cn.getPath().startsWith("/") || cn.getPath().equals(""))) { String path = null; if (cn != null) { path = cn.getPath(); } throw new IllegalArgumentException(smClient.getString( "managerServlet.invalidPath", RequestUtil.filter(path))); } Context ctxt = (Context) host.findChild(cn.getName()); if (null == ctxt) { throw new IllegalArgumentException(smClient.getString( "managerServlet.noContext", RequestUtil.filter(cn.getDisplayName()))); } Manager manager = ctxt.getManager(); List<Session> sessions = new ArrayList<Session>(); sessions.addAll(Arrays.asList(manager.findSessions())); if (manager instanceof DistributedManager && showProxySessions) { // Add dummy proxy sessions Set<String> sessionIds = ((DistributedManager) manager).getSessionIdsFull(); // Remove active (primary and backup) session IDs from full list for (Session session : sessions) { sessionIds.remove(session.getId()); } // Left with just proxy sessions - add them for (String sessionId : sessionIds) { sessions.add(new DummyProxySession(sessionId)); } } return sessions; }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
Override public void addChannelListener(ChannelListener channelListener) { if (!this.channelListeners.contains(channelListener) ) { this.channelListeners.add(channelListener); } else { throw new IllegalArgumentException("Listener already exists:"+channelListener+"["+channelListener.getClass().getName()+"]"); } }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
protected synchronized void internalStart(int svc) throws ChannelException { try { boolean valid = false; //make sure we don't pass down any flags that are unrelated to the bottom layer svc = svc & Channel.DEFAULT; if (startLevel == Channel.DEFAULT) return; //we have already started up all components if (svc == 0 ) return;//nothing to start if (svc == (svc & startLevel)) throw new ChannelException("Channel already started for level:"+svc); //must start the receiver first so that we can coordinate the port it //listens to with the local membership settings if ( Channel.SND_RX_SEQ==(svc & Channel.SND_RX_SEQ) ) { clusterReceiver.setMessageListener(this); clusterReceiver.start(); //synchronize, big time FIXME membershipService.setLocalMemberProperties(getClusterReceiver().getHost(), getClusterReceiver().getPort(), getClusterReceiver().getSecurePort(), getClusterReceiver().getUdpPort()); valid = true; } if ( Channel.SND_TX_SEQ==(svc & Channel.SND_TX_SEQ) ) { clusterSender.start(); valid = true; } if ( Channel.MBR_RX_SEQ==(svc & Channel.MBR_RX_SEQ) ) { membershipService.setMembershipListener(this); if (membershipService instanceof McastService) { ((McastService)membershipService).setMessageListener(this); } membershipService.start(MembershipService.MBR_RX); valid = true; } if ( Channel.MBR_TX_SEQ==(svc & Channel.MBR_TX_SEQ) ) { membershipService.start(MembershipService.MBR_TX); valid = true; } if ( !valid) { throw new IllegalArgumentException("Invalid start level, valid levels are:SND_RX_SEQ,SND_TX_SEQ,MBR_TX_SEQ,MBR_RX_SEQ"); } startLevel = (startLevel | svc); }catch ( ChannelException cx ) { throw cx; }catch ( Exception x ) { throw new ChannelException(x); } }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
protected synchronized void internalStop(int svc) throws ChannelException { try { //make sure we don't pass down any flags that are unrelated to the bottom layer svc = svc & Channel.DEFAULT; if (startLevel == 0) return; //we have already stopped up all components if (svc == 0 ) return;//nothing to stop boolean valid = false; if ( Channel.SND_RX_SEQ==(svc & Channel.SND_RX_SEQ) ) { clusterReceiver.stop(); clusterReceiver.setMessageListener(null); valid = true; } if ( Channel.SND_TX_SEQ==(svc & Channel.SND_TX_SEQ) ) { clusterSender.stop(); valid = true; } if ( Channel.MBR_RX_SEQ==(svc & Channel.MBR_RX_SEQ) ) { membershipService.stop(MembershipService.MBR_RX); membershipService.setMembershipListener(null); valid = true; } if ( Channel.MBR_TX_SEQ==(svc & Channel.MBR_TX_SEQ) ) { valid = true; membershipService.stop(MembershipService.MBR_TX); } if ( !valid) { throw new IllegalArgumentException("Invalid start level, valid levels are:SND_RX_SEQ,SND_TX_SEQ,MBR_TX_SEQ,MBR_RX_SEQ"); } startLevel = (startLevel & (~svc)); }catch ( Exception x ) { throw new ChannelException(x); } finally { } }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
public static MemberImpl getMember(byte[] data, int offset, int length, MemberImpl member) { //package looks like //start package TRIBES_MBR_BEGIN.length //package length - 4 bytes //alive - 8 bytes //port - 4 bytes //secure port - 4 bytes //udp port - 4 bytes //host length - 1 byte //host - hl bytes //clen - 4 bytes //command - clen bytes //dlen - 4 bytes //domain - dlen bytes //uniqueId - 16 bytes //payload length - 4 bytes //payload plen bytes //end package TRIBES_MBR_END.length int pos = offset; if (XByteBuffer.firstIndexOf(data,offset,TRIBES_MBR_BEGIN)!=pos) { throw new IllegalArgumentException("Invalid package, should start with:"+org.apache.catalina.tribes.util.Arrays.toString(TRIBES_MBR_BEGIN)); } if ( length < (TRIBES_MBR_BEGIN.length+4) ) { throw new ArrayIndexOutOfBoundsException("Member package to small to validate."); } pos += TRIBES_MBR_BEGIN.length; int bodylength = XByteBuffer.toInt(data,pos); pos += 4; if ( length < (bodylength+4+TRIBES_MBR_BEGIN.length+TRIBES_MBR_END.length) ) { throw new ArrayIndexOutOfBoundsException("Not enough bytes in member package."); } int endpos = pos+bodylength; if (XByteBuffer.firstIndexOf(data,endpos,TRIBES_MBR_END)!=endpos) { throw new IllegalArgumentException("Invalid package, should end with:"+org.apache.catalina.tribes.util.Arrays.toString(TRIBES_MBR_END)); } byte[] alived = new byte[8]; System.arraycopy(data, pos, alived, 0, 8); pos += 8; byte[] portd = new byte[4]; System.arraycopy(data, pos, portd, 0, 4); pos += 4; byte[] sportd = new byte[4]; System.arraycopy(data, pos, sportd, 0, 4); pos += 4; byte[] uportd = new byte[4]; System.arraycopy(data, pos, uportd, 0, 4); pos += 4; byte hl = data[pos++]; byte[] addr = new byte[hl]; System.arraycopy(data, pos, addr, 0, hl); pos += hl; int cl = XByteBuffer.toInt(data, pos); pos += 4; byte[] command = new byte[cl]; System.arraycopy(data, pos, command, 0, command.length); pos += command.length; int dl = XByteBuffer.toInt(data, pos); pos += 4; byte[] domain = new byte[dl]; System.arraycopy(data, pos, domain, 0, domain.length); pos += domain.length; byte[] uniqueId = new byte[16]; System.arraycopy(data, pos, uniqueId, 0, 16); pos += 16; int pl = XByteBuffer.toInt(data, pos); pos += 4; byte[] payload = new byte[pl]; System.arraycopy(data, pos, payload, 0, payload.length); pos += payload.length; member.setHost(addr); member.setPort(XByteBuffer.toInt(portd, 0)); member.setSecurePort(XByteBuffer.toInt(sportd, 0)); member.setUdpPort(XByteBuffer.toInt(uportd, 0)); member.setMemberAliveTime(XByteBuffer.toLong(alived, 0)); member.setUniqueId(uniqueId); member.payload = payload; member.domain = domain; member.command = command; member.dataPkg = new byte[length]; System.arraycopy(data, offset, member.dataPkg, 0, length); return member; }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
public void setPayload(byte[] payload) { byte[] oldpayload = this.payload; this.payload = payload!=null?payload:new byte[0]; if ( this.getData(true,true).length > McastServiceImpl.MAX_PACKET_SIZE ) { this.payload = oldpayload; throw new IllegalArgumentException("Payload is to large for tribes to handle."); } }
// in java/org/apache/catalina/tribes/membership/McastService.java
Override public void setLocalMemberProperties(String listenHost, int listenPort, int securePort, int udpPort) { properties.setProperty("tcpListenHost",listenHost); properties.setProperty("tcpListenPort",String.valueOf(listenPort)); properties.setProperty("udpListenPort",String.valueOf(udpPort)); properties.setProperty("tcpSecurePort",String.valueOf(securePort)); try { if (localMember != null) { localMember.setHostname(listenHost); localMember.setPort(listenPort); } else { localMember = new MemberImpl(listenHost, listenPort, 0); localMember.setUniqueId(UUIDGenerator.randomUUID(true)); localMember.setPayload(getPayload()); localMember.setDomain(getDomain()); } localMember.setSecurePort(securePort); localMember.setUdpPort(udpPort); localMember.getData(true, true); }catch ( IOException x ) { throw new IllegalArgumentException(x); } }
// in java/org/apache/catalina/tribes/membership/McastService.java
protected void hasProperty(Properties properties, String name){ if ( properties.getProperty(name)==null) throw new IllegalArgumentException("McastService:Required property \""+name+"\" is missing."); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public synchronized void start(int level) throws IOException { boolean valid = false; if ( (level & Channel.MBR_RX_SEQ)==Channel.MBR_RX_SEQ ) { if ( receiver != null ) throw new IllegalStateException("McastService.receive already running."); try { if ( sender == null ) socket.joinGroup(address); }catch (IOException iox) { log.error("Unable to join multicast group, make sure your system has multicasting enabled."); throw iox; } doRunReceiver = true; receiver = new ReceiverThread(); receiver.setDaemon(true); receiver.start(); valid = true; } if ( (level & Channel.MBR_TX_SEQ)==Channel.MBR_TX_SEQ ) { if ( sender != null ) throw new IllegalStateException("McastService.send already running."); if ( receiver == null ) socket.joinGroup(address); //make sure at least one packet gets out there send(false); doRunSender = true; sender = new SenderThread(sendFrequency); sender.setDaemon(true); sender.start(); //we have started the receiver, but not yet waited for membership to establish valid = true; } if (!valid) { throw new IllegalArgumentException("Invalid start level. Only acceptable levels are Channel.MBR_RX_SEQ and Channel.MBR_TX_SEQ"); } //pause, once or twice waitForMembers(level); startLevel = (startLevel | level); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public synchronized boolean stop(int level) throws IOException { boolean valid = false; if ( (level & Channel.MBR_RX_SEQ)==Channel.MBR_RX_SEQ ) { valid = true; doRunReceiver = false; if ( receiver !=null ) receiver.interrupt(); receiver = null; } if ( (level & Channel.MBR_TX_SEQ)==Channel.MBR_TX_SEQ ) { valid = true; doRunSender = false; if ( sender != null )sender.interrupt(); sender = null; } if (!valid) { throw new IllegalArgumentException("Invalid stop level. Only acceptable levels are Channel.MBR_RX_SEQ and Channel.MBR_TX_SEQ"); } startLevel = (startLevel & (~level)); //we're shutting down, send a shutdown message and close the socket if ( startLevel == 0 ) { //send a stop message member.setCommand(Member.SHUTDOWN_PAYLOAD); member.getData(true, true); send(false); //leave mcast group try {socket.leaveGroup(address);}catch ( Exception ignore){} try {socket.close();}catch ( Exception ignore){} member.setServiceStartTime(-1); } return (startLevel == 0); }
// in java/org/apache/catalina/tribes/util/StringManager.java
public String getString(String key) { if(key == null){ String msg = "key may not have a null value"; throw new IllegalArgumentException(msg); } String str = null; try { str = bundle.getString(key); } catch(MissingResourceException mre) { //bad: shouldn't mask an exception the following way: // str = "[cannot find message associated with key '" + key + "' due to " + mre + "]"; // because it hides the fact that the String was missing // from the calling code. //good: could just throw the exception (or wrap it in another) // but that would probably cause much havoc on existing // code. //better: consistent with container pattern to // simply return null. Calling code can then do // a null check. str = null; } return str; }
// in java/org/apache/catalina/session/FileStore.java
private File directory() throws IOException { if (this.directory == null) { return (null); } if (this.directoryFile != null) { // NOTE: Race condition is harmless, so do not synchronize return (this.directoryFile); } File file = new File(this.directory); if (!file.isAbsolute()) { Container container = manager.getContainer(); if (container instanceof Context) { ServletContext servletContext = ((Context) container).getServletContext(); File work = (File) servletContext.getAttribute(ServletContext.TEMPDIR); file = new File(work, this.directory); } else { throw new IllegalArgumentException ("Parent Container is not a Context"); } } if (!file.exists() || !file.isDirectory()) { if (!file.delete() && file.exists()) { throw new IOException( sm.getString("fileStore.deleteFailed", file)); } if (!file.mkdirs() && !file.isDirectory()) { throw new IOException( sm.getString("fileStore.createFailed", file)); } } this.directoryFile = file; return (file); }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
Override public void setContainer(Container container) { if (container != null && !(container instanceof Context)) { throw new IllegalArgumentException (sm.getString("authenticator.notContext")); } super.setContainer(container); this.context = (Context) container; }
// in java/org/apache/catalina/deploy/WebXml.java
public void addAfterOrderingOthers() { if (before.contains(ORDER_OTHERS)) { throw new IllegalArgumentException(sm.getString( "webXml.multipleOther")); } after.add(ORDER_OTHERS); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addBeforeOrderingOthers() { if (after.contains(ORDER_OTHERS)) { throw new IllegalArgumentException(sm.getString( "webXml.multipleOther")); } before.add(ORDER_OTHERS); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addFilter(FilterDef filter) { if (filters.containsKey(filter.getFilterName())) { // Filter names must be unique within a web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateFilter", filter.getFilterName())); } filters.put(filter.getFilterName(), filter); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addTaglib(String uri, String location) { if (taglibs.containsKey(uri)) { // Taglib URIs must be unique within a web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateTaglibUri", uri)); } taglibs.put(uri, location); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addEnvEntry(ContextEnvironment envEntry) { if (envEntries.containsKey(envEntry.getName())) { // env-entry names must be unique within a web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateEnvEntry", envEntry.getName())); } envEntries.put(envEntry.getName(),envEntry); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addResourceRef(ContextResource resourceRef) { if (resourceRefs.containsKey(resourceRef.getName())) { // resource-ref names must be unique within a web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateResourceRef", resourceRef.getName())); } resourceRefs.put(resourceRef.getName(), resourceRef); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addResourceEnvRef(ContextResourceEnvRef resourceEnvRef) { if (resourceEnvRefs.containsKey(resourceEnvRef.getName())) { // resource-env-ref names must be unique within a web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateResourceEnvRef", resourceEnvRef.getName())); } resourceEnvRefs.put(resourceEnvRef.getName(), resourceEnvRef); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addMessageDestinationRef( MessageDestinationRef messageDestinationRef) { if (messageDestinationRefs.containsKey( messageDestinationRef.getName())) { // message-destination-ref names must be unique within a // web(-fragment).xml throw new IllegalArgumentException(sm.getString( "webXml.duplicateMessageDestinationRef", messageDestinationRef.getName())); } messageDestinationRefs.put(messageDestinationRef.getName(), messageDestinationRef); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addMessageDestination( MessageDestination messageDestination) { if (messageDestinations.containsKey( messageDestination.getName())) { // message-destination names must be unique within a // web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateMessageDestination", messageDestination.getName())); } messageDestinations.put(messageDestination.getName(), messageDestination); }
// in java/org/apache/catalina/deploy/WebXml.java
public static Set<WebXml> orderWebFragments(WebXml application, Map<String,WebXml> fragments) { Set<WebXml> orderedFragments = new LinkedHashSet<WebXml>(); boolean absoluteOrdering = (application.getAbsoluteOrdering() != null); if (absoluteOrdering) { // Only those fragments listed should be processed Set<String> requestedOrder = application.getAbsoluteOrdering(); for (String requestedName : requestedOrder) { if (WebXml.ORDER_OTHERS.equals(requestedName)) { // Add all fragments not named explicitly at this point for (Entry<String, WebXml> entry : fragments.entrySet()) { if (!requestedOrder.contains(entry.getKey())) { WebXml fragment = entry.getValue(); if (fragment != null) { orderedFragments.add(fragment); } } } } else { WebXml fragment = fragments.get(requestedName); if (fragment != null) { orderedFragments.add(fragment); } else { log.warn(sm.getString("webXml.wrongFragmentName",requestedName)); } } } } else { List<String> order = new LinkedList<String>(); // Start by adding all fragments - order doesn't matter order.addAll(fragments.keySet()); // Now go through and move elements to start/end depending on if // they specify others for (WebXml fragment : fragments.values()) { String name = fragment.getName(); if (fragment.getBeforeOrdering().contains(WebXml.ORDER_OTHERS)) { // Move to beginning order.remove(name); order.add(0, name); } else if (fragment.getAfterOrdering().contains(WebXml.ORDER_OTHERS)) { // Move to end order.remove(name); order.add(name); } } // Now apply remaining ordering for (WebXml fragment : fragments.values()) { String name = fragment.getName(); for (String before : fragment.getBeforeOrdering()) { if (!before.equals(WebXml.ORDER_OTHERS) && order.contains(before) && order.indexOf(before) < order.indexOf(name)) { order.remove(name); order.add(order.indexOf(before), name); } } for (String after : fragment.getAfterOrdering()) { if (!after.equals(WebXml.ORDER_OTHERS) && order.contains(after) && order.indexOf(after) > order.indexOf(name)) { order.remove(name); order.add(order.indexOf(after) + 1, name); } } } // Finally check ordering was applied correctly - if there are // errors then that indicates circular references for (WebXml fragment : fragments.values()) { String name = fragment.getName(); for (String before : fragment.getBeforeOrdering()) { if (!before.equals(WebXml.ORDER_OTHERS) && order.contains(before) && order.indexOf(before) < order.indexOf(name)) { throw new IllegalArgumentException( sm.getString("webXml.mergeConflictOrder")); } } for (String after : fragment.getAfterOrdering()) { if (!after.equals(WebXml.ORDER_OTHERS) && order.contains(after) && order.indexOf(after) > order.indexOf(name)) { throw new IllegalArgumentException( sm.getString("webXml.mergeConflictOrder")); } } } // Build the ordered list for (String name : order) { orderedFragments.add(fragments.get(name)); } } return orderedFragments; }
// in java/org/apache/catalina/ha/session/DeltaSession.java
public void setAttribute(String name, Object value, boolean notify,boolean addDeltaRequest) { // Name cannot be null if (name == null) throw new IllegalArgumentException(sm.getString("standardSession.setAttribute.namenull")); // Null value is the same as removeAttribute() if (value == null) { removeAttribute(name); return; } try { lock(); super.setAttribute(name,value, notify); if (addDeltaRequest && deltaRequest != null && !exclude(name)) { deltaRequest.setAttribute(name, value); } } finally { unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
public void execute(DeltaSession session, boolean notifyListeners) { if ( !this.sessionId.equals( session.getId() ) ) throw new java.lang.IllegalArgumentException("Session id mismatch, not executing the delta request"); session.access(); for ( int i=0; i<actions.size(); i++ ) { AttributeInfo info = actions.get(i); switch ( info.getType() ) { case TYPE_ATTRIBUTE: { if ( info.getAction() == ACTION_SET ) { if ( log.isTraceEnabled() ) log.trace("Session.setAttribute('"+info.getName()+"', '"+info.getValue()+"')"); session.setAttribute(info.getName(), info.getValue(),notifyListeners,false); } else { if ( log.isTraceEnabled() ) log.trace("Session.removeAttribute('"+info.getName()+"')"); session.removeAttribute(info.getName(),notifyListeners,false); } break; }//case case TYPE_ISNEW: { if ( log.isTraceEnabled() ) log.trace("Session.setNew('"+info.getValue()+"')"); session.setNew(((Boolean)info.getValue()).booleanValue(),false); break; }//case case TYPE_MAXINTERVAL: { if ( log.isTraceEnabled() ) log.trace("Session.setMaxInactiveInterval('"+info.getValue()+"')"); session.setMaxInactiveInterval(((Integer)info.getValue()).intValue(),false); break; }//case case TYPE_PRINCIPAL: { Principal p = null; if ( info.getAction() == ACTION_SET ) { SerializablePrincipal sp = (SerializablePrincipal)info.getValue(); p = sp.getPrincipal(); } session.setPrincipal(p,false); break; }//case case TYPE_AUTHTYPE: { String authType = null; if ( info.getAction() == ACTION_SET ) { authType = (String)info.getValue(); } session.setAuthType(authType,false); break; }//case default : throw new java.lang.IllegalArgumentException("Invalid attribute info type="+info); }//switch }//for session.endAccess(); reset(); }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public boolean writeMessage(FileMessage msg) throws IllegalArgumentException, IOException { if (!openForWrite) throw new IllegalArgumentException( "Can't write message, this factory is reading."); if (log.isDebugEnabled()) log.debug("Message " + msg + " data " + HexUtils.toHexString(msg.getData()) + " data length " + msg.getDataLength() + " out " + out); if (msg.getMessageNumber() <= lastMessageProcessed.get()) { // Duplicate of message already processed log.warn("Receive Message again -- Sender ActTimeout too short [ name: " + msg.getContextName() + " war: " + msg.getFileName() + " data: " + HexUtils.toHexString(msg.getData()) + " data length: " + msg.getDataLength() + " ]"); return false; } FileMessage previous = msgBuffer.put(Long.valueOf(msg.getMessageNumber()), msg); if (previous !=null) { // Duplicate of message not yet processed log.warn("Receive Message again -- Sender ActTimeout too short [ name: " + msg.getContextName() + " war: " + msg.getFileName() + " data: " + HexUtils.toHexString(msg.getData()) + " data length: " + msg.getDataLength() + " ]"); return false; } FileMessage next = null; synchronized (this) { if (!isWriting) { next = msgBuffer.get(Long.valueOf(lastMessageProcessed.get() + 1)); if (next != null) { isWriting = true; } else { return false; } } else { return false; } } while (next != null) { out.write(next.getData(), 0, next.getDataLength()); lastMessageProcessed.incrementAndGet(); out.flush(); if (next.getMessageNumber() == next.getTotalNrOfMsgs()) { out.close(); cleanup(); return true; } synchronized(this) { next = msgBuffer.get(Long.valueOf(lastMessageProcessed.get() + 1)); if (next == null) { isWriting = false; } } } return false; }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
protected void checkState(boolean openForWrite) throws IllegalArgumentException { if (this.openForWrite != openForWrite) { cleanup(); if (openForWrite) throw new IllegalArgumentException( "Can't write message, this factory is reading."); else throw new IllegalArgumentException( "Can't read message, this factory is writing."); } if (this.closed) { cleanup(); throw new IllegalArgumentException("Factory has been closed."); } }
// in java/org/apache/catalina/ssi/SSIFsize.java
public String repeat(char aChar, int numChars) { if (numChars < 0) { throw new IllegalArgumentException("Num chars can't be negative"); } StringBuilder buf = new StringBuilder(); for (int i = 0; i < numChars; i++) { buf.append(aChar); } return buf.toString(); }
// in java/org/apache/catalina/ssi/SSIMediator.java
protected String encode(String value, String encoding) { String retVal = null; if (encoding.equalsIgnoreCase("url")) { retVal = urlEncoder.encode(value); } else if (encoding.equalsIgnoreCase("none")) { retVal = value; } else if (encoding.equalsIgnoreCase("entity")) { retVal = HttpMessages.filter(value); } else { //This shouldn't be possible throw new IllegalArgumentException("Unknown encoding: " + encoding); } return retVal; }
// in java/org/apache/catalina/connector/Connector.java
public void setParseBodyMethods(String methods) { HashSet<String> methodSet = new HashSet<String>(); if( null != methods ) { methodSet.addAll(Arrays.asList(methods.split("\\s*,\\s*"))); } if( methodSet.contains("TRACE") ) { throw new IllegalArgumentException(sm.getString("coyoteConnector.parseBodyMethodNoTrace")); } this.parseBodyMethods = methods; this.parseBodyMethodsSet = methodSet; }
// in java/org/apache/catalina/connector/Request.java
Override public void setAttribute(String name, Object value) { // Name cannot be null if (name == null) { throw new IllegalArgumentException (sm.getString("coyoteRequest.setAttribute.namenull")); } // Null value is the same as removeAttribute() if (value == null) { removeAttribute(name); return; } // Special attributes SpecialAttributeAdapter adapter = specialAttributes.get(name); if (adapter != null) { adapter.set(this, name, value); return; } // Add or replace the specified attribute // Check for read only attribute // requests are per thread so synchronization unnecessary if (readOnlyAttributes.containsKey(name)) { return; } // Do the security check before any updates are made if (Globals.IS_SECURITY_ENABLED && name.equals(Globals.SENDFILE_FILENAME_ATTR)) { // Use the canonical file name to avoid any possible symlink and // relative path issues String canonicalPath; try { canonicalPath = new File(value.toString()).getCanonicalPath(); } catch (IOException e) { throw new SecurityException(sm.getString( "coyoteRequest.sendfileNotCanonical", value), e); } // Sendfile is performed in Tomcat's security context so need to // check if the web app is permitted to access the file while still // in the web app's security context System.getSecurityManager().checkRead(canonicalPath); // Update the value so the canonical path is used value = canonicalPath; } Object oldValue = attributes.put(name, value); // Pass special attributes to the native layer if (name.startsWith("org.apache.tomcat.")) { coyoteRequest.setAttribute(name, value); } // Notify interested application event listeners notifyAttributeAssigned(name, value, oldValue); }
// in java/org/apache/catalina/connector/Request.java
Override public long getDateHeader(String name) { String value = getHeader(name); if (value == null) { return (-1L); } // Attempt to convert the date header in a variety of formats long result = FastHttpDateFormat.parseDate(value, formats); if (result != (-1L)) { return result; } throw new IllegalArgumentException(value); }
// in java/org/apache/catalina/connector/Request.java
protected String unescape(String s) { if (s==null) { return null; } if (s.indexOf('\\') == -1) { return s; } StringBuilder buf = new StringBuilder(); for (int i=0; i<s.length(); i++) { char c = s.charAt(i); if (c!='\\') { buf.append(c); } else { if (++i >= s.length()) { throw new IllegalArgumentException();//invalid escape, hence invalid cookie } c = s.charAt(i); buf.append(c); } } return buf.toString(); }
// in java/org/apache/catalina/connector/Response.java
private void normalize(CharChunk cc) { if (cc.endsWith("/.") || cc.endsWith("/..")) { try { cc.append('/'); } catch (IOException e) { throw new IllegalArgumentException(cc.toString(), e); } } char[] c = cc.getChars(); int start = cc.getStart(); int end = cc.getEnd(); int index = 0; int startIndex = 0; // Advance past the first three / characters (should place index just // scheme://host[:port] for (int i = 0; i < 3; i++) { startIndex = cc.indexOf('/', startIndex + 1); } // Remove /./ index = startIndex; while (true) { index = cc.indexOf("/./", 0, 3, index); if (index < 0) { break; } copyChars(c, start + index, start + index + 2, end - start - index - 2); end = end - 2; cc.setEnd(end); } // Remove /../ index = startIndex; int pos; while (true) { index = cc.indexOf("/../", 0, 4, index); if (index < 0) { break; } // Prevent from going outside our context if (index == startIndex) { throw new IllegalArgumentException(); } int index2 = -1; for (pos = start + index - 1; (pos >= 0) && (index2 < 0); pos --) { if (c[pos] == (byte) '/') { index2 = pos; } } copyChars(c, start + index2, start + index + 3, end - start - index - 3); end = end + index2 - index - 3; cc.setEnd(end); index = index2; }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public long skip(long n) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } if (n < 0) { throw new IllegalArgumentException(); } long nRead = 0; while (nRead < n) { if (cb.getLength() >= n) { cb.setOffset(cb.getStart() + (int) n); nRead = n; } else { nRead += cb.getLength(); cb.setOffset(cb.getEnd()); int toRead = 0; if (cb.getChars().length < (n - nRead)) { toRead = cb.getChars().length; } else { toRead = (int) (n - nRead); } int nb = realReadChars(cb.getChars(), 0, toRead); if (nb < 0) { break; } } } return nRead; }
// in java/org/apache/catalina/core/ApplicationFilterRegistration.java
Override public boolean setInitParameter(String name, String value) { if (name == null || value == null) { throw new IllegalArgumentException( sm.getString("applicationFilterRegistration.nullInitParam", name, value)); } if (getInitParameter(name) != null) { return false; } filterDef.addInitParameter(name, value); return true; }
// in java/org/apache/catalina/core/ApplicationFilterRegistration.java
Override public Set<String> setInitParameters(Map<String, String> initParameters) { Set<String> conflicts = new HashSet<String>(); for (Map.Entry<String, String> entry : initParameters.entrySet()) { if (entry.getKey() == null || entry.getValue() == null) { throw new IllegalArgumentException(sm.getString( "applicationFilterRegistration.nullInitParams", entry.getKey(), entry.getValue())); } if (getInitParameter(entry.getKey()) != null) { conflicts.add(entry.getKey()); } } // Have to add in a separate loop since spec requires no updates at all // if there is an issue for (Map.Entry<String, String> entry : initParameters.entrySet()) { setInitParameter(entry.getKey(), entry.getValue()); } return conflicts; }
// in java/org/apache/catalina/core/StandardHost.java
Override public void setName(String name) { if (name == null) throw new IllegalArgumentException (sm.getString("standardHost.nullName")); name = name.toLowerCase(Locale.ENGLISH); // Internally all names are lower case String oldName = this.name; this.name = name; support.firePropertyChange("name", oldName, this.name); }
// in java/org/apache/catalina/core/StandardHost.java
Override public void addChild(Container child) { child.addLifecycleListener(new MemoryLeakTrackingListener()); if (!(child instanceof Context)) throw new IllegalArgumentException (sm.getString("standardHost.notContext")); super.addChild(child); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public RequestDispatcher getRequestDispatcher(String path) { // Validate the path argument if (path == null) return (null); if (!path.startsWith("/")) throw new IllegalArgumentException (sm.getString ("applicationContext.requestDispatcher.iae", path)); // Get query string String queryString = null; String normalizedPath = path; int pos = normalizedPath.indexOf('?'); if (pos >= 0) { queryString = normalizedPath.substring(pos + 1); normalizedPath = normalizedPath.substring(0, pos); } normalizedPath = RequestUtil.normalize(normalizedPath); if (normalizedPath == null) return (null); pos = normalizedPath.length(); // Use the thread local URI and mapping data DispatchData dd = dispatchData.get(); if (dd == null) { dd = new DispatchData(); dispatchData.set(dd); } MessageBytes uriMB = dd.uriMB; uriMB.recycle(); // Use the thread local mapping data MappingData mappingData = dd.mappingData; // Map the URI CharChunk uriCC = uriMB.getCharChunk(); try { uriCC.append(context.getPath(), 0, context.getPath().length()); /* * Ignore any trailing path params (separated by ';') for mapping * purposes */ int semicolon = normalizedPath.indexOf(';'); if (pos >= 0 && semicolon > pos) { semicolon = -1; } uriCC.append(normalizedPath, 0, semicolon > 0 ? semicolon : pos); context.getMapper().map(uriMB, mappingData); if (mappingData.wrapper == null) { return (null); } /* * Append any trailing path params (separated by ';') that were * ignored for mapping purposes, so that they're reflected in the * RequestDispatcher's requestURI */ if (semicolon > 0) { uriCC.append(normalizedPath, semicolon, pos - semicolon); } } catch (Exception e) { // Should never happen log(sm.getString("applicationContext.mapping.error"), e); return (null); } Wrapper wrapper = (Wrapper) mappingData.wrapper; String wrapperPath = mappingData.wrapperPath.toString(); String pathInfo = mappingData.pathInfo.toString(); mappingData.recycle(); // Construct a RequestDispatcher to process this request return new ApplicationDispatcher (wrapper, uriCC.toString(), wrapperPath, pathInfo, queryString, null); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public Set<String> getResourcePaths(String path) { // Validate the path argument if (path == null) { return null; } if (!path.startsWith("/")) { throw new IllegalArgumentException (sm.getString("applicationContext.resourcePaths.iae", path)); } String normalizedPath = RequestUtil.normalize(path); if (normalizedPath == null) return (null); DirContext resources = context.getResources(); if (resources != null) { return (getResourcePathsInternal(resources, normalizedPath)); } return (null); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public void setAttribute(String name, Object value) { // Name cannot be null if (name == null) throw new IllegalArgumentException (sm.getString("applicationContext.setAttribute.namenull")); // Null value is the same as removeAttribute() if (value == null) { removeAttribute(name); return; } Object oldValue = null; boolean replaced = false; // Add or replace the specified attribute // Check for read only attribute if (readOnlyAttributes.containsKey(name)) return; oldValue = attributes.get(name); if (oldValue != null) replaced = true; attributes.put(name, value); // Notify interested application event listeners Object listeners[] = context.getApplicationEventListeners(); if ((listeners == null) || (listeners.length == 0)) return; ServletContextAttributeEvent event = null; if (replaced) event = new ServletContextAttributeEvent(context.getServletContext(), name, oldValue); else event = new ServletContextAttributeEvent(context.getServletContext(), name, value); for (int i = 0; i < listeners.length; i++) { if (!(listeners[i] instanceof ServletContextAttributeListener)) continue; ServletContextAttributeListener listener = (ServletContextAttributeListener) listeners[i]; try { if (replaced) { context.fireContainerEvent ("beforeContextAttributeReplaced", listener); listener.attributeReplaced(event); context.fireContainerEvent("afterContextAttributeReplaced", listener); } else { context.fireContainerEvent("beforeContextAttributeAdded", listener); listener.attributeAdded(event); context.fireContainerEvent("afterContextAttributeAdded", listener); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (replaced) context.fireContainerEvent("afterContextAttributeReplaced", listener); else context.fireContainerEvent("afterContextAttributeAdded", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); } } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public void setSessionTrackingModes( Set<SessionTrackingMode> sessionTrackingModes) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException( sm.getString("applicationContext.setSessionTracking.ise", getContextPath())); } // Check that only supported tracking modes have been requested for (SessionTrackingMode sessionTrackingMode : sessionTrackingModes) { if (!supportedSessionTrackingModes.contains(sessionTrackingMode)) { throw new IllegalArgumentException(sm.getString( "applicationContext.setSessionTracking.iae.invalid", sessionTrackingMode.toString(), getContextPath())); } } // Check SSL has not be configured with anything else if (sessionTrackingModes.contains(SessionTrackingMode.SSL)) { if (sessionTrackingModes.size() > 1) { throw new IllegalArgumentException(sm.getString( "applicationContext.setSessionTracking.iae.ssl", getContextPath())); } } this.sessionTrackingModes = sessionTrackingModes; }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public void addListener(Class<? extends EventListener> listenerClass) { EventListener listener; try { listener = createListener(listenerClass); } catch (ServletException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.init", listenerClass.getName()), e); } addListener(listener); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public void addListener(String className) { try { Object obj = context.getInstanceManager().newInstance(className); if (!(obj instanceof EventListener)) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", className)); } EventListener listener = (EventListener) obj; addListener(listener); } catch (IllegalAccessException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (NamingException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (InstantiationException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends EventListener> void addListener(T t) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException( sm.getString("applicationContext.addListener.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. boolean match = false; if (t instanceof ServletContextAttributeListener || t instanceof ServletRequestListener || t instanceof ServletRequestAttributeListener || t instanceof HttpSessionAttributeListener) { context.addApplicationEventListener(t); match = true; } if (t instanceof HttpSessionListener || (t instanceof ServletContextListener && newServletContextListenerAllowed)) { context.addApplicationLifecycleListener(t); match = true; } if (match) return; if (t instanceof ServletContextListener) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.sclNotAllowed", t.getClass().getName())); } else { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", t.getClass().getName())); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends EventListener> T createListener(Class<T> c) throws ServletException { try { @SuppressWarnings("unchecked") T listener = (T) context.getInstanceManager().newInstance(c.getName()); if (listener instanceof ServletContextListener || listener instanceof ServletContextAttributeListener || listener instanceof ServletRequestListener || listener instanceof ServletRequestAttributeListener || listener instanceof HttpSessionListener || listener instanceof HttpSessionAttributeListener) { return listener; } throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", listener.getClass().getName())); } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public void declareRoles(String... roleNames) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addRole.ise", getContextPath())); } if (roleNames == null) { throw new IllegalArgumentException( sm.getString("applicationContext.roles.iae", getContextPath())); } for (String role : roleNames) { if (role == null || "".equals(role)) { throw new IllegalArgumentException( sm.getString("applicationContext.role.iae", getContextPath())); } context.addSecurityRole(role); } }
// in java/org/apache/catalina/core/ContainerBase.java
private void addChildInternal(Container child) { if( log.isDebugEnabled() ) log.debug("Add child " + child + " " + this); synchronized(children) { if (children.get(child.getName()) != null) throw new IllegalArgumentException("addChild: Child name '" + child.getName() + "' is not unique"); child.setParent(this); // May throw IAE children.put(child.getName(), child); } // Start child // Don't do this inside sync block - start can be a slow process and // locking the children object can cause problems elsewhere if ((getState().isAvailable() || LifecycleState.STARTING_PREP.equals(getState())) && startChildren) { try { child.start(); } catch (LifecycleException e) { log.error("ContainerBase.addChild: start: ", e); throw new IllegalStateException ("ContainerBase.addChild: start: " + e); } } fireContainerEvent(ADD_CHILD_EVENT, child); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected void populateAnnotationsCache(Class<?> clazz, Map<String, String> injections) throws IllegalAccessException, InvocationTargetException, NamingException { List<AnnotationCacheEntry> annotations = null; while (clazz != null) { AnnotationCacheEntry[] annotationsArray = null; synchronized (annotationCache) { annotationsArray = annotationCache.get(clazz); } if (annotationsArray == null) { if (annotations == null) { annotations = new ArrayList<AnnotationCacheEntry>(); } else { annotations.clear(); } if (context != null) { // Initialize fields annotations for resource injection if // JNDI is enabled Field[] fields = null; if (Globals.IS_SECURITY_ENABLED) { final Class<?> clazz2 = clazz; fields = AccessController.doPrivileged( new PrivilegedAction<Field[]>(){ @Override public Field[] run(){ return clazz2.getDeclaredFields(); } }); } else { fields = clazz.getDeclaredFields(); } for (Field field : fields) { if (injections != null && injections.containsKey(field.getName())) { annotations.add(new AnnotationCacheEntry( field.getName(), null, injections.get(field.getName()), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(Resource.class)) { Resource annotation = field.getAnnotation(Resource.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(EJB.class)) { EJB annotation = field.getAnnotation(EJB.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(WebServiceRef.class)) { WebServiceRef annotation = field.getAnnotation(WebServiceRef.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(PersistenceContext.class)) { PersistenceContext annotation = field.getAnnotation(PersistenceContext.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(PersistenceUnit.class)) { PersistenceUnit annotation = field.getAnnotation(PersistenceUnit.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } } } // Initialize methods annotations Method[] methods = null; if (Globals.IS_SECURITY_ENABLED) { final Class<?> clazz2 = clazz; methods = AccessController.doPrivileged( new PrivilegedAction<Method[]>(){ @Override public Method[] run(){ return clazz2.getDeclaredMethods(); } }); } else { methods = clazz.getDeclaredMethods(); } Method postConstruct = null; Method preDestroy = null; for (Method method : methods) { String methodName = method.getName(); if (context != null) { // Resource injection only if JNDI is enabled if (injections != null && methodName.startsWith("set") && methodName.length() > 3) { String fieldName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); if (injections.containsKey(fieldName)) { annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), injections.get(method.getName()), AnnotationCacheEntryType.SETTER)); break; } } if (method.isAnnotationPresent(Resource.class)) { Resource annotation = method.getAnnotation(Resource.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(EJB.class)) { EJB annotation = method.getAnnotation(EJB.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(WebServiceRef.class)) { WebServiceRef annotation = method.getAnnotation(WebServiceRef.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(PersistenceContext.class)) { PersistenceContext annotation = method.getAnnotation(PersistenceContext.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(PersistenceUnit.class)) { PersistenceUnit annotation = method.getAnnotation(PersistenceUnit.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } } if (method.isAnnotationPresent(PostConstruct.class)) { if ((postConstruct != null) || (method.getParameterTypes().length != 0) || (Modifier.isStatic(method.getModifiers())) || (method.getExceptionTypes().length > 0) || (!method.getReturnType().getName().equals("void"))) { throw new IllegalArgumentException( "Invalid PostConstruct annotation"); } postConstruct = method; } if (method.isAnnotationPresent(PreDestroy.class)) { if ((preDestroy != null || method.getParameterTypes().length != 0) || (Modifier.isStatic(method.getModifiers())) || (method.getExceptionTypes().length > 0) || (!method.getReturnType().getName().equals("void"))) { throw new IllegalArgumentException( "Invalid PreDestroy annotation"); } preDestroy = method; } } if (postConstruct != null) { annotations.add(new AnnotationCacheEntry( postConstruct.getName(), postConstruct.getParameterTypes(), null, AnnotationCacheEntryType.POST_CONSTRUCT)); } if (preDestroy != null) { annotations.add(new AnnotationCacheEntry( preDestroy.getName(), preDestroy.getParameterTypes(), null, AnnotationCacheEntryType.PRE_DESTROY)); } if (annotations.isEmpty()) { // Use common object to save memory annotationsArray = ANNOTATIONS_EMPTY; } else { annotationsArray = annotations.toArray( new AnnotationCacheEntry[annotations.size()]); } synchronized (annotationCache) { annotationCache.put(clazz, annotationsArray); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected static void lookupMethodResource(Context context, Object instance, Method method, String name, Class<?> clazz) throws NamingException, IllegalAccessException, InvocationTargetException { if (!method.getName().startsWith("set") || method.getName().length() < 4 || method.getParameterTypes().length != 1 || !method.getReturnType().getName().equals("void")) { throw new IllegalArgumentException("Invalid method resource injection annotation"); } Object lookedupResource; boolean accessibility; String normalizedName = normalize(name); if ((normalizedName != null) && (normalizedName.length() > 0)) { lookedupResource = context.lookup(normalizedName); } else { lookedupResource = context.lookup( clazz.getName() + "/" + getName(method)); } synchronized (method) { accessibility = method.isAccessible(); method.setAccessible(true); method.invoke(instance, lookedupResource); method.setAccessible(accessibility); } }
// in java/org/apache/catalina/core/NamingContextListener.java
public void addEnvironment(ContextEnvironment env) { Object value = null; // Instantiating a new instance of the correct object type, and // initializing it. String type = env.getType(); try { if (type.equals("java.lang.String")) { value = env.getValue(); } else if (type.equals("java.lang.Byte")) { if (env.getValue() == null) { value = Byte.valueOf((byte) 0); } else { value = Byte.decode(env.getValue()); } } else if (type.equals("java.lang.Short")) { if (env.getValue() == null) { value = Short.valueOf((short) 0); } else { value = Short.decode(env.getValue()); } } else if (type.equals("java.lang.Integer")) { if (env.getValue() == null) { value = Integer.valueOf(0); } else { value = Integer.decode(env.getValue()); } } else if (type.equals("java.lang.Long")) { if (env.getValue() == null) { value = Long.valueOf(0); } else { value = Long.decode(env.getValue()); } } else if (type.equals("java.lang.Boolean")) { value = Boolean.valueOf(env.getValue()); } else if (type.equals("java.lang.Double")) { if (env.getValue() == null) { value = Double.valueOf(0); } else { value = Double.valueOf(env.getValue()); } } else if (type.equals("java.lang.Float")) { if (env.getValue() == null) { value = Float.valueOf(0); } else { value = Float.valueOf(env.getValue()); } } else if (type.equals("java.lang.Character")) { if (env.getValue() == null) { value = Character.valueOf((char) 0); } else { if (env.getValue().length() == 1) { value = Character.valueOf(env.getValue().charAt(0)); } else { throw new IllegalArgumentException(); } } } else { logger.error(sm.getString("naming.invalidEnvEntryType", env.getName())); } } catch (NumberFormatException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", env.getName())); } catch (IllegalArgumentException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", env.getName())); } // Binding the object to the appropriate name if (value != null) { try { if (logger.isDebugEnabled()) logger.debug(" Adding environment entry " + env.getName()); createSubcontexts(envCtx, env.getName()); envCtx.bind(env.getName(), value); } catch (NamingException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", e)); } } }
// in java/org/apache/catalina/core/StandardContext.java
Override public void setLoginConfig(LoginConfig config) { // Validate the incoming property value if (config == null) throw new IllegalArgumentException (sm.getString("standardContext.loginConfig.required")); String loginPage = config.getLoginPage(); if ((loginPage != null) && !loginPage.startsWith("/")) { if (isServlet22()) { if(log.isDebugEnabled()) log.debug(sm.getString("standardContext.loginConfig.loginWarning", loginPage)); config.setLoginPage("/" + loginPage); } else { throw new IllegalArgumentException (sm.getString("standardContext.loginConfig.loginPage", loginPage)); } } String errorPage = config.getErrorPage(); if ((errorPage != null) && !errorPage.startsWith("/")) { if (isServlet22()) { if(log.isDebugEnabled()) log.debug(sm.getString("standardContext.loginConfig.errorWarning", errorPage)); config.setErrorPage("/" + errorPage); } else { throw new IllegalArgumentException (sm.getString("standardContext.loginConfig.errorPage", errorPage)); } } // Process the property setting change LoginConfig oldLoginConfig = this.loginConfig; this.loginConfig = config; support.firePropertyChange("loginConfig", oldLoginConfig, this.loginConfig); }
// in java/org/apache/catalina/core/StandardContext.java
Override public void setWrapperClass(String wrapperClassName) { this.wrapperClassName = wrapperClassName; try { wrapperClass = Class.forName(wrapperClassName); if (!StandardWrapper.class.isAssignableFrom(wrapperClass)) { throw new IllegalArgumentException( sm.getString("standardContext.invalidWrapperClass", wrapperClassName)); } } catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException(cnfe.getMessage()); } }
// in java/org/apache/catalina/core/StandardContext.java
Override public void addChild(Container child) { // Global JspServlet Wrapper oldJspServlet = null; if (!(child instanceof Wrapper)) { throw new IllegalArgumentException (sm.getString("standardContext.notWrapper")); } boolean isJspServlet = "jsp".equals(child.getName()); // Allow webapp to override JspServlet inherited from global web.xml. if (isJspServlet) { oldJspServlet = (Wrapper) findChild("jsp"); if (oldJspServlet != null) { removeChild(oldJspServlet); } } super.addChild(child); if (isJspServlet && oldJspServlet != null) { /* * The webapp-specific JspServlet inherits all the mappings * specified in the global web.xml, and may add additional ones. */ String[] jspMappings = oldJspServlet.findMappings(); for (int i=0; jspMappings!=null && i<jspMappings.length; i++) { addServletMapping(jspMappings[i], child.getName()); } } }
// in java/org/apache/catalina/core/StandardContext.java
Override public void addConstraint(SecurityConstraint constraint) { // Validate the proposed constraint SecurityCollection collections[] = constraint.findCollections(); for (int i = 0; i < collections.length; i++) { String patterns[] = collections[i].findPatterns(); for (int j = 0; j < patterns.length; j++) { patterns[j] = adjustURLPattern(patterns[j]); if (!validateURLPattern(patterns[j])) throw new IllegalArgumentException (sm.getString ("standardContext.securityConstraint.pattern", patterns[j])); } if (collections[i].findMethods().length > 0 && collections[i].findOmittedMethods().length > 0) { throw new IllegalArgumentException(sm.getString( "standardContext.securityConstraint.mixHttpMethod")); } } // Add this constraint to the set for our web application synchronized (constraintsLock) { SecurityConstraint results[] = new SecurityConstraint[constraints.length + 1]; for (int i = 0; i < constraints.length; i++) results[i] = constraints[i]; results[constraints.length] = constraint; constraints = results; } }
// in java/org/apache/catalina/core/StandardContext.java
Override public void addErrorPage(ErrorPage errorPage) { // Validate the input parameters if (errorPage == null) throw new IllegalArgumentException (sm.getString("standardContext.errorPage.required")); String location = errorPage.getLocation(); if ((location != null) && !location.startsWith("/")) { if (isServlet22()) { if(log.isDebugEnabled()) log.debug(sm.getString("standardContext.errorPage.warning", location)); errorPage.setLocation("/" + location); } else { throw new IllegalArgumentException (sm.getString("standardContext.errorPage.error", location)); } } // Add the specified error page to our internal collections String exceptionType = errorPage.getExceptionType(); if (exceptionType != null) { synchronized (exceptionPages) { exceptionPages.put(exceptionType, errorPage); } } else { synchronized (statusPages) { if (errorPage.getErrorCode() == 200) { this.okErrorPage = errorPage; } statusPages.put(Integer.valueOf(errorPage.getErrorCode()), errorPage); } } fireContainerEvent("addErrorPage", errorPage); }
// in java/org/apache/catalina/core/StandardContext.java
private void validateFilterMap(FilterMap filterMap) { // Validate the proposed filter mapping String filterName = filterMap.getFilterName(); String[] servletNames = filterMap.getServletNames(); String[] urlPatterns = filterMap.getURLPatterns(); if (findFilterDef(filterName) == null) throw new IllegalArgumentException (sm.getString("standardContext.filterMap.name", filterName)); if (!filterMap.getMatchAllServletNames() && !filterMap.getMatchAllUrlPatterns() && (servletNames.length == 0) && (urlPatterns.length == 0)) throw new IllegalArgumentException (sm.getString("standardContext.filterMap.either")); // FIXME: Older spec revisions may still check this /* if ((servletNames.length != 0) && (urlPatterns.length != 0)) throw new IllegalArgumentException (sm.getString("standardContext.filterMap.either")); */ for (int i = 0; i < urlPatterns.length; i++) { if (!validateURLPattern(urlPatterns[i])) { throw new IllegalArgumentException (sm.getString("standardContext.filterMap.pattern", urlPatterns[i])); } } }
// in java/org/apache/catalina/core/StandardContext.java
Override public void addParameter(String name, String value) { // Validate the proposed context initialization parameter if ((name == null) || (value == null)) throw new IllegalArgumentException (sm.getString("standardContext.parameter.required")); if (parameters.get(name) != null) throw new IllegalArgumentException (sm.getString("standardContext.parameter.duplicate", name)); // Add this parameter to our defined set synchronized (parameters) { parameters.put(name, value); } fireContainerEvent("addParameter", name); }
// in java/org/apache/catalina/core/StandardContext.java
Override public void addServletMapping(String pattern, String name, boolean jspWildCard) { // Validate the proposed mapping if (findChild(name) == null) throw new IllegalArgumentException (sm.getString("standardContext.servletMap.name", name)); String decodedPattern = adjustURLPattern(RequestUtil.URLDecode(pattern)); if (!validateURLPattern(decodedPattern)) throw new IllegalArgumentException (sm.getString("standardContext.servletMap.pattern", decodedPattern)); // Add this mapping to our registered set synchronized (servletMappingsLock) { String name2 = servletMappings.get(decodedPattern); if (name2 != null) { // Don't allow more than one servlet on the same pattern Wrapper wrapper = (Wrapper) findChild(name2); wrapper.removeMapping(decodedPattern); mapper.removeWrapper(decodedPattern); } servletMappings.put(decodedPattern, name); } Wrapper wrapper = (Wrapper) findChild(name); wrapper.addMapping(decodedPattern); // Update context mapper mapper.addWrapper(decodedPattern, wrapper, jspWildCard, resourceOnlyServlets.contains(name)); fireContainerEvent("addServletMapping", decodedPattern); }
// in java/org/apache/catalina/core/StandardContext.java
Override public void removeChild(Container child) { if (!(child instanceof Wrapper)) { throw new IllegalArgumentException (sm.getString("standardContext.notWrapper")); } super.removeChild(child); }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public void setParent(Container container) { if ((container != null) && !(container instanceof Context)) throw new IllegalArgumentException (sm.getString("standardWrapper.notContext")); if (container instanceof StandardContext) { swallowOutput = ((StandardContext)container).getSwallowOutput(); unloadDelay = ((StandardContext)container).getUnloadDelay(); } super.setParent(container); }
// in java/org/apache/catalina/core/ApplicationServletRegistration.java
Override public boolean setInitParameter(String name, String value) { if (name == null || value == null) { throw new IllegalArgumentException( sm.getString("applicationFilterRegistration.nullInitParam", name, value)); } if (getInitParameter(name) != null) { return false; } wrapper.addInitParameter(name, value); return true; }
// in java/org/apache/catalina/core/ApplicationServletRegistration.java
Override public Set<String> setInitParameters(Map<String, String> initParameters) { Set<String> conflicts = new HashSet<String>(); for (Map.Entry<String, String> entry : initParameters.entrySet()) { if (entry.getKey() == null || entry.getValue() == null) { throw new IllegalArgumentException(sm.getString( "applicationFilterRegistration.nullInitParams", entry.getKey(), entry.getValue())); } if (getInitParameter(entry.getKey()) != null) { conflicts.add(entry.getKey()); } } // Have to add in a separate loop since spec requires no updates at all // if there is an issue if (conflicts.isEmpty()) { for (Map.Entry<String, String> entry : initParameters.entrySet()) { setInitParameter(entry.getKey(), entry.getValue()); } } return conflicts; }
// in java/org/apache/catalina/core/ApplicationServletRegistration.java
Override public Set<String> setServletSecurity(ServletSecurityElement constraint) { if (constraint == null) { throw new IllegalArgumentException(sm.getString( "applicationServletRegistration.setServletSecurity.iae", getName(), context.getName())); } if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException(sm.getString( "applicationServletRegistration.setServletSecurity.ise", getName(), context.getName())); } return context.addServletSecurity(this, constraint); }
// in java/org/apache/catalina/core/StandardEngine.java
Override public void addChild(Container child) { if (!(child instanceof Host)) throw new IllegalArgumentException (sm.getString("standardEngine.notHost")); super.addChild(child); }
// in java/org/apache/catalina/core/StandardEngine.java
Override public void setParent(Container container) { throw new IllegalArgumentException (sm.getString("standardEngine.notParent")); }
// in java/org/apache/catalina/util/RequestUtil.java
public static String URLDecode(byte[] bytes, String enc, boolean isQuery) { if (bytes == null) return null; int len = bytes.length; int ix = 0; int ox = 0; while (ix < len) { byte b = bytes[ix++]; // Get byte to test if (b == '+' && isQuery) { b = (byte)' '; } else if (b == '%') { if (ix + 2 > len) { throw new IllegalArgumentException( sm.getString("requestUtil.urlDecode.missingDigit")); } b = (byte) ((convertHexDigit(bytes[ix++]) << 4) + convertHexDigit(bytes[ix++])); } bytes[ox++] = b; } if (enc != null) { try { return new String(bytes, 0, ox, B2CConverter.getCharset(enc)); } catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee); } return null; } } return new String(bytes, 0, ox); }
// in java/org/apache/catalina/util/RequestUtil.java
private static byte convertHexDigit( byte b ) { if ((b >= '0') && (b <= '9')) return (byte)(b - '0'); if ((b >= 'a') && (b <= 'f')) return (byte)(b - 'a' + 10); if ((b >= 'A') && (b <= 'F')) return (byte)(b - 'A' + 10); throw new IllegalArgumentException( sm.getString("requestUtil.convertHexDigit.notHex", Character.valueOf((char)b))); }
// in java/javax/servlet/http/HttpUtils.java
public static Hashtable<String,String[]> parsePostData(int len, ServletInputStream in) { // XXX // should a length of 0 be an IllegalArgumentException // cheap hack to return an empty hash if (len <=0) return new Hashtable<String,String[]>(); if (in == null) { throw new IllegalArgumentException(); } // Make sure we read the entire POSTed body. byte[] postedBytes = new byte [len]; try { int offset = 0; do { int inputLen = in.read (postedBytes, offset, len - offset); if (inputLen <= 0) { String msg = lStrings.getString("err.io.short_read"); throw new IllegalArgumentException (msg); } offset += inputLen; } while ((len - offset) > 0); } catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); } // XXX we shouldn't assume that the only kind of POST body // is FORM data encoded using ASCII or ISO Latin/1 ... or // that the body should always be treated as FORM data. try { String postedBody = new String(postedBytes, 0, len, "8859_1"); return parseQueryString(postedBody); } catch (java.io.UnsupportedEncodingException e) { // XXX function should accept an encoding parameter & throw this // exception. Otherwise throw something expected. throw new IllegalArgumentException(e.getMessage(), e); } }
// in java/javax/servlet/http/HttpUtils.java
private static String parseName(String s, StringBuilder sb) { sb.setLength(0); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '+': sb.append(' '); break; case '%': try { sb.append((char) Integer.parseInt(s.substring(i+1, i+3), 16)); i += 2; } catch (NumberFormatException e) { // XXX // need to be more specific about illegal arg throw new IllegalArgumentException(); } catch (StringIndexOutOfBoundsException e) { String rest = s.substring(i); sb.append(rest); if (rest.length()==2) i++; } break; default: sb.append(c); break; } } return sb.toString(); }
// in java/javax/servlet/ServletResponseWrapper.java
public void setResponse(ServletResponse response) { if (response == null) { throw new IllegalArgumentException("Response cannot be null"); } this.response = response; }
// in java/javax/servlet/ServletSecurityElement.java
private void addHttpMethodConstraints( Collection<HttpMethodConstraintElement> httpMethodConstraints) { if (httpMethodConstraints == null) { return; } for (HttpMethodConstraintElement constraint : httpMethodConstraints) { String method = constraint.getMethodName(); if (methodConstraints.containsKey(method)) { throw new IllegalArgumentException( "Duplicate method name: " + method); } methodConstraints.put(method, constraint); } }
// in java/javax/servlet/ServletRequestWrapper.java
public void setRequest(ServletRequest request) { if (request == null) { throw new IllegalArgumentException("Request cannot be null"); } this.request = request; }
// in java/javax/el/ArrayELResolver.java
private static final int coerce(Object property) { if (property instanceof Number) { return ((Number) property).intValue(); } if (property instanceof Character) { return ((Character) property).charValue(); } if (property instanceof Boolean) { return (((Boolean) property).booleanValue() ? 1 : 0); } if (property instanceof String) { return Integer.parseInt((String) property); } throw new IllegalArgumentException(property != null ? property.toString() : "null"); }
// in java/javax/el/ListELResolver.java
private static final int coerce(Object property) { if (property instanceof Number) { return ((Number) property).intValue(); } if (property instanceof Character) { return ((Character) property).charValue(); } if (property instanceof Boolean) { return (((Boolean) property).booleanValue() ? 1 : 0); } if (property instanceof String) { return Integer.parseInt((String) property); } throw new IllegalArgumentException(property != null ? property.toString() : "null"); }
19
              
// in java/org/apache/naming/resources/WARDirContext.java
catch (Exception e) { throw new IllegalArgumentException (sm.getString("warResources.invalidWar", e.getMessage())); }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (Exception e) { throw new IllegalArgumentException(sm.getString( "resources.invalidCache", cacheClassName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { throw new IllegalArgumentException( sm.getString("webappClassLoader.validationErrorJarPath", jarEntry2.getName()), ioe); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( IOException x ) { throw new IllegalArgumentException(x); }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { throw new IllegalArgumentException(cc.toString(), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ServletException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.init", listenerClass.getName()), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException(cnfe.getMessage()); }
// in java/org/apache/catalina/util/CharsetMapper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new IllegalArgumentException(t.toString()); }
// in java/javax/servlet/http/HttpUtils.java
catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); }
// in java/javax/servlet/http/HttpUtils.java
catch (java.io.UnsupportedEncodingException e) { // XXX function should accept an encoding parameter & throw this // exception. Otherwise throw something expected. throw new IllegalArgumentException(e.getMessage(), e); }
// in java/javax/servlet/http/HttpUtils.java
catch (NumberFormatException e) { // XXX // need to be more specific about illegal arg throw new IllegalArgumentException(); }
9
              
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) throws IOException, IllegalStateException, IllegalArgumentException { }
// in java/org/apache/tomcat/util/modeler/BaseNotificationBroadcaster.java
Override public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException { synchronized (entries) { // Optimization to coalesce attribute name filters if (filter instanceof BaseAttributeFilter) { BaseAttributeFilter newFilter = (BaseAttributeFilter) filter; Iterator<BaseNotificationBroadcasterEntry> items = entries.iterator(); while (items.hasNext()) { BaseNotificationBroadcasterEntry item = items.next(); if ((item.listener == listener) && (item.filter != null) && (item.filter instanceof BaseAttributeFilter) && (item.handback == handback)) { BaseAttributeFilter oldFilter = (BaseAttributeFilter) item.filter; String newNames[] = newFilter.getNames(); String oldNames[] = oldFilter.getNames(); if (newNames.length == 0) { oldFilter.clear(); } else { if (oldNames.length != 0) { for (int i = 0; i < newNames.length; i++) oldFilter.addAttribute(newNames[i]); } } return; } } } // General purpose addition of a new entry entries.add(new BaseNotificationBroadcasterEntry (listener, filter, handback)); } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void addAttributeChangeNotificationListener (NotificationListener listener, String name, Object handback) throws IllegalArgumentException { if (listener == null) throw new IllegalArgumentException("Listener is null"); if (attributeBroadcaster == null) attributeBroadcaster = new BaseNotificationBroadcaster(); if( log.isDebugEnabled() ) log.debug("addAttributeNotificationListener " + listener); BaseAttributeFilter filter = new BaseAttributeFilter(name); attributeBroadcaster.addNotificationListener (listener, filter, handback); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException { if (listener == null) throw new IllegalArgumentException("Listener is null"); if( log.isDebugEnabled() ) log.debug("addNotificationListener " + listener); if (generalBroadcaster == null) generalBroadcaster = new BaseNotificationBroadcaster(); generalBroadcaster.addNotificationListener (listener, filter, handback); // We'll send the attribute change notifications to all listeners ( who care ) // The normal filtering can be used. // The problem is that there is no other way to add attribute change listeners // to a model mbean ( AFAIK ). I suppose the spec should be fixed. if (attributeBroadcaster == null) attributeBroadcaster = new BaseNotificationBroadcaster(); if( log.isDebugEnabled() ) log.debug("addAttributeNotificationListener " + listener); attributeBroadcaster.addNotificationListener (listener, filter, handback); }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public FileMessage readMessage(FileMessage f) throws IllegalArgumentException, IOException { checkState(false); int length = in.read(data); if (length == -1) { cleanup(); return null; } else { f.setData(data, length); f.setTotalLength(size); f.setTotalNrOfMsgs(totalNrOfMessages); f.setMessageNumber(++nrOfMessagesProcessed); return f; }//end if }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public boolean writeMessage(FileMessage msg) throws IllegalArgumentException, IOException { if (!openForWrite) throw new IllegalArgumentException( "Can't write message, this factory is reading."); if (log.isDebugEnabled()) log.debug("Message " + msg + " data " + HexUtils.toHexString(msg.getData()) + " data length " + msg.getDataLength() + " out " + out); if (msg.getMessageNumber() <= lastMessageProcessed.get()) { // Duplicate of message already processed log.warn("Receive Message again -- Sender ActTimeout too short [ name: " + msg.getContextName() + " war: " + msg.getFileName() + " data: " + HexUtils.toHexString(msg.getData()) + " data length: " + msg.getDataLength() + " ]"); return false; } FileMessage previous = msgBuffer.put(Long.valueOf(msg.getMessageNumber()), msg); if (previous !=null) { // Duplicate of message not yet processed log.warn("Receive Message again -- Sender ActTimeout too short [ name: " + msg.getContextName() + " war: " + msg.getFileName() + " data: " + HexUtils.toHexString(msg.getData()) + " data length: " + msg.getDataLength() + " ]"); return false; } FileMessage next = null; synchronized (this) { if (!isWriting) { next = msgBuffer.get(Long.valueOf(lastMessageProcessed.get() + 1)); if (next != null) { isWriting = true; } else { return false; } } else { return false; } } while (next != null) { out.write(next.getData(), 0, next.getDataLength()); lastMessageProcessed.incrementAndGet(); out.flush(); if (next.getMessageNumber() == next.getTotalNrOfMsgs()) { out.close(); cleanup(); return true; } synchronized(this) { next = msgBuffer.get(Long.valueOf(lastMessageProcessed.get() + 1)); if (next == null) { isWriting = false; } } } return false; }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
protected void checkState(boolean openForWrite) throws IllegalArgumentException { if (this.openForWrite != openForWrite) { cleanup(); if (openForWrite) throw new IllegalArgumentException( "Can't write message, this factory is reading."); else throw new IllegalArgumentException( "Can't read message, this factory is writing."); } if (this.closed) { cleanup(); throw new IllegalArgumentException("Factory has been closed."); } }
// in java/org/apache/catalina/core/StandardContext.java
Override public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object object) throws IllegalArgumentException { broadcaster.addNotificationListener(listener,filter,object); }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object object) throws IllegalArgumentException { broadcaster.addNotificationListener(listener,filter,object); }
(Lib) IOException 205
              
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void clear() throws IOException { if (writer != null) { throw new IOException(); } else { nextChar = 0; if (LIMIT_BUFFER && (cb.length > Constants.DEFAULT_TAG_BUFFER_SIZE)) { cb = new char[Constants.DEFAULT_TAG_BUFFER_SIZE]; bufferSize = cb.length; } } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
private void ensureOpen() throws IOException { if (closed) throw new IOException("Stream closed"); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public final void clear() throws IOException { if ((bufferSize == 0) && (out != null)) // clear() is illegal after any unbuffered output (JSP.5.5) throw new IllegalStateException( getLocalizeMessage("jsp.error.ise_on_clear")); if (flushed) throw new IOException( getLocalizeMessage("jsp.error.attempt_to_clear_flushed_buffer")); ensureOpen(); nextChar = 0; }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
private final void bufferOverflow() throws IOException { throw new IOException(getLocalizeMessage("jsp.error.overflow")); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
private void ensureOpen() throws IOException { if (response == null || closed) throw new IOException("Stream closed"); }
// in java/org/apache/jasper/compiler/SmapUtil.java
static void install(File classFile, byte[] smap) throws IOException { File tmpFile = new File(classFile.getPath() + "tmp"); new SDEInstaller(classFile, smap, tmpFile); if (!classFile.delete()) { throw new IOException("classFile.delete() failed"); } if (!tmpFile.renameTo(classFile)) { throw new IOException("tmpFile.renameTo(classFile) failed"); } }
// in java/org/apache/jasper/compiler/SmapUtil.java
static byte[] readWhole(File input) throws IOException { FileInputStream inStream = new FileInputStream(input); int len = (int)input.length(); byte[] bytes = new byte[len]; if (inStream.read(bytes, 0, len) != len) { throw new IOException("expected size: " + len); } inStream.close(); return bytes; }
// in java/org/apache/jasper/compiler/SmapUtil.java
int copyConstantPool(int constantPoolCount) throws UnsupportedEncodingException, IOException { int sdeIndex = -1; // copy const pool index zero not in class file for (int i = 1; i < constantPoolCount; ++i) { int tag = readU1(); writeU1(tag); switch (tag) { case 7 : // Class case 8 : // String if (log.isDebugEnabled()) log.debug(i + " copying 2 bytes"); copy(2); break; case 9 : // Field case 10 : // Method case 11 : // InterfaceMethod case 3 : // Integer case 4 : // Float case 12 : // NameAndType if (log.isDebugEnabled()) log.debug(i + " copying 4 bytes"); copy(4); break; case 5 : // Long case 6 : // Double if (log.isDebugEnabled()) log.debug(i + " copying 8 bytes"); copy(8); i++; break; case 1 : // Utf8 int len = readU2(); writeU2(len); byte[] utf8 = readBytes(len); String str = new String(utf8, "UTF-8"); if (log.isDebugEnabled()) log.debug(i + " read class attr -- '" + str + "'"); if (str.equals(nameSDE)) { sdeIndex = i; } writeBytes(utf8); break; default : throw new IOException("unexpected tag: " + tag); } } return sdeIndex; }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private void tldScanStream(String resourcePath, String entryName, InputStream stream) throws IOException { try { // Parse the tag library descriptor at the specified resource path String uri = null; TreeNode tld = new ParserUtils().parseXMLDocument(resourcePath, stream); TreeNode uriNode = tld.findChild("uri"); if (uriNode != null) { String body = uriNode.getBody(); if (body != null) uri = body; } // Add implicit map entry only if its uri is not already // present in the map if (uri != null && mappings.get(uri) == null) { TldLocation location; if (entryName == null) { location = new TldLocation(resourcePath); } else { location = new TldLocation(entryName, resourcePath); } mappings.put(uri, location); } } catch (JasperException e) { // Hack - makes exception handling simpler throw new IOException(e); } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void createInitialReader() throws IOException, JasperException { // wrap this stream in RewindableInputStream stream = new RewindableInputStream(stream); // perform auto-detect of encoding if necessary if (encoding == null) { // read first four bytes and determine encoding final byte[] b4 = new byte[4]; int count = 0; for (; count<4; count++ ) { b4[count] = (byte)stream.read(); } if (count == 4) { Object [] encodingDesc = getEncodingName(b4, count); encoding = (String)(encodingDesc[0]); isBigEndian = (Boolean)(encodingDesc[1]); if (encodingDesc.length > 3) { isBomPresent = ((Boolean)(encodingDesc[2])).booleanValue(); skip = ((Integer)(encodingDesc[3])).intValue(); } else { isBomPresent = true; skip = ((Integer)(encodingDesc[2])).intValue(); } stream.reset(); // Special case UTF-8 files with BOM created by Microsoft // tools. It's more efficient to consume the BOM than make // the reader perform extra checks. -Ac if (count > 2 && encoding.equals("UTF-8")) { int b0 = b4[0] & 0xFF; int b1 = b4[1] & 0xFF; int b2 = b4[2] & 0xFF; if (b0 == 0xEF && b1 == 0xBB && b2 == 0xBF) { // ignore first three bytes... long skipped = stream.skip(3); if (skipped != 3) { throw new IOException(Localizer.getMessage( "xmlParser.skipBomFail")); } } } reader = createReader(stream, encoding, isBigEndian); } else { reader = createReader(stream, encoding, isBigEndian); } } }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public void mark(int readAheadLimit) throws IOException { throw new IOException( Localizer.getMessage("jsp.error.xml.operationNotSupported", "mark()", "UTF-8")); }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public int read() throws IOException { int b0 = fInputStream.read(); if (b0 > 0x80) { throw new IOException(Localizer.getMessage("jsp.error.xml.invalidASCII", Integer.toString(b0))); } return b0; }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public int read(char ch[], int offset, int length) throws IOException { if (length > fBuffer.length) { length = fBuffer.length; } int count = fInputStream.read(fBuffer, 0, length); for (int i = 0; i < count; i++) { int b0 = (0xff & fBuffer[i]); // Convert to unsigned if (b0 > 0x80) { throw new IOException(Localizer.getMessage("jsp.error.xml.invalidASCII", Integer.toString(b0))); } ch[offset + i] = (char)b0; } return count; }
// in java/org/apache/naming/resources/WARDirContext.java
Override public InputStream streamContent() throws IOException { try { if (binaryContent == null) { InputStream is = base.getInputStream(entry); inputStream = is; return is; } } catch (ZipException e) { throw new IOException(e.getMessage(), e); } return super.streamContent(); }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
Override protected void output(byte[] src, int offset, int length) throws IOException { outputBuffer.put(src, offset, length); long socketRef = socket.getSocket().longValue(); if (outputBuffer.position() > 0) { if ((socketRef != 0) && Socket.sendbb(socketRef, 0, outputBuffer.position()) < 0) { throw new IOException(sm.getString("ajpprocessor.failedsend")); } outputBuffer.clear(); } }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
protected boolean read(int n) throws IOException { if (inputBuffer.capacity() - inputBuffer.limit() <= n - inputBuffer.remaining()) { inputBuffer.compact(); inputBuffer.limit(inputBuffer.position()); inputBuffer.position(0); } int nRead; while (inputBuffer.remaining() < n) { nRead = Socket.recvbb (socket.getSocket().longValue(), inputBuffer.limit(), inputBuffer.capacity() - inputBuffer.limit()); if (nRead > 0) { inputBuffer.limit(inputBuffer.limit() + nRead); } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } } return true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
protected boolean readt(int n, boolean useAvailableData) throws IOException { if (useAvailableData && inputBuffer.remaining() == 0) { return false; } if (inputBuffer.capacity() - inputBuffer.limit() <= n - inputBuffer.remaining()) { inputBuffer.compact(); inputBuffer.limit(inputBuffer.position()); inputBuffer.position(0); } int nRead; while (inputBuffer.remaining() < n) { nRead = Socket.recvbb (socket.getSocket().longValue(), inputBuffer.limit(), inputBuffer.capacity() - inputBuffer.limit()); if (nRead > 0) { inputBuffer.limit(inputBuffer.limit() + nRead); } else { if ((-nRead) == Status.ETIMEDOUT || (-nRead) == Status.TIMEUP) { return false; } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } } } return true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
Override protected void output(byte[] src, int offset, int length) throws IOException { ByteBuffer writeBuffer = socket.getBufHandler() .getWriteBuffer(); writeBuffer.put(src, offset, length); writeBuffer.flip(); NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled"); long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { pool.write(writeBuffer, socket, selector, writeTimeout, true); }finally { if ( selector != null ) pool.put(selector); } writeBuffer.clear(); }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
protected int read(byte[] buf, int pos, int n, boolean blockFirstRead) throws IOException { int read = 0; int res = 0; boolean block = blockFirstRead; while (read < n) { res = readSocket(buf, read + pos, n, block); if (res > 0) { read += res; } else if (res == 0 && !block) { break; } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } block = true; } return read; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
private int readSocket(byte[] buf, int pos, int n, boolean block) throws IOException { int nRead = 0; socket.getBufHandler().getReadBuffer().clear(); socket.getBufHandler().getReadBuffer().limit(n); if ( block ) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled."); nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout()); } catch ( EOFException eof ) { nRead = -1; } finally { if ( selector != null ) pool.put(selector); } } else { nRead = socket.read(socket.getBufHandler().getReadBuffer()); } if (nRead > 0) { socket.getBufHandler().getReadBuffer().flip(); socket.getBufHandler().getReadBuffer().limit(nRead); socket.getBufHandler().getReadBuffer().get(buf, pos, nRead); return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("iib.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
protected int readMessage(AjpMessage message, boolean blockFirstRead) throws IOException { byte[] buf = message.getBuffer(); int headerLength = message.getHeaderLength(); int bytesRead = read(buf, 0, headerLength, blockFirstRead); if (bytesRead == 0) { return 0; } int messageLength = message.processHeader(true); if (messageLength < 0) { // Invalid AJP header signature throw new IOException(sm.getString("ajpmessage.invalidLength", Integer.valueOf(messageLength))); } else if (messageLength == 0) { // Zero length message. return bytesRead; } else { if (messageLength > buf.length) { // Message too long for the buffer // Need to trigger a 400 response throw new IllegalArgumentException(sm.getString( "ajpprocessor.header.tooLong", Integer.valueOf(messageLength), Integer.valueOf(buf.length))); } bytesRead += read(buf, headerLength, messageLength, true); return bytesRead; } }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public SocketState event(SocketStatus status) throws IOException { // Should never reach this code but in case we do... throw new IOException( sm.getString("ajpprocessor.comet.notsupported")); }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public SocketState upgradeDispatch() throws IOException { // Should never reach this code but in case we do... throw new IOException( sm.getString("ajpprocessor.httpupgrade.notsupported")); }
// in java/org/apache/coyote/ajp/AjpProcessor.java
protected boolean read(byte[] buf, int pos, int n) throws IOException { int read = 0; int res = 0; while (read < n) { res = input.read(buf, read + pos, n - read); if (res > 0) { read += res; } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } } return true; }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
private int readSocket(boolean timeout, boolean block) throws IOException { int nRead = 0; socket.getBufHandler().getReadBuffer().clear(); if ( block ) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled."); nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout()); } catch ( EOFException eof ) { nRead = -1; } finally { if ( selector != null ) pool.put(selector); } } else { nRead = socket.read(socket.getBufHandler().getReadBuffer()); } if (nRead > 0) { socket.getBufHandler().getReadBuffer().flip(); socket.getBufHandler().getReadBuffer().limit(nRead); expand(nRead + pos); socket.getBufHandler().getReadBuffer().get(buf, pos, nRead); lastValid = pos + nRead; return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("iib.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
Override public void flush() throws IOException { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) nioChannel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled"); } long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { do { if (nioChannel.flush(true, selector, writeTimeout)) { break; } } while (true); } finally { if (selector != null) { pool.put(selector); } } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
private int readSocket(boolean block, byte[] bytes, int offset, int len) throws IOException { int nRead = 0; nioChannel.getBufHandler().getReadBuffer().clear(); nioChannel.getBufHandler().getReadBuffer().limit(len); if (block) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) nioChannel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled."); } nRead = pool.read(nioChannel.getBufHandler().getReadBuffer(), nioChannel, selector, att.getTimeout()); } catch (EOFException eof) { nRead = -1; } finally { if (selector != null) { pool.put(selector); } } } else { nRead = nioChannel.read(nioChannel.getBufHandler().getReadBuffer()); } if (nRead > 0) { nioChannel.getBufHandler().getReadBuffer().flip(); nioChannel.getBufHandler().getReadBuffer().limit(nRead); nioChannel.getBufHandler().getReadBuffer().get(bytes, offset, nRead); return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("nio.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
private synchronized int writeToSocket(byte[] bytes, int off, int len) throws IOException { nioChannel.getBufHandler().getWriteBuffer().clear(); nioChannel.getBufHandler().getWriteBuffer().put(bytes, off, len); nioChannel.getBufHandler().getWriteBuffer().flip(); int written = 0; NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) nioChannel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled"); } long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { written = pool.write(nioChannel.getBufHandler().getWriteBuffer(), nioChannel, selector, writeTimeout, true); } finally { if (selector != null) { pool.put(selector); } } return written; }
// in java/org/apache/coyote/http11/upgrade/UpgradeAprProcessor.java
Override public int read(boolean block, byte[] bytes, int off, int len) throws IOException { if (!block) { Socket.optSet(socket, Socket.APR_SO_NONBLOCK, -1); } try { int result = Socket.recv(socket, bytes, off, len); if (result > 0) { return result; } else if (-result == Status.EAGAIN) { return 0; } else { throw new IOException(sm.getString("apr.error", Integer.valueOf(-result))); } } finally { if (!block) { Socket.optSet(socket, Socket.APR_SO_NONBLOCK, 0); } } }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
Override public int doRead(ByteChunk chunk, Request req) throws IOException { if (endChunk) return -1; if(needCRLFParse) { needCRLFParse = false; parseCRLF(); } if (remaining <= 0) { if (!parseChunkHeader()) { throw new IOException("Invalid chunk header"); } if (endChunk) { parseEndChunk(); return -1; } } int result = 0; if (pos >= lastValid) { readBytes(); } if (remaining > (lastValid - pos)) { result = lastValid - pos; remaining = remaining - result; chunk.setBytes(buf, pos, result); pos = lastValid; } else { result = remaining; chunk.setBytes(buf, pos, remaining); pos = pos + remaining; remaining = 0; //we need a CRLF if ((pos+1) >= lastValid) { //if we call parseCRLF we overrun the buffer here //so we defer it to the next call BZ 11117 needCRLFParse = true; } else { parseCRLF(); //parse the CRLF immediately } } return result; }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
protected boolean parseCRLF() throws IOException { boolean eol = false; boolean crfound = false; while (!eol) { if (pos >= lastValid) { if (readBytes() <= 0) throw new IOException("Invalid CRLF"); } if (buf[pos] == Constants.CR) { if (crfound) throw new IOException("Invalid CRLF, two CR characters encountered."); crfound = true; } else if (buf[pos] == Constants.LF) { if (!crfound) throw new IOException("Invalid CRLF, no CR character encountered."); eol = true; } else { throw new IOException("Invalid CRLF"); } pos++; } return true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
Override public SocketState upgradeDispatch() throws IOException { // Should never reach this code but in case we do... // TODO throw new IOException( sm.getString("TODO")); }
// in java/org/apache/coyote/http11/Http11Processor.java
Override public SocketState event(SocketStatus status) throws IOException { // Should never reach this code but in case we do... throw new IOException( sm.getString("http11processor.comet.notsupported")); }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
Override public void sendAck() throws IOException { if (!committed) { if (Socket.send(socket, Constants.ACK_BYTES, 0, Constants.ACK_BYTES.length) < 0) throw new IOException(sm.getString("iib.failedwrite")); } }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
private void flushBuffer() throws IOException { if (bbuf.position() > 0) { if (Socket.sendbb(socket, 0, bbuf.position()) < 0) { throw new IOException(); } bbuf.clear(); } }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
protected boolean fill() throws IOException { int nRead = 0; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.EAGAIN) { return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } else { if (buf.length - end < 4500) { // In this case, the request header was really large, so we allocate a // brand new one; the old one will get GCed when subsequent requests // clear all references buf = new byte[buf.length]; end = 0; } pos = end; lastValid = pos; bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.ETIMEDOUT || (-nRead) == Status.TIMEUP) { throw new SocketTimeoutException(sm.getString("iib.failedread")); } else if (nRead == 0) { // APR_STATUS_IS_EOF, since native 1.1.22 return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } return (nRead > 0); }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
private synchronized int writeToSocket(ByteBuffer bytebuffer, boolean block, boolean flip) throws IOException { if ( flip ) bytebuffer.flip(); int written = 0; NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled"); long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { written = pool.write(bytebuffer, socket, selector, writeTimeout, block); //make sure we are flushed do { if (socket.flush(true,selector,writeTimeout)) break; }while ( true ); }finally { if ( selector != null ) pool.put(selector); } if ( block ) bytebuffer.clear(); //only clear return written; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
Override public SocketState process(SocketWrapper<Object> socket) throws IOException { throw new IOException("Unimplemented"); }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
public void onSynStream(SpdyStream str) throws IOException { this.spdyStream = str; SpdyFrame frame = str.reqFrame; // We need to make a copy - the frame buffer will be reused. // We use the 'wrap' methods of MimeHeaders - which should be // lighter on mem in some cases. RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); // Request received. MimeHeaders mimeHeaders = request.getMimeHeaders(); for (int i = 0; i < frame.nvCount; i++) { int nameLen = frame.read16(); if (nameLen > frame.remaining()) { throw new IOException("Name too long"); } keyBuffer.setBytes(frame.data, frame.off, nameLen); if (keyBuffer.equals("method")) { frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } request.method().setBytes(frame.data, frame.off, valueLen); frame.advance(valueLen); } else if (keyBuffer.equals("url")) { frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } request.requestURI().setBytes(frame.data, frame.off, valueLen); if (SpdyContext.debug) { System.err.println("URL= " + request.requestURI()); } frame.advance(valueLen); } else if (keyBuffer.equals("version")) { frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } frame.advance(valueLen); } else { MessageBytes value = mimeHeaders.addValue(frame.data, frame.off, nameLen); frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } value.setBytes(frame.data, frame.off, valueLen); frame.advance(valueLen); } } onRequest(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public void listen(final int port) throws IOException { if (acceptor != null) { throw new IOException("Already accepting on " + acceptor.port); } if (sslMode && certFile == null) { throw new IOException("Missing certificates for server"); } if (sslMode || !nonBlockingAccept) { acceptorDispatch = new AcceptorDispatchThread(port); acceptorDispatch.setName("AprAcceptorDispatch-" + port); acceptorDispatch.start(); } acceptor = new AcceptorThread(port); acceptor.prepare(); acceptor.setName("AprAcceptor-" + port); acceptor.start(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
protected void connectBlocking(AprSocket apr) throws IOException { try { if (!running) { throw new IOException("Stopped"); } HostInfo hi = apr.getHost(); long clientSockP; synchronized (pollers) { long socketpool = Pool.create(getRootPool()); int family = Socket.APR_INET; clientSockP = Socket.create(family, Socket.SOCK_STREAM, Socket.APR_PROTO_TCP, socketpool); // or rootPool ? } Socket.timeoutSet(clientSockP, connectTimeout * 1000); if (OS.IS_UNIX) { Socket.optSet(clientSockP, Socket.APR_SO_REUSEADDR, 1); } Socket.optSet(clientSockP, Socket.APR_SO_KEEPALIVE, 1); // Blocking // TODO: use socket pool // TODO: cache it ( and TTL ) in hi long inetAddress = Address.info(hi.host, Socket.APR_INET, hi.port, 0, rootPool); // this may take a long time - stop/destroy must wait // at least connect timeout int rc = Socket.connect(clientSockP, inetAddress); if (rc != 0) { synchronized (pollers) { Socket.close(clientSockP); Socket.destroy(clientSockP); } /////Pool.destroy(socketpool); throw new IOException("Socket.connect(): " + rc + " " + Error.strerror(rc) + " " + connectTimeout); } if (!running) { throw new IOException("Stopped"); } connectionsCount.incrementAndGet(); if (tcpNoDelay) { Socket.optSet(clientSockP, Socket.APR_TCP_NODELAY, 1); } Socket.timeoutSet(clientSockP, defaultTimeout * 1000); apr.socket = clientSockP; apr.afterConnect(); } catch (IOException e) { apr.reset(); throw e; } catch (Throwable e) { apr.reset(); e.printStackTrace(); throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
long getSslCtx() throws Exception { if (sslCtx == 0) { synchronized (AprSocketContext.class) { boolean serverMode = acceptor != null; sslCtx = SSLContext.make(getRootPool(), sslProtocol, serverMode ? SSL.SSL_MODE_SERVER : SSL.SSL_MODE_CLIENT); // SSL.SSL_OP_NO_SSLv3 int opts = SSL.SSL_OP_NO_SSLv2 | SSL.SSL_OP_SINGLE_DH_USE; if (!USE_TICKETS || serverMode && ticketKey == null) { opts |= SSL.SSL_OP_NO_TICKET; } SSLContext.setOptions(sslCtx, opts); // Set revocation // SSLContext.setCARevocation(sslContext, SSLCARevocationFile, SSLCARevocationPath); // Client certificate verification - maybe make it option try { SSLContext.setCipherSuite(sslCtx, SSLCipherSuite); if (serverMode) { if (ticketKey != null) { //SSLExt.setTicketKeys(sslCtx, ticketKey, ticketKey.length); } if (certFile != null) { boolean rc = SSLContext.setCertificate(sslCtx, certFile, keyFile, null, SSL.SSL_AIDX_DSA); if (!rc) { throw new IOException("Can't set keys"); } } SSLContext.setVerify(sslCtx, SSL.SSL_CVERIFY_NONE, 10); if (spdyNPN != null) { SSLExt.setNPN(sslCtx, spdyNPN, spdyNPN.length); } } else { if (tlsCertVerifier != null) { // NONE ? SSLContext.setVerify(sslCtx, SSL.SSL_CVERIFY_NONE, 10); } else { SSLContext.setCACertificate(sslCtx, "/etc/ssl/certs/ca-certificates.crt", "/etc/ssl/certs"); SSLContext.setVerify(sslCtx, SSL.SSL_CVERIFY_REQUIRE, 10); } if (spdyNPN != null) { SSLExt.setNPN(sslCtx, spdyNPN, spdyNPN.length); } } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } long mode = SSLExt.sslCtxSetMode(sslCtx, SSLExt.SSL_MODE_ENABLE_PARTIAL_WRITE | SSLExt.SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); // TODO: try release buffers } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
void prepare() throws IOException { try { // Create the pool for the server socket serverSockPool = Pool.create(getRootPool()); int family = Socket.APR_INET; inetAddress = Address.info(addressStr, family, port, 0, serverSockPool); // Create the APR server socket serverSock = Socket.create(family, Socket.SOCK_STREAM, Socket.APR_PROTO_TCP, serverSockPool); if (OS.IS_UNIX) { Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Deal with the firewalls that tend to drop the inactive sockets Socket.optSet(serverSock, Socket.APR_SO_KEEPALIVE, 1); // Bind the server socket int ret = Socket.bind(serverSock, inetAddress); if (ret != 0) { throw new IOException("Socket.bind " + ret + " " + Error.strerror(ret) + " port=" + port); } // Start listening on the server socket ret = Socket.listen(serverSock, backlog ); if (ret != 0) { throw new IOException("endpoint.init.listen" + ret + " " + Error.strerror(ret)); } if (OS.IS_WIN32 || OS.IS_WIN64) { // On Windows set the reuseaddr flag after the bind/listen Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Sendfile usage on systems which don't support it cause major problems if (useSendfile && !Library.APR_HAS_SENDFILE) { useSendfile = false; } // Delay accepting of new connections until data is available // Only Linux kernels 2.4 + have that implemented // on other platforms this call is noop and will return APR_ENOTIMPL. if (deferAccept) { if (Socket.optSet(serverSock, Socket.APR_TCP_DEFER_ACCEPT, 1) == Status.APR_ENOTIMPL) { deferAccept = false; } } } catch (Throwable t) { throw new IOException(t); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
private void pollAdd(AprSocket up, int req) throws IOException { boolean failed = false; int rv; synchronized (channels) { if (up.isClosed()) { return; } rv = Poll.add(serverPollset, up.socket, req); if (rv != Status.APR_SUCCESS) { up.poller = null; keepAliveCount.decrementAndGet(); failed = true; } else { polledCount.incrementAndGet(); channels.put(up.socket, up); up.setStatus(AprSocket.POLL); } } if (failed) { up.reset(); throw new IOException("poll add error " + rv + " " + up + " " + Error.strerror(rv)); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int write(byte[] data, int off, int len, long to) throws IOException { long max = System.currentTimeMillis() + to; while (true) { int rc = writeInternal(data, off, len); if (rc < 0) { throw new IOException("Write error " + rc); } else if (rc == 0) { // need poll out - do we need to update polling ? context.findPollerAndAdd(this); } else { return rc; } try { long waitTime = max - System.currentTimeMillis(); if (waitTime <= 0) { return 0; } wait(waitTime); } catch (InterruptedException e) { return 0; } } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int write(byte[] data, int off, int len) throws IOException { // In SSL mode, read/write can't be called at the same time. int rc = writeInternal(data, off, len); if (rc < 0) { throw new IOException("Write error " + rc); } else if (rc == 0) { // need poll out - do we need to update polling ? synchronized (this) { context.findPollerAndAdd(this); } } return rc; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private int writeInternal(byte[] data, int off, int len) throws IOException { int rt = 0; int sent = 0; synchronized(this) { if ((status & CLOSED) != 0 || socket == 0 || !context.running) { throw new IOException("Closed"); } if ((status & WRITING) != 0) { throw new IOException("Write from 2 threads not allowed"); } status |= WRITING; while (len > 0) { sent = Socket.send(socket, data, off, len); if (sent <= 0) { break; } off += sent; len -= sent; } status &= ~WRITING; } if (context.rawDataHandler != null) { context.rawData(this, false, data, off, sent, len, false); } if (sent <= 0) { if (sent == -Status.TIMEUP || sent == -Status.EAGAIN || sent == 0) { setStatus(POLLOUT); updatePolling(); return rt; } if (context.debug) { log.warning("apr.send(): Failed to send, closing " + sent); } reset(); throw new IOException("Error sending " + sent + " " + Error.strerror(-sent)); } else { off += sent; len -= sent; rt += sent; return sent; } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private int processReadResult(byte[] data, int off, int len, int read) throws IOException { if (context.rawDataHandler != null) { context.rawData(this, true, data, off, read, len, false); } if (read > 0) { return read; } if (read == 0 || read == -Status.TIMEUP || read == -Status.ETIMEDOUT || read == -Status.EAGAIN) { read = 0; setStatus(POLLIN); updatePolling(); return 0; } if (read == -Status.APR_EOF || read == -1) { close(); return -1; } // abrupt close reset(); throw new IOException("apr.read(): " + read + " " + Error.strerror(-read)); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int readNB(byte[] data, int off, int len) throws IOException { int read; synchronized(this) { if ((status & CLOSED) != 0 || socket == 0 || !context.running) { return -1; } if ((status & READING) != 0) { throw new IOException("Read from 2 threads not allowed"); } status |= READING; read = Socket.recv(socket, data, off, len); status &= ~READING; } return processReadResult(data, off, len, read); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public long getIOTimeout() throws IOException { if (socket != 0 && context.running) { try { return Socket.timeoutGet(socket) / 1000; } catch (Exception e) { throw new IOException(e); } } else { throw new IOException("Socket is closed"); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public byte[][] getPeerCert(boolean check) throws IOException { getHost(); if (hostInfo.certs != null && hostInfo.certs != NO_CERTS && !check) { return hostInfo.certs; } if (!checkBitAndSocket(SSL_ATTACHED)) { return NO_CERTS; } try { int certLength = SSLSocket.getInfoI(socket, SSL.SSL_INFO_CLIENT_CERT_CHAIN); // TODO: if resumed, old certs are good. // If not - warn if certs changed, remember first cert, etc. if (certLength <= 0) { // Can also happen on session resume - keep the old if (hostInfo.certs == null) { hostInfo.certs = NO_CERTS; } return hostInfo.certs; } hostInfo.certs = new byte[certLength + 1][]; hostInfo.certs[0] = SSLSocket.getInfoB(socket, SSL.SSL_INFO_CLIENT_CERT); for (int i = 0; i < certLength; i++) { hostInfo.certs[i + 1] = SSLSocket.getInfoB(socket, SSL.SSL_INFO_CLIENT_CERT_CHAIN + i); } return hostInfo.certs; } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public X509Certificate[] getPeerX509Cert() throws IOException { byte[][] certs = getPeerCert(false); X509Certificate[] xcerts = new X509Certificate[certs.length]; if (certs.length == 0) { return xcerts; } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (int i = 0; i < certs.length; i++) { if (certs[i] != null) { ByteArrayInputStream bis = new ByteArrayInputStream( certs[i]); xcerts[i] = (X509Certificate) cf.generateCertificate(bis); bis.close(); } } } catch (CertificateException ex) { throw new IOException(ex); } return xcerts; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getCipherSuite() throws IOException { if (checkBitAndSocket(SSL_ATTACHED)) { return null; } try { return SSLSocket.getInfoS(socket, SSL.SSL_INFO_CIPHER); } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int getKeySize() throws IOException { if (checkBitAndSocket(SSL_ATTACHED)) { return -1; } try { return SSLSocket.getInfoI(socket, SSL.SSL_INFO_CIPHER_USEKEYSIZE); } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int getRemotePort() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_REMOTE, socket); Sockaddr addr = Address.getInfo(sa); return addr.port; } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getRemoteAddress() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_REMOTE, socket); return Address.getip(sa); } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getRemoteHostname() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_REMOTE, socket); String remoteHost = Address.getnameinfo(sa, 0); if (remoteHost == null) { remoteHost = Address.getip(sa); } return remoteHost; } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int getLocalPort() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_LOCAL, socket); Sockaddr addr = Address.getInfo(sa); return addr.port; } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getLocalAddress() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_LOCAL, socket); return Address.getip(sa); } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getLocalHostname() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_LOCAL, socket); return Address.getnameinfo(sa, 0); } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
void notifyIO() throws IOException { long t0 = System.currentTimeMillis(); try { if (handler != null) { handler.process(this, true, false, false); } } catch (Throwable t) { throw new IOException(t); } finally { long t1 = System.currentTimeMillis(); t1 -= t0; if (t1 > context.maxHandlerTime.get()) { context.maxHandlerTime.set(t1); } context.totalHandlerTime.addAndGet(t1); context.handlerCount.incrementAndGet(); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public void blockingStartTLS() throws IOException { synchronized(this) { if (socket == 0 || !context.running) { return; } if ((status & SSL_ATTACHED) != 0) { return; } status |= SSL_ATTACHED; } try { if (context.debug) { log.info(this + " StartSSL"); } AprSocketContext aprCon = context; SSLSocket.attach(aprCon.getSslCtx(), socket); if (context.debugSSL) { SSLExt.debug(socket); } if (!getContext().isServer()) { if (context.USE_TICKETS && hostInfo.ticketLen > 0) { SSLExt.setTicket(socket, hostInfo.ticket, hostInfo.ticketLen); } else if (hostInfo.sessDer != null) { SSLExt.setSessionData(socket, hostInfo.sessDer, hostInfo.sessDer.length); } } SSLExt.sslSetMode(socket, SSLExt.SSL_MODE_ENABLE_PARTIAL_WRITE | SSLExt.SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); int rc = SSLSocket.handshake(socket); // At this point we have the session ID, remote certs, etc // we can lookup host info if (hostInfo == null) { hostInfo = new HostInfo(); } if (rc != Status.APR_SUCCESS) { throw new IOException(this + " Handshake failed " + rc + " " + Error.strerror(rc) + " SSLL " + SSL.getLastError()); } else { // SUCCESS handshakeDone(); } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private void handshakeDone() throws IOException { getHost(); if (socket == 0 || !context.running) { throw new IOException("Socket closed"); } if (context.USE_TICKETS && ! context.isServer()) { if (hostInfo.ticket == null) { hostInfo.ticket = new byte[2048]; } int ticketLen = SSLExt.getTicket(socket, hostInfo.ticket); if (ticketLen > 0) { hostInfo.ticketLen = ticketLen; if (context.debug) { log.info("Received ticket: " + ticketLen); } } } // TODO: if the ticket, session id or session changed - callback to // save the session again try { hostInfo.sessDer = SSLExt.getSessionData(socket); getPeerCert(true); hostInfo.sessionId = SSLSocket.getInfoS(socket, SSL.SSL_INFO_SESSION_ID); } catch (Exception e) { throw new IOException(e); } hostInfo.npn = new byte[32]; hostInfo.npnLen = SSLExt.getNPN(socket, hostInfo.npn); // If custom verification is used - should check the certificates if (context.tlsCertVerifier != null) { context.tlsCertVerifier.handshakeDone(this); } }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public SpdyFrame getDataFrame(long to) throws IOException { while (true) { SpdyFrame res = getFrame(to); if (res == null || res.isData()) { return res; } if (res.type == SpdyConnection.TYPE_RST_STREAM) { throw new IOException("Reset"); } } }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public SpdyConnection getConnection(String host, int port) throws IOException { SpdyConnectionAprSocket spdy = new SpdyConnectionAprSocket(ctx); AprSocket ch = con.socket(host, port, ctx.tls); spdy.setSocket(ch); ch.connect(); ch.setHandler(new SpdySocketHandler(spdy)); // need to consume the input to receive more read events int rc = spdy.processInput(); if (rc == SpdyConnection.CLOSE) { ch.close(); throw new IOException("Error connecting"); } return spdy; }
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
Override public synchronized void decompress(SpdyFrame frame, int start) throws IOException { // stream id ( 4 ) + unused ( 2 ) // nvCount is compressed in impl - spec is different init(); if (decompressBuffer == null) { decompressBuffer = new byte[frame.data.length]; } // will read from dec buffer to frame.data decMax = frame.endData; decOff = start; int off = start; zipIn.setInput(frame.data, start, decMax - start); while (true) { int rd; try { rd = zipIn.inflate(decompressBuffer, off, decompressBuffer.length - off); if (rd == 0 && zipIn.needsDictionary()) { zipIn.setDictionary(SPDY_DICT); continue; } } catch (DataFormatException e) { throw new IOException(e); } if (rd == 0) { break; } if (rd == -1) { break; } off += rd; byte[] b = new byte[decompressBuffer.length * 2]; System.arraycopy(decompressBuffer, 0, b, 0, off); decompressBuffer = b; } byte[] tmpBuf = decompressBuffer; decompressBuffer = frame.data; frame.data = tmpBuf; frame.off = start; frame.endData = off; }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
protected Socket getSocket(String host, int port) throws IOException { try { if (ctx.tls) { SSLContext sslCtx = SSLContext.getDefault(); SSLSocket socket = (SSLSocket) sslCtx.getSocketFactory().createSocket(host, port); //socket.setEnabledProtocols(new String[] {"TLS1"}); socket.startHandshake(); return socket; } else { return new Socket(host, port); } } catch (NoSuchAlgorithmException e) { throw new IOException(e); } }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int handshake(boolean read, boolean write) throws IOException { if ( handshakeComplete ) return 0; //we have done our initial handshake if (!flush(netOutBuffer)) return SelectionKey.OP_WRITE; //we still have data to write SSLEngineResult handshake = null; while (!handshakeComplete) { switch ( handshakeStatus ) { case NOT_HANDSHAKING: { //should never happen throw new IOException("NOT_HANDSHAKING during handshake"); } case FINISHED: { //we are complete if we have delivered the last package handshakeComplete = !netOutBuffer.hasRemaining(); //return 0 if we are complete, otherwise we still have data to write return handshakeComplete?0:SelectionKey.OP_WRITE; } case NEED_WRAP: { //perform the wrap function handshake = handshakeWrap(write); if ( handshake.getStatus() == Status.OK ){ if (handshakeStatus == HandshakeStatus.NEED_TASK) handshakeStatus = tasks(); } else { //wrap should always work with our buffers throw new IOException("Unexpected status:" + handshake.getStatus() + " during handshake WRAP."); } if ( handshakeStatus != HandshakeStatus.NEED_UNWRAP || (!flush(netOutBuffer)) ) { //should actually return OP_READ if we have NEED_UNWRAP return SelectionKey.OP_WRITE; } //fall down to NEED_UNWRAP on the same call, will result in a //BUFFER_UNDERFLOW if it needs data } //$FALL-THROUGH$ case NEED_UNWRAP: { //perform the unwrap function handshake = handshakeUnwrap(read); if ( handshake.getStatus() == Status.OK ) { if (handshakeStatus == HandshakeStatus.NEED_TASK) handshakeStatus = tasks(); } else if ( handshake.getStatus() == Status.BUFFER_UNDERFLOW ){ //read more data, reregister for OP_READ return SelectionKey.OP_READ; } else { throw new IOException("Invalid handshake status:"+handshakeStatus+" during handshake UNWRAP."); }//switch break; } case NEED_TASK: { handshakeStatus = tasks(); break; } default: throw new IllegalStateException("Invalid handshake status:"+handshakeStatus); }//switch }//while //return 0 if we are complete, otherwise reregister for any activity that //would cause this method to be called again. return handshakeComplete?0:(SelectionKey.OP_WRITE|SelectionKey.OP_READ); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
protected SSLEngineResult handshakeUnwrap(boolean doread) throws IOException { if (netInBuffer.position() == netInBuffer.limit()) { //clear the buffer if we have emptied it out on data netInBuffer.clear(); } if ( doread ) { //if we have data to read, read it int read = sc.read(netInBuffer); if (read == -1) throw new IOException("EOF encountered during handshake."); } SSLEngineResult result; boolean cont = false; //loop while we can perform pure SSLEngine data do { //prepare the buffer with the incoming data netInBuffer.flip(); //call unwrap result = sslEngine.unwrap(netInBuffer, bufHandler.getReadBuffer()); //compact the buffer, this is an optional method, wonder what would happen if we didn't netInBuffer.compact(); //read in the status handshakeStatus = result.getHandshakeStatus(); if ( result.getStatus() == SSLEngineResult.Status.OK && result.getHandshakeStatus() == HandshakeStatus.NEED_TASK ) { //execute tasks if we need to handshakeStatus = tasks(); } //perform another unwrap? cont = result.getStatus() == SSLEngineResult.Status.OK && handshakeStatus == HandshakeStatus.NEED_UNWRAP; }while ( cont ); return result; }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public void close() throws IOException { if (closing) return; closing = true; sslEngine.closeOutbound(); if (!flush(netOutBuffer)) { throw new IOException("Remaining data in the network buffer, can't send SSL close message, force a close with close(true) instead"); } //prep the buffer for the close message netOutBuffer.clear(); //perform the close, since we called sslEngine.closeOutbound SSLEngineResult handshake = sslEngine.wrap(getEmptyBuf(), netOutBuffer); //we should be in a close state if (handshake.getStatus() != SSLEngineResult.Status.CLOSED) { throw new IOException("Invalid close state, will not send network data."); } //prepare the buffer for writing netOutBuffer.flip(); //if there is data to be written flush(netOutBuffer); //is the channel closed? closed = (!netOutBuffer.hasRemaining() && (handshake.getHandshakeStatus() != HandshakeStatus.NEED_WRAP)); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int read(ByteBuffer dst) throws IOException { //if we want to take advantage of the expand function, make sure we only use the ApplicationBufferHandler's buffers if ( dst != bufHandler.getReadBuffer() ) throw new IllegalArgumentException("You can only read using the application read buffer provided by the handler."); //are we in the middle of closing or closed? if ( closing || closed) return -1; //did we finish our handshake? if (!handshakeComplete) throw new IllegalStateException("Handshake incomplete, you must complete handshake before reading data."); //read from the network int netread = sc.read(netInBuffer); //did we reach EOF? if so send EOF up one layer. if (netread == -1) return -1; //the data read int read = 0; //the SSL engine result SSLEngineResult unwrap; do { //prepare the buffer netInBuffer.flip(); //unwrap the data unwrap = sslEngine.unwrap(netInBuffer, dst); //compact the buffer netInBuffer.compact(); if ( unwrap.getStatus()==Status.OK || unwrap.getStatus()==Status.BUFFER_UNDERFLOW ) { //we did receive some data, add it to our total read += unwrap.bytesProduced(); //perform any tasks if needed if (unwrap.getHandshakeStatus() == HandshakeStatus.NEED_TASK) tasks(); //if we need more network data, then bail out for now. if ( unwrap.getStatus() == Status.BUFFER_UNDERFLOW ) break; }else if ( unwrap.getStatus()==Status.BUFFER_OVERFLOW && read>0 ) { //buffer overflow can happen, if we have read data, then //empty out the dst buffer before we do another read break; }else { //here we should trap BUFFER_OVERFLOW and call expand on the buffer //for now, throw an exception, as we initialized the buffers //in the constructor throw new IOException("Unable to unwrap data, invalid status: " + unwrap.getStatus()); } } while ( (netInBuffer.position() != 0)); //continue to unwrapping as long as the input buffer has stuff return (read); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int write(ByteBuffer src) throws IOException { if ( src == this.netOutBuffer ) { //we can get here through a recursive call //by using the NioBlockingSelector int written = sc.write(src); return written; } else { //make sure we can handle expand, and that we only use on buffer if ( (!this.isSendFile()) && (src != bufHandler.getWriteBuffer()) ) throw new IllegalArgumentException("You can only write using the application write buffer provided by the handler."); //are we closing or closed? if ( closing || closed) throw new IOException("Channel is in closing state."); //the number of bytes written int written = 0; if (!flush(netOutBuffer)) { //we haven't emptied out the buffer yet return written; } /* * The data buffer is empty, we can reuse the entire buffer. */ netOutBuffer.clear(); SSLEngineResult result = sslEngine.wrap(src, netOutBuffer); written = result.bytesConsumed(); netOutBuffer.flip(); if (result.getStatus() == Status.OK) { if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) tasks(); } else { throw new IOException("Unable to wrap data, invalid engine state: " +result.getStatus()); } //force a flush flush(netOutBuffer); return written; } }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int write(ByteBuffer buf, NioChannel socket, long writeTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int written = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) && buf.hasRemaining()) { if (keycount > 0) { //only write if we were registered for a write int cnt = socket.write(buf); //write the data if (cnt == -1) throw new EOFException(); written += cnt; if (cnt > 0) { time = System.currentTimeMillis(); //reset our timeout timer continue; //we successfully wrote, try again without a selector } } try { if ( att.getWriteLatch()==null || att.getWriteLatch().getCount()==0) att.startWriteLatch(1); poller.add(att,SelectionKey.OP_WRITE,reference); if (writeTimeout < 0) { att.awaitWriteLatch(Long.MAX_VALUE,TimeUnit.MILLISECONDS); } else { att.awaitWriteLatch(writeTimeout,TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getWriteLatch()!=null && att.getWriteLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetWriteLatch(); } if (writeTimeout > 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= writeTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_WRITE); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return written; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int read(ByteBuffer buf, NioChannel socket, long readTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int read = 0; boolean timedout = false; int keycount = 1; //assume we can read long time = System.currentTimeMillis(); //start the timeout timer try { while(!timedout) { if (keycount > 0) { //only read if we were registered for a read read = socket.read(buf); if (read == -1) throw new EOFException(); if (read > 0) break; } try { if ( att.getReadLatch()==null || att.getReadLatch().getCount()==0) att.startReadLatch(1); poller.add(att,SelectionKey.OP_READ, reference); if (readTimeout < 0) { att.awaitReadLatch(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } else { att.awaitReadLatch(readTimeout, TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getReadLatch()!=null && att.getReadLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetReadLatch(); } if (readTimeout >= 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= readTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_READ); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return read; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
public boolean processSendfile(SelectionKey sk, KeyAttachment attachment, boolean reg, boolean event) { NioChannel sc = null; try { unreg(sk, attachment, sk.readyOps()); SendfileData sd = attachment.getSendfileData(); if ( sd.fchannel == null ) { File f = new File(sd.fileName); if ( !f.exists() ) { cancelledKey(sk,SocketStatus.ERROR); return false; } sd.fchannel = new FileInputStream(f).getChannel(); } sc = attachment.getChannel(); sc.setSendFile(true); WritableByteChannel wc = ((sc instanceof SecureNioChannel)?sc:sc.getIOChannel()); if (sc.getOutboundRemaining()>0) { if (sc.flushOutbound()) { attachment.access(); } } else { long written = sd.fchannel.transferTo(sd.pos,sd.length,wc); if ( written > 0 ) { sd.pos += written; sd.length -= written; attachment.access(); } else { // Unusual not to be able to transfer any bytes // Check the length was set correctly if (sd.fchannel.size() <= sd.pos) { throw new IOException("Sendfile configured to " + "send more data than was available"); } } } if ( sd.length <= 0 && sc.getOutboundRemaining()<=0) { if (log.isDebugEnabled()) { log.debug("Send file complete for:"+sd.fileName); } attachment.setSendfileData(null); try { sd.fchannel.close(); } catch (Exception ignore) { } if ( sd.keepAlive ) { if (reg) { if (log.isDebugEnabled()) { log.debug("Connection is keep alive, registering back for OP_READ"); } if (event) { this.add(attachment.getChannel(),SelectionKey.OP_READ); } else { reg(sk,attachment,SelectionKey.OP_READ); } } } else { if (log.isDebugEnabled()) { log.debug("Send file connection is being closed"); } cancelledKey(sk,SocketStatus.STOP); return false; } } else if ( attachment.interestOps() == 0 && reg ) { if (log.isDebugEnabled()) { log.debug("OP_WRITE for sendilfe:"+sd.fileName); } if (event) { add(attachment.getChannel(),SelectionKey.OP_WRITE); } else { reg(sk,attachment,SelectionKey.OP_WRITE); } } }catch ( IOException x ) { if ( log.isDebugEnabled() ) log.debug("Unable to complete sendfile request:", x); cancelledKey(sk,SocketStatus.ERROR); return false; }catch ( Throwable t ) { log.error("",t); cancelledKey(sk, SocketStatus.ERROR); return false; }finally { if (sc!=null) sc.setSendFile(false); } return true; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public void handshake(Socket sock) throws IOException { // We do getSession instead of startHandshake() so we can call this multiple times SSLSession session = ((SSLSocket)sock).getSession(); if (session.getCipherSuite().equals("SSL_NULL_WITH_NULL_NULL")) throw new IOException("SSL handshake failed. Ciper suite in SSL Session is SSL_NULL_WITH_NULL_NULL"); if (!allowUnsafeLegacyRenegotiation && !RFC_5746_SUPPORTED) { // Prevent further handshakes by removing all cipher suites ((SSLSocket) sock).setEnabledCipherSuites(new String[0]); } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
private KeyStore getStore(String type, String provider, String path, String pass) throws IOException { KeyStore ks = null; InputStream istream = null; try { if (provider == null) { ks = KeyStore.getInstance(type); } else { ks = KeyStore.getInstance(type, provider); } if(!("PKCS11".equalsIgnoreCase(type) || "".equalsIgnoreCase(path))) { File keyStoreFile = new File(path); if (!keyStoreFile.isAbsolute()) { keyStoreFile = new File(System.getProperty( Constants.CATALINA_BASE_PROP), path); } istream = new FileInputStream(keyStoreFile); } char[] storePass = null; if (pass != null && !"".equals(pass)) { storePass = pass.toCharArray(); } ks.load(istream, storePass); } catch (FileNotFoundException fnfe) { log.error(sm.getString("jsse.keystore_load_failed", type, path, fnfe.getMessage()), fnfe); throw fnfe; } catch (IOException ioe) { // May be expected when working with a trust store // Re-throw. Caller will catch and log as required throw ioe; } catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); } finally { if (istream != null) { try { istream.close(); } catch (IOException ioe) { // Do nothing } } } return ks; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
void init() throws IOException { try { String clientAuthStr = endpoint.getClientAuth(); if("true".equalsIgnoreCase(clientAuthStr) || "yes".equalsIgnoreCase(clientAuthStr)) { requireClientAuth = true; } else if("want".equalsIgnoreCase(clientAuthStr)) { wantClientAuth = true; } SSLContext context = createSSLContext(); context.init(getKeyManagers(), getTrustManagers(), null); // Configure SSL session cache SSLSessionContext sessionContext = context.getServerSessionContext(); if (sessionContext != null) { configureSessionContext(sessionContext); } // create proxy sslProxy = context.getServerSocketFactory(); // Determine which cipher suites to enable String requestedCiphers = endpoint.getCiphers(); enabledCiphers = getEnabledCiphers(requestedCiphers, sslProxy.getSupportedCipherSuites()); allowUnsafeLegacyRenegotiation = "true".equals( endpoint.getAllowUnsafeLegacyRenegotiation()); // Check the SSL config is OK checkConfig(); } catch(Exception e) { if( e instanceof IOException ) throw (IOException)e; throw new IOException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected KeyManager[] getKeyManagers(String keystoreType, String keystoreProvider, String algorithm, String keyAlias) throws Exception { KeyManager[] kms = null; String keystorePass = getKeystorePassword(); KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass); if (keyAlias != null && !ks.isKeyEntry(keyAlias)) { throw new IOException( sm.getString("jsse.alias_no_key_entry", keyAlias)); } KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); String keyPass = endpoint.getKeyPass(); if (keyPass == null) { keyPass = keystorePass; } kmf.init(ks, keyPass.toCharArray()); kms = kmf.getKeyManagers(); if (keyAlias != null) { String alias = keyAlias; if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) { alias = alias.toLowerCase(Locale.ENGLISH); } for(int i=0; i<kms.length; i++) { kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias); } } return kms; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public byte readByte() throws IOException { // Buffer depleted ? if (head == tail) { head = 0; // Refill. tail = input.read(buffer, head, bufSize); if (tail == -1) { // No more data available. throw new IOException("No more data is available"); } if (notifier != null) { notifier.noteBytesRead(tail); } } return buffer[head++]; }
// in java/org/apache/tomcat/util/http/fileupload/DeferredFileOutputStream.java
public void writeTo(OutputStream out) throws IOException { // we may only need to check if this is closed if we are working with a file // but we should force the habit of closing wether we are working with // a file or memory. if (!closed) { throw new IOException("Stream not closed"); } if(isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } }
// in java/org/apache/tomcat/util/http/fileupload/FileDeleteStrategy.java
public void delete(File fileToDelete) throws IOException { if (fileToDelete.exists() && doDelete(fileToDelete) == false) { throw new IOException("Deletion failed: " + fileToDelete); } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void deleteDirectory(File directory) throws IOException { if (!directory.exists()) { return; } cleanDirectory(directory); if (!directory.delete()) { String message = "Unable to delete directory " + directory + "."; throw new IOException(message); } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void cleanDirectory(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (int i = 0; i < files.length; i++) { File file = files[i]; try { forceDelete(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void forceDelete(File file) throws IOException { if (file.isDirectory()) { deleteDirectory(file); } else { boolean filePresent = file.exists(); if (!file.delete()) { if (!filePresent){ throw new FileNotFoundException("File does not exist: " + file); } String message = "Unable to delete file: " + file; throw new IOException(message); } } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
private static void cleanDirectoryOnExit(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (int i = 0; i < files.length; i++) { File file = files[i]; try { forceDeleteOnExit(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
Override public final void close() throws IOException { // shouldn't be called - we filter it out in writer throw new IOException("close() called - shouldn't happen "); }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public void flushBuffer() throws IOException { //assert out!=null if( out==null ) { throw new IOException( "Buffer overflow, no sink " + limit + " " + buff.length ); } out.realWriteChars( buff, start, end - start ); end=start; }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void close() throws IOException { // shouldn't be called - we filter it out in writer throw new IOException("close() called - shouldn't happen "); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void write(int i) throws IOException { throw new IOException("write( int ) called - shouldn't happen "); }
// in java/org/apache/tomcat/util/buf/ByteChunk.java
public void flushBuffer() throws IOException { //assert out!=null if( out==null ) { throw new IOException( "Buffer overflow, no sink " + limit + " " + buff.length ); } out.realWriteBytes( buff, start, end-start ); end=start; }
// in java/org/apache/el/parser/SimpleCharStream.java
protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
// in java/org/apache/catalina/startup/ContextConfig.java
protected ServletContainerInitializer getServletContainerInitializer( InputStream is) throws IOException { String className = null; if (is != null) { String line = null; try { BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); line = br.readLine(); if (line != null && line.trim().length() > 0) { className = line.trim(); } } catch (UnsupportedEncodingException e) { // Should never happen with UTF-8 // If it does - ignore & return null } } ServletContainerInitializer sci = null; try { Class<?> clazz = Class.forName(className,true, context.getLoader().getClassLoader()); sci = (ServletContainerInitializer) clazz.newInstance(); } catch (ClassNotFoundException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); } catch (InstantiationException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); } catch (IllegalAccessException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); } return sci; }
// in java/org/apache/catalina/startup/TldConfig.java
private XmlErrorHandler tldScanStream(InputStream resourceStream) throws IOException { InputSource source = new InputSource(resourceStream); XmlErrorHandler result = new XmlErrorHandler(); synchronized (tldDigester) { try { tldDigester.setErrorHandler(result); tldDigester.push(this); tldDigester.parse(source); } catch (SAXException s) { // Hack - makes exception handling simpler throw new IOException(s); } finally { tldDigester.reset(); } return result; } }
// in java/org/apache/catalina/startup/ExpandWar.java
public static String expand(Host host, URL war, String pathname) throws IOException { // Make sure that there is no such directory already existing File docBase = new File(host.getAppBaseFile(), pathname); if (docBase.exists()) { // War file is already installed return (docBase.getAbsolutePath()); } // Create the new document base directory docBase.mkdir(); // Expand the WAR into the new document base directory String canonicalDocBasePrefix = docBase.getCanonicalPath(); if (!canonicalDocBasePrefix.endsWith(File.separator)) { canonicalDocBasePrefix += File.separator; } JarURLConnection juc = (JarURLConnection) war.openConnection(); juc.setUseCaches(false); JarFile jarFile = null; InputStream input = null; boolean success = false; try { jarFile = juc.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String name = jarEntry.getName(); File expandedFile = new File(docBase, name); if (!expandedFile.getCanonicalPath().startsWith( canonicalDocBasePrefix)) { // Trying to expand outside the docBase // Throw an exception to stop the deployment throw new IllegalArgumentException( sm.getString("expandWar.illegalPath",war, name, expandedFile.getCanonicalPath(), canonicalDocBasePrefix)); } int last = name.lastIndexOf('/'); if (last >= 0) { File parent = new File(docBase, name.substring(0, last)); if (!parent.mkdirs() && !parent.isDirectory()) { throw new IOException( sm.getString("expandWar.createFailed", parent)); } } if (name.endsWith("/")) { continue; } input = jarFile.getInputStream(jarEntry); if(null == input) throw new ZipException(sm.getString("expandWar.missingJarEntry", jarEntry.getName())); // Bugzilla 33636 expand(input, expandedFile); long lastModified = jarEntry.getTime(); if ((lastModified != -1) && (lastModified != 0)) { expandedFile.setLastModified(lastModified); } input.close(); input = null; } success = true; } catch (IOException e) { throw e; } finally { if (!success) { // If something went wrong, delete expanded dir to keep things // clean deleteDir(docBase); } if (input != null) { try { input.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } input = null; } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } } // Return the absolute path to our new document base directory return (docBase.getAbsolutePath()); }
// in java/org/apache/catalina/loader/WebappLoader.java
private void setRepositories() throws IOException { if (!(container instanceof Context)) return; ServletContext servletContext = ((Context) container).getServletContext(); if (servletContext == null) return; loaderRepositories=new ArrayList<String>(); // Loading the work directory File workDir = (File) servletContext.getAttribute(ServletContext.TEMPDIR); if (workDir == null) { log.info("No work dir for " + servletContext); } if( log.isDebugEnabled() && workDir != null) log.debug(sm.getString("webappLoader.deploy", workDir.getAbsolutePath())); classLoader.setWorkDir(workDir); DirContext resources = container.getResources(); // Setting up the class repository (/WEB-INF/classes), if it exists String classesPath = "/WEB-INF/classes"; DirContext classes = null; try { Object object = resources.lookup(classesPath); if (object instanceof DirContext) { classes = (DirContext) object; } } catch(NamingException e) { // Silent catch: it's valid that no /WEB-INF/classes collection // exists } if (classes != null) { File classRepository = null; String absoluteClassesPath = servletContext.getRealPath(classesPath); if (absoluteClassesPath != null) { classRepository = new File(absoluteClassesPath); } else { classRepository = new File(workDir, classesPath); if (!classRepository.mkdirs() && !classRepository.isDirectory()) { throw new IOException( sm.getString("webappLoader.mkdirFailure")); } if (!copyDir(classes, classRepository)) { throw new IOException( sm.getString("webappLoader.copyFailure")); } } if(log.isDebugEnabled()) log.debug(sm.getString("webappLoader.classDeploy", classesPath, classRepository.getAbsolutePath())); // Adding the repository to the class loader classLoader.addRepository(classesPath + "/", classRepository); loaderRepositories.add(classesPath + "/" ); } // Setting up the JAR repository (/WEB-INF/lib), if it exists String libPath = "/WEB-INF/lib"; classLoader.setJarPath(libPath); DirContext libDir = null; // Looking up directory /WEB-INF/lib in the context try { Object object = resources.lookup(libPath); if (object instanceof DirContext) libDir = (DirContext) object; } catch(NamingException e) { // Silent catch: it's valid that no /WEB-INF/lib collection // exists } if (libDir != null) { boolean copyJars = false; String absoluteLibPath = servletContext.getRealPath(libPath); File destDir = null; if (absoluteLibPath != null) { destDir = new File(absoluteLibPath); } else { copyJars = true; destDir = new File(workDir, libPath); if (!destDir.mkdirs() && !destDir.isDirectory()) { throw new IOException( sm.getString("webappLoader.mkdirFailure")); } } // Looking up directory /WEB-INF/lib in the context NamingEnumeration<NameClassPair> enumeration = null; try { enumeration = libDir.list(""); } catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", libPath)); ioe.initCause(e); throw ioe; } while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String filename = libPath + "/" + ncPair.getName(); if (!filename.endsWith(".jar")) continue; // Copy JAR in the work directory, always (the JAR file // would get locked otherwise, which would make it // impossible to update it or remove it at runtime) File destFile = new File(destDir, ncPair.getName()); if( log.isDebugEnabled()) log.debug(sm.getString("webappLoader.jarDeploy", filename, destFile.getAbsolutePath())); // Bug 45403 - Explicitly call lookup() on the name to check // that the resource is readable. We cannot use resources // returned by listBindings(), because that lists all of them, // but does not perform the necessary checks on each. Object obj = null; try { obj = libDir.lookup(ncPair.getName()); } catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", filename)); ioe.initCause(e); throw ioe; } if (!(obj instanceof Resource)) continue; Resource jarResource = (Resource) obj; if (copyJars) { if (!copy(jarResource.streamContent(), new FileOutputStream(destFile))) { throw new IOException( sm.getString("webappLoader.copyFailure")); } } try { JarFile jarFile = new JarFile(destFile); classLoader.addJar(filename, jarFile, destFile); } catch (Exception ex) { // Catch the exception if there is an empty jar file // Should ignore and continue loading other jar files // in the dir } loaderRepositories.add( filename ); } } }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
Override public void save() throws Exception { if (getReadonly()) { log.error(sm.getString("memoryUserDatabase.readOnly")); return; } if (!isWriteable()) { log.warn(sm.getString("memoryUserDatabase.notPersistable")); return; } // Write out contents to a temporary file File fileNew = new File(pathnameNew); if (!fileNew.isAbsolute()) { fileNew = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathnameNew); } PrintWriter writer = null; try { // Configure our PrintWriter FileOutputStream fos = new FileOutputStream(fileNew); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF8"); writer = new PrintWriter(osw); // Print the file prolog writer.println("<?xml version='1.0' encoding='utf-8'?>"); writer.println("<tomcat-users>"); // Print entries for each defined role, group, and user Iterator<?> values = null; values = getRoles(); while (values.hasNext()) { writer.print(" "); writer.println(values.next()); } values = getGroups(); while (values.hasNext()) { writer.print(" "); writer.println(values.next()); } values = getUsers(); while (values.hasNext()) { writer.print(" "); writer.println(((MemoryUser) values.next()).toXml()); } // Print the file epilog writer.println("</tomcat-users>"); // Check for errors that occurred while printing if (writer.checkError()) { writer.close(); fileNew.delete(); throw new IOException (sm.getString("memoryUserDatabase.writeException", fileNew.getAbsolutePath())); } writer.close(); } catch (IOException e) { if (writer != null) { writer.close(); } fileNew.delete(); throw e; } // Perform the required renames to permanently save this file File fileOld = new File(pathnameOld); if (!fileOld.isAbsolute()) { fileOld = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathnameOld); } fileOld.delete(); File fileOrig = new File(pathname); if (!fileOrig.isAbsolute()) { fileOrig = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathname); } if (fileOrig.exists()) { fileOld.delete(); if (!fileOrig.renameTo(fileOld)) { throw new IOException (sm.getString("memoryUserDatabase.renameOld", fileOld.getAbsolutePath())); } } if (!fileNew.renameTo(fileOrig)) { if (fileOld.exists()) { fileOld.renameTo(fileOrig); } throw new IOException (sm.getString("memoryUserDatabase.renameNew", fileOrig.getAbsolutePath())); } fileOld.delete(); }
// in java/org/apache/catalina/websocket/MessageInbound.java
private void resizeByteBuffer() throws IOException { int maxSize = getByteBufferMaxSize(); if (bb.limit() >= maxSize) { throw new IOException(sm.getString("message.bufferTooSmall")); } long newSize = bb.limit() * 2; if (newSize > maxSize) { newSize = maxSize; } // Cast is safe. newSize < maxSize and maxSize is an int ByteBuffer newBuffer = ByteBuffer.allocate((int) newSize); bb.rewind(); newBuffer.put(bb); bb = newBuffer; }
// in java/org/apache/catalina/websocket/MessageInbound.java
private void resizeCharBuffer() throws IOException { int maxSize = getCharBufferMaxSize(); if (cb.limit() >= maxSize) { throw new IOException(sm.getString("message.bufferTooSmall")); } long newSize = cb.limit() * 2; if (newSize > maxSize) { newSize = maxSize; } // Cast is safe. newSize < maxSize and maxSize is an int CharBuffer newBuffer = CharBuffer.allocate((int) newSize); cb.rewind(); newBuffer.put(cb); cb = newBuffer; }
// in java/org/apache/catalina/websocket/WsInputStream.java
private void makePayloadDataAvailable() throws IOException { if (error != null) { throw new IOException(error); } while (remaining == 0 && !frame.getFin()) { // Need more data - process next frame nextFrame(true); while (frame.isControl()) { if (frame.getOpCode() == Constants.OPCODE_PING) { outbound.pong(frame.getPayLoad()); } else if (frame.getOpCode() == Constants.OPCODE_PONG) { // NO-OP. Swallow it. } else if (frame.getOpCode() == Constants.OPCODE_CLOSE) { outbound.close(frame); } else{ throw new IOException(sm.getString("is.unknownOpCode", Byte.valueOf(frame.getOpCode()))); } nextFrame(true); } if (frame.getOpCode() != Constants.OPCODE_CONTINUATION) { error = sm.getString("is.notContinuation", Byte.valueOf(frame.getOpCode())); throw new IOException(error); } } }
// in java/org/apache/catalina/websocket/WsFrame.java
private int blockingRead(UpgradeProcessor<?> processor) throws IOException { int result = processor.read(); if (result == -1) { throw new IOException(sm.getString("frame.eos")); } return result; }
// in java/org/apache/catalina/websocket/WsFrame.java
private void blockingRead(UpgradeProcessor<?> processor, byte[] bytes) throws IOException { int read = 0; int last = 0; while (read < bytes.length) { last = processor.read(true, bytes, read, bytes.length - read); if (last == -1) { throw new IOException(sm.getString("frame.eos")); } read += last; } }
// in java/org/apache/catalina/websocket/WsFrame.java
private void blockingRead(UpgradeProcessor<?> processor, ByteBuffer bb) throws IOException { int last = 0; while (bb.hasRemaining()) { last = processor.read(); if (last == -1) { throw new IOException(sm.getString("frame.eos")); } bb.put((byte) (last ^ mask[bb.position() % 4])); } bb.flip(); }
// in java/org/apache/catalina/websocket/WsFrame.java
public static WsFrame nextFrame(UpgradeProcessor<?> processor, boolean block) throws IOException { byte[] first = new byte[1]; int read = processor.read(block, first, 0, 1); if (read == 1) { return new WsFrame(first[0], processor); } else if (read == 0) { return null; } else if (read == -1) { throw new EOFException(sm.getString("frame.readEos")); } else { throw new IOException( sm.getString("frame.readFailed", Integer.valueOf(read))); } }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeBinaryData(int b) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (bb.position() == bb.capacity()) { doFlush(false); } if (text == null) { text = Boolean.FALSE; } else if (text == Boolean.TRUE) { // Flush the character data flush(); text = Boolean.FALSE; } bb.put((byte) (b & 0xFF)); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeTextData(char c) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (cb.position() == cb.capacity()) { doFlush(false); } if (text == null) { text = Boolean.TRUE; } else if (text == Boolean.FALSE) { // Flush the binary data flush(); text = Boolean.TRUE; } cb.append(c); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeBinaryMessage(ByteBuffer msgBb) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (text != null) { // Empty the buffer flush(); } text = Boolean.FALSE; doWriteBytes(msgBb, true); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeTextMessage(CharBuffer msgCb) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (text != null) { // Empty the buffer flush(); } text = Boolean.TRUE; doWriteText(msgCb, true); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void flush() throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } doFlush(true); }
// in java/org/apache/catalina/websocket/WsOutbound.java
protected void close(WsFrame frame) throws IOException { if (frame.getPayLoadLength() > 0) { // Must be status (2 bytes) plus optional message if (frame.getPayLoadLength() == 1) { throw new IOException(); } int status = (frame.getPayLoad().get() & 0xFF) << 8; status += frame.getPayLoad().get() & 0xFF; if (validateCloseStatus(status)) { // Echo the status back to the client close(status, frame.getPayLoad()); } else { // Invalid close code close(Constants.STATUS_PROTOCOL_ERROR, null); } } else { // No status close(0, null); } }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void pong(ByteBuffer data) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } doFlush(true); upgradeOutbound.write(0x8A); if (data == null) { upgradeOutbound.write(0); } else { upgradeOutbound.write(data.limit() - data.position()); upgradeOutbound.write(data.array(), data.position(), data.limit() - data.position()); } upgradeOutbound.flush(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
protected void uploadWar(PrintWriter writer, HttpServletRequest request, File war, StringManager smClient) throws IOException { if (war.exists() && !war.delete()) { String msg = smClient.getString("managerServlet.deleteFail", war); throw new IOException(msg); } ServletInputStream istream = null; BufferedOutputStream ostream = null; try { istream = request.getInputStream(); ostream = new BufferedOutputStream(new FileOutputStream(war), 1024); byte buffer[] = new byte[1024]; while (true) { int n = istream.read(buffer); if (n < 0) { break; } ostream.write(buffer, 0, n); } ostream.flush(); ostream.close(); ostream = null; istream.close(); istream = null; } catch (IOException e) { if (war.exists() && !war.delete()) { writer.println( smClient.getString("managerServlet.deleteFail", war)); } throw e; } finally { if (ostream != null) { try { ostream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } ostream = null; } if (istream != null) { try { istream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } istream = null; } } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
protected void waitForAck() throws java.io.IOException { try { boolean ackReceived = false; boolean failAckReceived = false; ackbuf.clear(); int bytesRead = 0; int i = soIn.read(); while ((i != -1) && (bytesRead < Constants.ACK_COMMAND.length)) { bytesRead++; byte d = (byte)i; ackbuf.append(d); if (ackbuf.doesPackageExist() ) { byte[] ackcmd = ackbuf.extractDataPackage(true).getBytes(); ackReceived = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.ACK_DATA); failAckReceived = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA); ackReceived = ackReceived || failAckReceived; break; } i = soIn.read(); } if (!ackReceived) { if (i == -1) throw new IOException(sm.getString("IDataSender.ack.eof",getAddress(), new Integer(socket.getLocalPort()))); else throw new IOException(sm.getString("IDataSender.ack.wrong",getAddress(), new Integer(socket.getLocalPort()))); } else if ( failAckReceived && getThrowOnFailedAck()) { throw new RemoteProcessException("Received a failed ack:org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA"); } } catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; } finally { ackbuf.clear(); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
Override public void start() throws IOException { super.start(); try { setPool(new RxTaskPool(getMaxThreads(),getMinThreads(),this)); } catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } try { getBind(); bind(); Thread t = new Thread(this, "BioReceiver"); t.setDaemon(true); t.start(); } catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
public boolean process(SelectionKey key, boolean waitForAck) throws IOException { int ops = key.readyOps(); key.interestOps(key.interestOps() & ~ops); //in case disconnect has been called if ((!isConnected()) && (!connecting)) throw new IOException("Sender has been disconnected, can't selection key."); if ( !key.isValid() ) throw new IOException("Key is not valid, it must have been cancelled."); if ( key.isConnectable() ) { if ( socketChannel.finishConnect() ) { completeConnect(); if ( current != null ) key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); return false; } else { //wait for the connection to finish key.interestOps(key.interestOps() | SelectionKey.OP_CONNECT); return false; }//end if } else if ( key.isWritable() ) { boolean writecomplete = write(); if ( writecomplete ) { //we are completed, should we read an ack? if ( waitForAck ) { //register to read the ack key.interestOps(key.interestOps() | SelectionKey.OP_READ); } else { //if not, we are ready, setMessage will reregister us for another write interest //do a health check, we have no way of verify a disconnected //socket since we don't register for OP_READ on waitForAck=false read();//this causes overhead setRequestCount(getRequestCount()+1); return true; } } else { //we are not complete, lets write some more key.interestOps(key.interestOps()|SelectionKey.OP_WRITE); }//end if } else if ( key.isReadable() ) { boolean readcomplete = read(); if ( readcomplete ) { setRequestCount(getRequestCount()+1); return true; } else { key.interestOps(key.interestOps() | SelectionKey.OP_READ); }//end if } else { //unknown state, should never happen log.warn("Data is in unknown state. readyOps="+ops); throw new IOException("Data is in unknown state. readyOps="+ops); }//end if return false; }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
protected boolean read() throws IOException { //if there is no message here, we are done if ( current == null ) return true; int read = isUdpBased()?dataChannel.read(readbuf) : socketChannel.read(readbuf); //end of stream if ( read == -1 ) throw new IOException("Unable to receive an ack message. EOF on socket channel has been reached."); //no data read else if ( read == 0 ) return false; readbuf.flip(); ackbuf.append(readbuf,read); readbuf.clear(); if (ackbuf.doesPackageExist() ) { byte[] ackcmd = ackbuf.extractDataPackage(true).getBytes(); boolean ack = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.ACK_DATA); boolean fack = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA); if ( fack && getThrowOnFailedAck() ) throw new RemoteProcessException("Received a failed ack:org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA"); return ack || fack; } else { return false; } }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
protected boolean write() throws IOException { if ( (!isConnected()) || (this.socketChannel==null && this.dataChannel==null)) { throw new IOException("NioSender is not connected, this should not occur."); } if ( current != null ) { if ( remaining > 0 ) { //we have written everything, or we are starting a new package //protect against buffer overwrite int byteswritten = isUdpBased()?dataChannel.write(writebuf) : socketChannel.write(writebuf); if (byteswritten == -1 ) throw new EOFException(); remaining -= byteswritten; //if the entire message was written from the buffer //reset the position counter if ( remaining < 0 ) { remaining = 0; } } return (remaining==0); } //no message to send, we can consider that complete return true; }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
Override public synchronized void connect() throws IOException { if ( connecting || isConnected()) return; connecting = true; if ( isConnected() ) throw new IOException("NioSender is already in connected state."); if ( readbuf == null ) { readbuf = getReadBuffer(); } else { readbuf.clear(); } if ( writebuf == null ) { writebuf = getWriteBuffer(); } else { writebuf.clear(); } if (isUdpBased()) { InetSocketAddress daddr = new InetSocketAddress(getAddress(),getUdpPort()); if ( dataChannel != null ) throw new IOException("Datagram channel has already been established. Connection might be in progress."); dataChannel = DatagramChannel.open(); dataChannel.configureBlocking(false); dataChannel.connect(daddr); completeConnect(); dataChannel.register(getSelector(),SelectionKey.OP_WRITE, this); } else { InetSocketAddress addr = new InetSocketAddress(getAddress(),getPort()); if ( socketChannel != null ) throw new IOException("Socket channel has already been established. Connection might be in progress."); socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); if ( socketChannel.connect(addr) ) { completeConnect(); socketChannel.register(getSelector(), SelectionKey.OP_WRITE, this); } else { socketChannel.register(getSelector(), SelectionKey.OP_CONNECT, this); } } }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
Override public void start() throws IOException { super.start(); try { setPool(new RxTaskPool(getMaxThreads(),getMinThreads(),this)); } catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } try { getBind(); bind(); Thread t = new Thread(this, "NioReceiver"); t.setDaemon(true); t.start(); } catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } }
// in java/org/apache/catalina/session/FileStore.java
private File directory() throws IOException { if (this.directory == null) { return (null); } if (this.directoryFile != null) { // NOTE: Race condition is harmless, so do not synchronize return (this.directoryFile); } File file = new File(this.directory); if (!file.isAbsolute()) { Container container = manager.getContainer(); if (container instanceof Context) { ServletContext servletContext = ((Context) container).getServletContext(); File work = (File) servletContext.getAttribute(ServletContext.TEMPDIR); file = new File(work, this.directory); } else { throw new IllegalArgumentException ("Parent Container is not a Context"); } } if (!file.exists() || !file.isDirectory()) { if (!file.delete() && file.exists()) { throw new IOException( sm.getString("fileStore.deleteFailed", file)); } if (!file.mkdirs() && !file.isDirectory()) { throw new IOException( sm.getString("fileStore.createFailed", file)); } } this.directoryFile = file; return (file); }
// in java/org/apache/catalina/servlets/CGIServlet.java
protected void run() throws IOException { /* * REMIND: this method feels too big; should it be re-written? */ if (!isReady()) { throw new IOException(this.getClass().getName() + ": not ready to run."); } if (debug >= 1 ) { log("runCGI(envp=[" + env + "], command=" + command + ")"); } if ((command.indexOf(File.separator + "." + File.separator) >= 0) || (command.indexOf(File.separator + "..") >= 0) || (command.indexOf(".." + File.separator) >= 0)) { throw new IOException(this.getClass().getName() + "Illegal Character in CGI command " + "path ('.' or '..') detected. Not " + "running CGI [" + command + "]."); } /* original content/structure of this section taken from * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4216884 * with major modifications by Martin Dengler */ Runtime rt = null; BufferedReader cgiHeaderReader = null; InputStream cgiOutput = null; BufferedReader commandsStdErr = null; Thread errReaderThread = null; BufferedOutputStream commandsStdIn = null; Process proc = null; int bufRead = -1; List<String> cmdAndArgs = new ArrayList<String>(); if (cgiExecutable.length() != 0) { cmdAndArgs.add(cgiExecutable); } if (cgiExecutableArgs != null) { cmdAndArgs.addAll(cgiExecutableArgs); } cmdAndArgs.add(command); cmdAndArgs.addAll(params); try { rt = Runtime.getRuntime(); proc = rt.exec( cmdAndArgs.toArray(new String[cmdAndArgs.size()]), hashToStringArray(env), wd); String sContentLength = env.get("CONTENT_LENGTH"); if(!"".equals(sContentLength)) { commandsStdIn = new BufferedOutputStream(proc.getOutputStream()); IOTools.flow(stdin, commandsStdIn); commandsStdIn.flush(); commandsStdIn.close(); } /* we want to wait for the process to exit, Process.waitFor() * is useless in our situation; see * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4223650 */ boolean isRunning = true; commandsStdErr = new BufferedReader (new InputStreamReader(proc.getErrorStream())); final BufferedReader stdErrRdr = commandsStdErr ; errReaderThread = new Thread() { @Override public void run () { sendToLog(stdErrRdr) ; } }; errReaderThread.start(); InputStream cgiHeaderStream = new HTTPHeaderInputStream(proc.getInputStream()); cgiHeaderReader = new BufferedReader(new InputStreamReader(cgiHeaderStream)); while (isRunning) { try { //set headers String line = null; while (((line = cgiHeaderReader.readLine()) != null) && !("".equals(line))) { if (debug >= 2) { log("runCGI: addHeader(\"" + line + "\")"); } if (line.startsWith("HTTP")) { response.setStatus(getSCFromHttpStatusLine(line)); } else if (line.indexOf(":") >= 0) { String header = line.substring(0, line.indexOf(":")).trim(); String value = line.substring(line.indexOf(":") + 1).trim(); if (header.equalsIgnoreCase("status")) { response.setStatus(getSCFromCGIStatusHeader(value)); } else { response.addHeader(header , value); } } else { log("runCGI: bad header line \"" + line + "\""); } } //write output byte[] bBuf = new byte[2048]; OutputStream out = response.getOutputStream(); cgiOutput = proc.getInputStream(); try { while ((bufRead = cgiOutput.read(bBuf)) != -1) { if (debug >= 4) { log("runCGI: output " + bufRead + " bytes of data"); } out.write(bBuf, 0, bufRead); } } finally { // Attempt to consume any leftover byte if something bad happens, // such as a socket disconnect on the servlet side; otherwise, the // external process could hang if (bufRead != -1) { while ((bufRead = cgiOutput.read(bBuf)) != -1) { // NOOP - just read the data } } } proc.exitValue(); // Throws exception if alive isRunning = false; } catch (IllegalThreadStateException e) { try { Thread.sleep(500); } catch (InterruptedException ignored) { // Ignore } } } //replacement for Process.waitFor() } catch (IOException e){ log ("Caught exception " + e); throw e; } finally{ // Close the header reader if (cgiHeaderReader != null) { try { cgiHeaderReader.close(); } catch (IOException ioe) { log ("Exception closing header reader " + ioe); } } // Close the output stream if used if (cgiOutput != null) { try { cgiOutput.close(); } catch (IOException ioe) { log ("Exception closing output stream " + ioe); } } // Make sure the error stream reader has finished if (errReaderThread != null) { try { errReaderThread.join(stderrTimeout); } catch (InterruptedException e) { log ("Interupted waiting for stderr reader thread"); } } if (debug > 4) { log ("Running finally block"); } if (proc != null){ proc.destroy(); proc = null; } } }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected String getAbsolutePath(String path) throws IOException { String pathWithoutContext = SSIServletRequestUtil.getRelativePath(req); String prefix = getPathWithoutFileName(pathWithoutContext); if (prefix == null) { throw new IOException("Couldn't remove filename from path: " + pathWithoutContext); } String fullPath = prefix + path; String retVal = RequestUtil.normalize(fullPath); if (retVal == null) { throw new IOException("Normalization yielded null on path: " + fullPath); } return retVal; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected ServletContextAndPath getServletContextAndPathFromNonVirtualPath( String nonVirtualPath) throws IOException { if (nonVirtualPath.startsWith("/") || nonVirtualPath.startsWith("\\")) { throw new IOException("A non-virtual path can't be absolute: " + nonVirtualPath); } if (nonVirtualPath.indexOf("../") >= 0) { throw new IOException("A non-virtual path can't contain '../' : " + nonVirtualPath); } String path = getAbsolutePath(nonVirtualPath); ServletContextAndPath csAndP = new ServletContextAndPath( context, path); return csAndP; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected ServletContextAndPath getServletContextAndPathFromVirtualPath( String virtualPath) throws IOException { if (!virtualPath.startsWith("/") && !virtualPath.startsWith("\\")) { return new ServletContextAndPath(context, getAbsolutePath(virtualPath)); } String normalized = RequestUtil.normalize(virtualPath); if (isVirtualWebappRelative) { return new ServletContextAndPath(context, normalized); } ServletContext normContext = context.getContext(normalized); if (normContext == null) { throw new IOException("Couldn't get context for path: " + normalized); } //If it's the root context, then there is no context element // to remove, // ie: // '/file1.shtml' vs '/appName1/file1.shtml' if (!isRootContext(normContext)) { String noContext = getPathWithoutContext( normContext.getContextPath(), normalized); if (noContext == null) { throw new IOException( "Couldn't remove context from path: " + normalized); } return new ServletContextAndPath(normContext, noContext); } return new ServletContextAndPath(normContext, normalized); }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected URLConnection getURLConnection(String originalPath, boolean virtual) throws IOException { ServletContextAndPath csAndP = getServletContextAndPath(originalPath, virtual); ServletContext context = csAndP.getServletContext(); String path = csAndP.getPath(); URL url = context.getResource(path); if (url == null) { throw new IOException("Context did not contain resource: " + path); } URLConnection urlConnection = url.openConnection(); return urlConnection; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
Override public String getFileText(String originalPath, boolean virtual) throws IOException { try { ServletContextAndPath csAndP = getServletContextAndPath( originalPath, virtual); ServletContext context = csAndP.getServletContext(); String path = csAndP.getPath(); RequestDispatcher rd = context.getRequestDispatcher(path); if (rd == null) { throw new IOException( "Couldn't get request dispatcher for path: " + path); } ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream(); ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(context, req, res, basos); rd.include(req, responseIncludeWrapper); //We can't assume the included servlet flushed its output responseIncludeWrapper.flushOutputStreamOrWriter(); byte[] bytes = basos.toByteArray(); //Assume platform default encoding unless otherwise specified String retVal; if (inputEncoding == null) { retVal = new String( bytes ); } else { retVal = new String (bytes, B2CConverter.getCharset(inputEncoding)); } //make an assumption that an empty response is a failure. This is // a problem // if a truly empty file //were included, but not sure how else to tell. if (retVal.equals("") && !req.getMethod().equalsIgnoreCase( org.apache.coyote.http11.Constants.HEAD)) { throw new IOException("Couldn't find file: " + path); } return retVal; } catch (ServletException e) { throw new IOException("Couldn't include file: " + originalPath + " because of ServletException: " + e.getMessage()); } }
// in java/org/apache/catalina/connector/Request.java
protected byte[] readChunkedPostBody() throws IOException { ByteChunk body = new ByteChunk(); byte[] buffer = new byte[CACHED_POST_LEN]; int len = 0; while (len > -1) { len = getStream().read(buffer, 0, CACHED_POST_LEN); if (connector.getMaxPostSize() > 0 && (body.getLength() + len) > connector.getMaxPostSize()) { // Too much data checkSwallowInput(); throw new IOException( sm.getString("coyoteRequest.chunkedPostTooLarge")); } if (len > 0) { body.append(buffer, 0, len); } } if (body.getLength() == 0) { return null; } if (body.getLength() < body.getBuffer().length) { int length = body.getLength(); byte[] result = new byte[length]; System.arraycopy(body.getBuffer(), 0, result, 0, length); return result; } return body.getBuffer(); }
// in java/org/apache/catalina/connector/InputBuffer.java
public int readByte() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return bb.substract(); }
// in java/org/apache/catalina/connector/InputBuffer.java
public int read(byte[] b, int off, int len) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return bb.substract(b, off, len); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int read() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return cb.substract(); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int read(char[] cbuf) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return read(cbuf, 0, cbuf.length); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int read(char[] cbuf, int off, int len) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return cb.substract(cbuf, off, len); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public long skip(long n) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } if (n < 0) { throw new IllegalArgumentException(); } long nRead = 0; while (nRead < n) { if (cb.getLength() >= n) { cb.setOffset(cb.getStart() + (int) n); nRead = n; } else { nRead += cb.getLength(); cb.setOffset(cb.getEnd()); int toRead = 0; if (cb.getChars().length < (n - nRead)) { toRead = cb.getChars().length; } else { toRead = (int) (n - nRead); } int nb = realReadChars(cb.getChars(), 0, toRead); if (nb < 0) { break; } } } return nRead; }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public boolean ready() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return (available() > 0); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public void mark(int readAheadLimit) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } if (cb.getLength() <= 0) { cb.setOffset(0); cb.setEnd(0); } else { if ((cb.getBuffer().length > (2 * size)) && (cb.getLength()) < (cb.getStart())) { System.arraycopy(cb.getBuffer(), cb.getStart(), cb.getBuffer(), 0, cb.getLength()); cb.setEnd(cb.getLength()); cb.setOffset(0); } } cb.setLimit(cb.getStart() + readAheadLimit + size); markPos = cb.getStart(); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public void reset() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } if (state == CHAR_STATE) { if (markPos < 0) { cb.recycle(); markPos = -1; throw new IOException(); } else { cb.setOffset(markPos); } } else { bb.recycle(); } }
// in java/org/apache/catalina/core/ApplicationPart.java
Override public void write(String fileName) throws IOException { File file = new File(fileName); if (!file.isAbsolute()) { file = new File(mce.getLocation(), fileName); } try { fileItem.write(file); } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/catalina/util/Conversions.java
public static long byteArrayToLong(byte[] input) throws IOException { if (input.length > 8) { // TODO: Better message throw new IOException(); } int shift = 0; long result = 0; for (int i = input.length - 1; i >= 0; i--) { result = result + ((input[i] & 0xFF) << shift); shift += 8; } return result; }
// in java/javax/servlet/jsp/tagext/BodyContent.java
Override public void flush() throws IOException { throw new IOException("Illegal to flush within a custom tag"); }
// in java/javax/servlet/http/HttpServlet.java
Override public void write(byte buf[], int offset, int len) throws IOException { if (len >= 0) { contentLength += len; } else { // XXX // isn't this really an IllegalArgumentException? String msg = lStrings.getString("err.io.negativelength"); throw new IOException(msg); } }
33
              
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (JasperException e) { // Hack - makes exception handling simpler throw new IOException(e); }
// in java/org/apache/naming/resources/WARDirContext.java
catch (ZipException e) { throw new IOException(e.getMessage(), e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable e) { apr.reset(); e.printStackTrace(); throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable t) { throw new IOException(t); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (CertificateException ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable t) { throw new IOException(t); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
catch (DataFormatException e) { throw new IOException(e); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (NoSuchAlgorithmException e) { throw new IOException(e); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception e) { if( e instanceof IOException ) throw (IOException)e; throw new IOException(e.getMessage(), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassNotFoundException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (InstantiationException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IllegalAccessException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (SAXException s) { // Hack - makes exception handling simpler throw new IOException(s); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
catch (ServletException e) { throw new IOException("Couldn't include file: " + originalPath + " because of ServletException: " + e.getMessage()); }
// in java/org/apache/catalina/core/ApplicationPart.java
catch (Exception e) { throw new IOException(e); }
1262
              
// in java/org/apache/jasper/tagplugins/jstl/Util.java
Override public void write(int b) throws IOException { bos.write(b); }
// in java/org/apache/jasper/runtime/ServletResponseWrapperInclude.java
Override public PrintWriter getWriter() throws IOException { return printWriter; }
// in java/org/apache/jasper/runtime/ServletResponseWrapperInclude.java
Override public ServletOutputStream getOutputStream() throws IOException { throw new IllegalStateException(); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) throws IOException, IllegalStateException, IllegalArgumentException { }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void forward(String relativeUrlPath) throws ServletException, IOException { invokingJspCtxt.forward(relativeUrlPath); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void include(String relativeUrlPath) throws ServletException, IOException { invokingJspCtxt.include(relativeUrlPath); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void include(String relativeUrlPath, boolean flush) throws ServletException, IOException { invokingJspCtxt.include(relativeUrlPath, false); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void handlePageException(Exception ex) throws IOException, ServletException { // Should never be called since handleException() called with a // Throwable in the generated servlet. handlePageException((Throwable) ex); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void handlePageException(Throwable t) throws IOException, ServletException { invokingJspCtxt.handlePageException(t); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void write(int c) throws IOException { if (writer != null) { writer.write(c); } else { ensureOpen(); if (nextChar >= bufferSize) { reAllocBuff (1); } cb[nextChar++] = (char) c; } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void write(char[] cbuf, int off, int len) throws IOException { if (writer != null) { writer.write(cbuf, off, len); } else { ensureOpen(); if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } if (len >= bufferSize - nextChar) reAllocBuff (len); System.arraycopy(cbuf, off, cb, nextChar, len); nextChar+=len; } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void write(char[] buf) throws IOException { if (writer != null) { writer.write(buf); } else { write(buf, 0, buf.length); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void write(String s, int off, int len) throws IOException { if (writer != null) { writer.write(s, off, len); } else { ensureOpen(); if (len >= bufferSize - nextChar) reAllocBuff(len); s.getChars(off, off + len, cb, nextChar); nextChar += len; } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void write(String s) throws IOException { if (writer != null) { writer.write(s); } else { write(s, 0, s.length()); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void newLine() throws IOException { if (writer != null) { writer.write(LINE_SEPARATOR); } else { write(LINE_SEPARATOR); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(boolean b) throws IOException { if (writer != null) { writer.write(b ? "true" : "false"); } else { write(b ? "true" : "false"); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(char c) throws IOException { if (writer != null) { writer.write(String.valueOf(c)); } else { write(String.valueOf(c)); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(int i) throws IOException { if (writer != null) { writer.write(String.valueOf(i)); } else { write(String.valueOf(i)); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(long l) throws IOException { if (writer != null) { writer.write(String.valueOf(l)); } else { write(String.valueOf(l)); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(float f) throws IOException { if (writer != null) { writer.write(String.valueOf(f)); } else { write(String.valueOf(f)); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(double d) throws IOException { if (writer != null) { writer.write(String.valueOf(d)); } else { write(String.valueOf(d)); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(char[] s) throws IOException { if (writer != null) { writer.write(s); } else { write(s); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(String s) throws IOException { if (s == null) s = "null"; if (writer != null) { writer.write(s); } else { write(s); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(Object obj) throws IOException { if (writer != null) { writer.write(String.valueOf(obj)); } else { write(String.valueOf(obj)); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println() throws IOException { newLine(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(boolean x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(char x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(int x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(long x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(float x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(double x) throws IOException{ print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(char x[]) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(String x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(Object x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void clear() throws IOException { if (writer != null) { throw new IOException(); } else { nextChar = 0; if (LIMIT_BUFFER && (cb.length > Constants.DEFAULT_TAG_BUFFER_SIZE)) { cb = new char[Constants.DEFAULT_TAG_BUFFER_SIZE]; bufferSize = cb.length; } } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void clearBuffer() throws IOException { if (writer == null) { this.clear(); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void close() throws IOException { if (writer != null) { writer.close(); } else { closed = true; } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void writeOut(Writer out) throws IOException { if (writer == null) { out.write(cb, 0, nextChar); // Flush not called as the writer passed could be a BodyContent and // it doesn't allow to flush. } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
private void ensureOpen() throws IOException { if (closed) throw new IOException("Stream closed"); }
// in java/org/apache/jasper/runtime/HttpJspBase.java
Override public final void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { _jspService(request, response); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) throws IOException { _initialize(servlet, request, response, errorPageURL, needsSession, bufferSize, autoFlush); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void include(String relativeUrlPath) throws ServletException, IOException { JspRuntimeLibrary .include(request, response, relativeUrlPath, out, true); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void include(final String relativeUrlPath, final boolean flush) throws ServletException, IOException { if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doInclude(relativeUrlPath, flush); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doInclude(String relativeUrlPath, boolean flush) throws ServletException, IOException { JspRuntimeLibrary.include(request, response, relativeUrlPath, out, flush); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void forward(final String relativeUrlPath) throws ServletException, IOException { if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doForward(relativeUrlPath); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doForward(String relativeUrlPath) throws ServletException, IOException { // JSP.4.5 If the buffer was flushed, throw IllegalStateException try { out.clear(); } catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer .getMessage("jsp.error.attempt_to_clear_flushed_buffer")); ise.initCause(ex); throw ise; } // Make sure that the response object is not the wrapper for include while (response instanceof ServletResponseWrapperInclude) { response = ((ServletResponseWrapperInclude) response).getResponse(); } final String path = getAbsolutePathRelativeToContext(relativeUrlPath); String includeUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); if (includeUri != null) request.removeAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH); try { context.getRequestDispatcher(path).forward(request, response); } finally { if (includeUri != null) request.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH, includeUri); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void handlePageException(Exception ex) throws IOException, ServletException { // Should never be called since handleException() called with a // Throwable in the generated servlet. handlePageException((Throwable) ex); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void handlePageException(final Throwable t) throws IOException, ServletException { if (t == null) throw new NullPointerException("null Throwable"); if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doHandlePageException(t); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doHandlePageException(Throwable t) throws IOException, ServletException { if (errorPageURL != null && !errorPageURL.equals("")) { /* * Set request attributes. Do not set the * javax.servlet.error.exception attribute here (instead, set in the * generated servlet code for the error page) in order to prevent * the ErrorReportValve, which is invoked as part of forwarding the * request to the error page, from throwing it if the response has * not been committed (the response will have been committed if the * error page is a JSP page). */ request.setAttribute(PageContext.EXCEPTION, t); request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, ((HttpServletRequest) request).getRequestURI()); request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, config.getServletName()); try { forward(errorPageURL); } catch (IllegalStateException ise) { include(errorPageURL); } // The error page could be inside an include. Object newException = request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); // t==null means the attribute was not set. if ((newException != null) && (newException == t)) { request.removeAttribute(RequestDispatcher.ERROR_EXCEPTION); } // now clear the error code - to prevent double handling. request.removeAttribute(RequestDispatcher.ERROR_STATUS_CODE); request.removeAttribute(RequestDispatcher.ERROR_REQUEST_URI); request.removeAttribute(RequestDispatcher.ERROR_SERVLET_NAME); request.removeAttribute(PageContext.EXCEPTION); } else { // Otherwise throw the exception wrapped inside a ServletException. // Set the exception as the root cause in the ServletException // to get a stack trace for the real problem if (t instanceof IOException) throw (IOException) t; if (t instanceof ServletException) throw (ServletException) t; if (t instanceof RuntimeException) throw (RuntimeException) t; Throwable rootCause = null; if (t instanceof JspException) { rootCause = ((JspException) t).getCause(); } else if (t instanceof ELException) { rootCause = ((ELException) t).getCause(); } if (rootCause != null) { throw new ServletException(t.getClass().getName() + ": " + t.getMessage(), rootCause); } throw new ServletException(t); } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
protected final void flushBuffer() throws IOException { if (bufferSize == 0) return; flushed = true; ensureOpen(); if (nextChar == 0) return; initOut(); out.write(cb, 0, nextChar); nextChar = 0; }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
private void initOut() throws IOException { if (out == null) { out = response.getWriter(); } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public final void clear() throws IOException { if ((bufferSize == 0) && (out != null)) // clear() is illegal after any unbuffered output (JSP.5.5) throw new IllegalStateException( getLocalizeMessage("jsp.error.ise_on_clear")); if (flushed) throw new IOException( getLocalizeMessage("jsp.error.attempt_to_clear_flushed_buffer")); ensureOpen(); nextChar = 0; }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void clearBuffer() throws IOException { if (bufferSize == 0) throw new IllegalStateException( getLocalizeMessage("jsp.error.ise_on_clear")); ensureOpen(); nextChar = 0; }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
private final void bufferOverflow() throws IOException { throw new IOException(getLocalizeMessage("jsp.error.overflow")); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void flush() throws IOException { flushBuffer(); if (out != null) { out.flush(); } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void close() throws IOException { if (response == null || closed) // multiple calls to close is OK return; flush(); if (out != null) out.close(); out = null; closed = true; }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
private void ensureOpen() throws IOException { if (response == null || closed) throw new IOException("Stream closed"); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void write(int c) throws IOException { ensureOpen(); if (bufferSize == 0) { initOut(); out.write(c); } else { if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); cb[nextChar++] = (char) c; } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void write(char cbuf[], int off, int len) throws IOException { ensureOpen(); if (bufferSize == 0) { initOut(); out.write(cbuf, off, len); return; } if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } if (len >= bufferSize) { /* If the request length exceeds the size of the output buffer, flush the buffer and then write the data directly. In this way buffered streams will cascade harmlessly. */ if (autoFlush) flushBuffer(); else bufferOverflow(); initOut(); out.write(cbuf, off, len); return; } int b = off, t = off + len; while (b < t) { int d = min(bufferSize - nextChar, t - b); System.arraycopy(cbuf, b, cb, nextChar, d); b += d; nextChar += d; if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void write(char buf[]) throws IOException { write(buf, 0, buf.length); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void write(String s, int off, int len) throws IOException { ensureOpen(); if (bufferSize == 0) { initOut(); out.write(s, off, len); return; } int b = off, t = off + len; while (b < t) { int d = min(bufferSize - nextChar, t - b); s.getChars(b, b + d, cb, nextChar); b += d; nextChar += d; if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void write(String s) throws IOException { // Simple fix for Bugzilla 35410 // Calling the other write function so as to init the buffer anyways if(s == null) { write(s, 0, 0); } else { write(s, 0, s.length()); } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void newLine() throws IOException { write(lineSeparator); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(boolean b) throws IOException { write(b ? "true" : "false"); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(char c) throws IOException { write(String.valueOf(c)); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(int i) throws IOException { write(String.valueOf(i)); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(long l) throws IOException { write(String.valueOf(l)); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(float f) throws IOException { write(String.valueOf(f)); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(double d) throws IOException { write(String.valueOf(d)); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(char s[]) throws IOException { write(s); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(String s) throws IOException { if (s == null) { s = "null"; } write(s); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(Object obj) throws IOException { write(String.valueOf(obj)); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println() throws IOException { newLine(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(boolean x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(char x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(int x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(long x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(float x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(double x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(char x[]) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(String x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(Object x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void include(ServletRequest request, ServletResponse response, String relativePath, JspWriter out, boolean flush) throws IOException, ServletException { if (flush && !(out instanceof BodyContent)) out.flush(); // FIXME - It is tempting to use request.getRequestDispatcher() to // resolve a relative path directly, but Catalina currently does not // take into account whether the caller is inside a RequestDispatcher // include or not. Whether Catalina *should* take that into account // is a spec issue currently under review. In the mean time, // replicate Jasper's previous behavior String resourcePath = getContextRelativePath(request, relativePath); RequestDispatcher rd = request.getRequestDispatcher(resourcePath); rd.include(request, new ServletResponseWrapperInclude(response, out)); }
// in java/org/apache/jasper/compiler/JspUtil.java
public static InputStream getInputStream(String fname, JarFile jarFile, JspCompilationContext ctxt) throws IOException { InputStream in = null; if (jarFile != null) { String jarEntryName = fname.substring(1, fname.length()); ZipEntry jarEntry = jarFile.getEntry(jarEntryName); if (jarEntry == null) { throw new FileNotFoundException(Localizer.getMessage( "jsp.error.file.not.found", fname)); } in = jarFile.getInputStream(jarEntry); } else { in = ctxt.getResourceAsStream(fname); } if (in == null) { throw new FileNotFoundException(Localizer.getMessage( "jsp.error.file.not.found", fname)); } return in; }
// in java/org/apache/jasper/compiler/JspUtil.java
static InputStreamReader getReader(String fname, String encoding, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err) throws JasperException, IOException { return getReader(fname, encoding, jarFile, ctxt, err, 0); }
// in java/org/apache/jasper/compiler/JspUtil.java
static InputStreamReader getReader(String fname, String encoding, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err, int skip) throws JasperException, IOException { InputStreamReader reader = null; InputStream in = getInputStream(fname, jarFile, ctxt); for (int i = 0; i < skip; i++) { in.read(); } try { reader = new InputStreamReader(in, encoding); } catch (UnsupportedEncodingException ex) { err.jspError("jsp.error.unsupported.encoding", encoding); } return reader; }
// in java/org/apache/jasper/compiler/SmapUtil.java
public static String[] generateSmap( JspCompilationContext ctxt, Node.Nodes pageNodes) throws IOException { // Scan the nodes for presence of Jasper generated inner classes PreScanVisitor psVisitor = new PreScanVisitor(); try { pageNodes.visit(psVisitor); } catch (JasperException ex) { } HashMap<String, SmapStratum> map = psVisitor.getMap(); // set up our SMAP generator SmapGenerator g = new SmapGenerator(); /** Disable reading of input SMAP because: 1. There is a bug here: getRealPath() is null if .jsp is in a jar Bugzilla 14660. 2. Mappings from other sources into .jsp files are not supported. TODO: fix 1. if 2. is not true. // determine if we have an input SMAP String smapPath = inputSmapPath(ctxt.getRealPath(ctxt.getJspFile())); File inputSmap = new File(smapPath); if (inputSmap.exists()) { byte[] embeddedSmap = null; byte[] subSmap = SDEInstaller.readWhole(inputSmap); String subSmapString = new String(subSmap, SMAP_ENCODING); g.addSmap(subSmapString, "JSP"); } **/ // now, assemble info about our own stratum (JSP) using JspLineMap SmapStratum s = new SmapStratum("JSP"); g.setOutputFileName(unqualify(ctxt.getServletJavaFileName())); // Map out Node.Nodes evaluateNodes(pageNodes, s, map, ctxt.getOptions().getMappedFile()); s.optimizeLineSection(); g.addStratum(s, true); if (ctxt.getOptions().isSmapDumped()) { File outSmap = new File(ctxt.getClassFileName() + ".smap"); PrintWriter so = new PrintWriter( new OutputStreamWriter( new FileOutputStream(outSmap), SMAP_ENCODING)); so.print(g.getString()); so.close(); } String classFileName = ctxt.getClassFileName(); int innerClassCount = map.size(); String [] smapInfo = new String[2 + innerClassCount*2]; smapInfo[0] = classFileName; smapInfo[1] = g.getString(); int count = 2; Iterator<Map.Entry<String,SmapStratum>> iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String,SmapStratum> entry = iter.next(); String innerClass = entry.getKey(); s = entry.getValue(); s.optimizeLineSection(); g = new SmapGenerator(); g.setOutputFileName(unqualify(ctxt.getServletJavaFileName())); g.addStratum(s, true); String innerClassFileName = classFileName.substring(0, classFileName.indexOf(".class")) + '$' + innerClass + ".class"; if (ctxt.getOptions().isSmapDumped()) { File outSmap = new File(innerClassFileName + ".smap"); PrintWriter so = new PrintWriter( new OutputStreamWriter( new FileOutputStream(outSmap), SMAP_ENCODING)); so.print(g.getString()); so.close(); } smapInfo[count] = innerClassFileName; smapInfo[count+1] = g.getString(); count += 2; } return smapInfo; }
// in java/org/apache/jasper/compiler/SmapUtil.java
public static void installSmap(String[] smap) throws IOException { if (smap == null) { return; } for (int i = 0; i < smap.length; i += 2) { File outServlet = new File(smap[i]); SDEInstaller.install(outServlet, smap[i+1].getBytes(Constants.ISO_8859_1)); } }
// in java/org/apache/jasper/compiler/SmapUtil.java
static void install(File classFile, byte[] smap) throws IOException { File tmpFile = new File(classFile.getPath() + "tmp"); new SDEInstaller(classFile, smap, tmpFile); if (!classFile.delete()) { throw new IOException("classFile.delete() failed"); } if (!tmpFile.renameTo(classFile)) { throw new IOException("tmpFile.renameTo(classFile) failed"); } }
// in java/org/apache/jasper/compiler/SmapUtil.java
static byte[] readWhole(File input) throws IOException { FileInputStream inStream = new FileInputStream(input); int len = (int)input.length(); byte[] bytes = new byte[len]; if (inStream.read(bytes, 0, len) != len) { throw new IOException("expected size: " + len); } inStream.close(); return bytes; }
// in java/org/apache/jasper/compiler/SmapUtil.java
void addSDE() throws UnsupportedEncodingException, IOException { copy(4 + 2 + 2); // magic min/maj version int constantPoolCountPos = genPos; int constantPoolCount = readU2(); if (log.isDebugEnabled()) log.debug("constant pool count: " + constantPoolCount); writeU2(constantPoolCount); // copy old constant pool return index of SDE symbol, if found sdeIndex = copyConstantPool(constantPoolCount); if (sdeIndex < 0) { // if "SourceDebugExtension" symbol not there add it writeUtf8ForSDE(); // increment the countantPoolCount sdeIndex = constantPoolCount; ++constantPoolCount; randomAccessWriteU2(constantPoolCountPos, constantPoolCount); if (log.isDebugEnabled()) log.debug("SourceDebugExtension not found, installed at: " + sdeIndex); } else { if (log.isDebugEnabled()) log.debug("SourceDebugExtension found at: " + sdeIndex); } copy(2 + 2 + 2); // access, this, super int interfaceCount = readU2(); writeU2(interfaceCount); if (log.isDebugEnabled()) log.debug("interfaceCount: " + interfaceCount); copy(interfaceCount * 2); copyMembers(); // fields copyMembers(); // methods int attrCountPos = genPos; int attrCount = readU2(); writeU2(attrCount); if (log.isDebugEnabled()) log.debug("class attrCount: " + attrCount); // copy the class attributes, return true if SDE attr found (not copied) if (!copyAttrs(attrCount)) { // we will be adding SDE and it isn't already counted ++attrCount; randomAccessWriteU2(attrCountPos, attrCount); if (log.isDebugEnabled()) log.debug("class attrCount incremented"); } writeAttrForSDE(sdeIndex); }
// in java/org/apache/jasper/compiler/SmapUtil.java
int copyConstantPool(int constantPoolCount) throws UnsupportedEncodingException, IOException { int sdeIndex = -1; // copy const pool index zero not in class file for (int i = 1; i < constantPoolCount; ++i) { int tag = readU1(); writeU1(tag); switch (tag) { case 7 : // Class case 8 : // String if (log.isDebugEnabled()) log.debug(i + " copying 2 bytes"); copy(2); break; case 9 : // Field case 10 : // Method case 11 : // InterfaceMethod case 3 : // Integer case 4 : // Float case 12 : // NameAndType if (log.isDebugEnabled()) log.debug(i + " copying 4 bytes"); copy(4); break; case 5 : // Long case 6 : // Double if (log.isDebugEnabled()) log.debug(i + " copying 8 bytes"); copy(8); i++; break; case 1 : // Utf8 int len = readU2(); writeU2(len); byte[] utf8 = readBytes(len); String str = new String(utf8, "UTF-8"); if (log.isDebugEnabled()) log.debug(i + " read class attr -- '" + str + "'"); if (str.equals(nameSDE)) { sdeIndex = i; } writeBytes(utf8); break; default : throw new IOException("unexpected tag: " + tag); } } return sdeIndex; }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parse(String inFileName) throws FileNotFoundException, JasperException, IOException { // If we're parsing a packaged tag file or a resource included by it // (using an include directive), ctxt.getTagFileJar() returns the // JAR file from which to read the tag file or included resource, // respectively. isTagFile = ctxt.isTagFile(); directiveOnly = false; return doParse(inFileName, null, ctxt.getTagFileJarResource()); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parseDirectives(String inFileName) throws FileNotFoundException, JasperException, IOException { // If we're parsing a packaged tag file or a resource included by it // (using an include directive), ctxt.getTagFileJar() returns the // JAR file from which to read the tag file or included resource, // respectively. isTagFile = ctxt.isTagFile(); directiveOnly = true; return doParse(inFileName, null, ctxt.getTagFileJarResource()); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parse(String inFileName, Node parent, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { // For files that are statically included, isTagfile and directiveOnly // remain unchanged. return doParse(inFileName, parent, jarResource); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parseTagFileDirectives(String inFileName, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { boolean isTagFileSave = isTagFile; boolean directiveOnlySave = directiveOnly; isTagFile = true; directiveOnly = true; Node.Nodes page = doParse(inFileName, null, jarResource); directiveOnly = directiveOnlySave; isTagFile = isTagFileSave; return page; }
// in java/org/apache/jasper/compiler/ParserController.java
private Node.Nodes doParse(String inFileName, Node parent, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { Node.Nodes parsedPage = null; isEncodingSpecifiedInProlog = false; isBomPresent = false; isDefaultPageEncoding = false; JarFile jarFile = (jarResource == null) ? null : jarResource.getJarFile(); String absFileName = resolveFileName(inFileName); String jspConfigPageEnc = getJspConfigPageEncoding(absFileName); // Figure out what type of JSP document and encoding type we are // dealing with determineSyntaxAndEncoding(absFileName, jarFile, jspConfigPageEnc); if (parent != null) { // Included resource, add to dependent list if (jarFile == null) { compiler.getPageInfo().addDependant(absFileName, ctxt.getLastModified(absFileName)); } else { String entry = absFileName.substring(1); compiler.getPageInfo().addDependant( jarResource.getEntry(entry).toString(), Long.valueOf(jarFile.getEntry(entry).getTime())); } } if ((isXml && isEncodingSpecifiedInProlog) || isBomPresent) { /* * Make sure the encoding explicitly specified in the XML * prolog (if any) matches that in the JSP config element * (if any), treating "UTF-16", "UTF-16BE", and "UTF-16LE" as * identical. */ if (jspConfigPageEnc != null && !jspConfigPageEnc.equals(sourceEnc) && (!jspConfigPageEnc.startsWith("UTF-16") || !sourceEnc.startsWith("UTF-16"))) { err.jspError("jsp.error.prolog_config_encoding_mismatch", sourceEnc, jspConfigPageEnc); } } // Dispatch to the appropriate parser if (isXml) { // JSP document (XML syntax) // InputStream for jspx page is created and properly closed in // JspDocumentParser. parsedPage = JspDocumentParser.parse(this, absFileName, jarFile, parent, isTagFile, directiveOnly, sourceEnc, jspConfigPageEnc, isEncodingSpecifiedInProlog, isBomPresent); } else { // Standard syntax InputStreamReader inStreamReader = null; try { inStreamReader = JspUtil.getReader(absFileName, sourceEnc, jarFile, ctxt, err, skip); JspReader jspReader = new JspReader(ctxt, absFileName, sourceEnc, inStreamReader, err); parsedPage = Parser.parse(this, jspReader, parent, isTagFile, directiveOnly, jarResource, sourceEnc, jspConfigPageEnc, isDefaultPageEncoding, isBomPresent); } finally { if (inStreamReader != null) { try { inStreamReader.close(); } catch (Exception any) { } } } } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } baseDirStack.pop(); return parsedPage; }
// in java/org/apache/jasper/compiler/ParserController.java
private void determineSyntaxAndEncoding(String absFileName, JarFile jarFile, String jspConfigPageEnc) throws JasperException, IOException { isXml = false; /* * 'true' if the syntax (XML or standard) of the file is given * from external information: either via a JSP configuration element, * the ".jspx" suffix, or the enclosing file (for included resources) */ boolean isExternal = false; /* * Indicates whether we need to revert from temporary usage of * "ISO-8859-1" back to "UTF-8" */ boolean revert = false; JspConfig jspConfig = ctxt.getOptions().getJspConfig(); JspConfig.JspProperty jspProperty = jspConfig.findJspProperty( absFileName); if (jspProperty.isXml() != null) { // If <is-xml> is specified in a <jsp-property-group>, it is used. isXml = JspUtil.booleanValue(jspProperty.isXml()); isExternal = true; } else if (absFileName.endsWith(".jspx") || absFileName.endsWith(".tagx")) { isXml = true; isExternal = true; } if (isExternal && !isXml) { // JSP (standard) syntax. Use encoding specified in jsp-config // if provided. sourceEnc = jspConfigPageEnc; if (sourceEnc != null) { return; } // We don't know the encoding, so use BOM to determine it sourceEnc = "ISO-8859-1"; } else { // XML syntax or unknown, (auto)detect encoding ... Object[] ret = XMLEncodingDetector.getEncoding(absFileName, jarFile, ctxt, err); sourceEnc = (String) ret[0]; if (((Boolean) ret[1]).booleanValue()) { isEncodingSpecifiedInProlog = true; } if (((Boolean) ret[2]).booleanValue()) { isBomPresent = true; } skip = ((Integer) ret[3]).intValue(); if (!isXml && sourceEnc.equals("UTF-8")) { /* * We don't know if we're dealing with XML or standard syntax. * Therefore, we need to check to see if the page contains * a <jsp:root> element. * * We need to be careful, because the page may be encoded in * ISO-8859-1 (or something entirely different), and may * contain byte sequences that will cause a UTF-8 converter to * throw exceptions. * * It is safe to use a source encoding of ISO-8859-1 in this * case, as there are no invalid byte sequences in ISO-8859-1, * and the byte/character sequences we're looking for (i.e., * <jsp:root>) are identical in either encoding (both UTF-8 * and ISO-8859-1 are extensions of ASCII). */ sourceEnc = "ISO-8859-1"; revert = true; } } if (isXml) { // (This implies 'isExternal' is TRUE.) // We know we're dealing with a JSP document (via JSP config or // ".jspx" suffix), so we're done. return; } /* * At this point, 'isExternal' or 'isXml' is FALSE. * Search for jsp:root action, in order to determine if we're dealing * with XML or standard syntax (unless we already know what we're * dealing with, i.e., when 'isExternal' is TRUE and 'isXml' is FALSE). * No check for XML prolog, since nothing prevents a page from * outputting XML and still using JSP syntax (in this case, the * XML prolog is treated as template text). */ JspReader jspReader = null; try { jspReader = new JspReader(ctxt, absFileName, sourceEnc, jarFile, err); } catch (FileNotFoundException ex) { throw new JasperException(ex); } jspReader.setSingleFile(true); Mark startMark = jspReader.mark(); if (!isExternal) { jspReader.reset(startMark); if (hasJspRoot(jspReader)) { if (revert) { sourceEnc = "UTF-8"; } isXml = true; return; } else { if (revert && isBomPresent) { sourceEnc = "UTF-8"; } isXml = false; } } /* * At this point, we know we're dealing with JSP syntax. * If an XML prolog is provided, it's treated as template text. * Determine the page encoding from the page directive, unless it's * specified via JSP config. */ if (!isBomPresent) { sourceEnc = jspConfigPageEnc; if (sourceEnc == null) { sourceEnc = getPageEncodingForJspSyntax(jspReader, startMark); if (sourceEnc == null) { // Default to "ISO-8859-1" per JSP spec sourceEnc = "ISO-8859-1"; isDefaultPageEncoding = true; } } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
Override public void scan(JarURLConnection urlConn) throws IOException { tldScanJar(urlConn); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
Override public void scan(File file) throws IOException { File metaInf = new File(file, "META-INF"); if (metaInf.isDirectory()) { tldScanDir(metaInf); } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private void tldScanDir(File start) throws IOException { File[] fileList = start.listFiles(); if (fileList != null) { for (int i = 0; i < fileList.length; i++) { // Scan recursively if (fileList[i].isDirectory()) { tldScanDir(fileList[i]); } else if (fileList[i].getAbsolutePath().endsWith(TLD_EXT)) { InputStream stream = null; try { stream = new FileInputStream(fileList[i]); tldScanStream( fileList[i].toURI().toString(), null, stream); } finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } } } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private void tldScanJar(JarURLConnection jarConn) throws IOException { Jar jar = null; InputStream is; boolean foundTld = false; URL resourceURL = jarConn.getJarFileURL(); String resourcePath = resourceURL.toString(); try { jar = JarFactory.newInstance(jarConn.getURL()); jar.nextEntry(); String entryName = jar.getEntryName(); while (entryName != null) { if (entryName.startsWith("META-INF/") && entryName.endsWith(".tld")) { is = null; try { is = jar.getEntryInputStream(); foundTld = true; tldScanStream(resourcePath, entryName, is); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } } } jar.nextEntry(); entryName = jar.getEntryName(); } } finally { if (jar != null) { jar.close(); } } if (!foundTld) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.tldCache.noTldInJar", resourcePath)); } else if (showTldScanWarning) { // Not entirely thread-safe but a few duplicate log messages are // not a huge issue showTldScanWarning = false; log.info(Localizer.getMessage("jsp.tldCache.noTldSummary")); } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private void tldScanStream(String resourcePath, String entryName, InputStream stream) throws IOException { try { // Parse the tag library descriptor at the specified resource path String uri = null; TreeNode tld = new ParserUtils().parseXMLDocument(resourcePath, stream); TreeNode uriNode = tld.findChild("uri"); if (uriNode != null) { String body = uriNode.getBody(); if (body != null) uri = body; } // Add implicit map entry only if its uri is not already // present in the map if (uri != null && mappings.get(uri) == null) { TldLocation location; if (entryName == null) { location = new TldLocation(resourcePath); } else { location = new TldLocation(entryName, resourcePath); } mappings.put(uri, location); } } catch (JasperException e) { // Hack - makes exception handling simpler throw new IOException(e); } }
// in java/org/apache/jasper/compiler/JavacErrorDetail.java
private String[] readFile(InputStream s) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(s)); List<String> lines = new ArrayList<String>(); String line; while ( (line = reader.readLine()) != null ) { lines.add(line); } return lines.toArray( new String[lines.size()] ); }
// in java/org/apache/jasper/compiler/JarURLResource.java
Override public JarFile getJarFile() throws IOException { URL jarFileUrl = new URL("jar:" + jarUrl + "!/"); JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection(); conn.setUseCaches(false); conn.connect(); return conn.getJarFile(); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public static JavacErrorDetail[] parseJavacErrors(String errMsg, String fname, Node.Nodes page) throws JasperException, IOException { return parseJavacMessage(errMsg, fname, page); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
private static JavacErrorDetail[] parseJavacMessage( String errMsg, String fname, Node.Nodes page) throws IOException, JasperException { ArrayList<JavacErrorDetail> errors = new ArrayList<JavacErrorDetail>(); StringBuilder errMsgBuf = null; int lineNum = -1; JavacErrorDetail javacError = null; BufferedReader reader = new BufferedReader(new StringReader(errMsg)); /* * Parse compilation errors. Each compilation error consists of a file * path and error line number, followed by a number of lines describing * the error. */ String line = null; while ((line = reader.readLine()) != null) { /* * Error line number is delimited by set of colons. * Ignore colon following drive letter on Windows (fromIndex = 2). * XXX Handle deprecation warnings that don't have line info */ int beginColon = line.indexOf(':', 2); int endColon = line.indexOf(':', beginColon + 1); if ((beginColon >= 0) && (endColon >= 0)) { if (javacError != null) { // add previous error to error vector errors.add(javacError); } String lineNumStr = line.substring(beginColon + 1, endColon); try { lineNum = Integer.parseInt(lineNumStr); } catch (NumberFormatException e) { lineNum = -1; } errMsgBuf = new StringBuilder(); javacError = createJavacError(fname, page, errMsgBuf, lineNum); } // Ignore messages preceding first error if (errMsgBuf != null) { errMsgBuf.append(line); errMsgBuf.append(Constants.NEWLINE); } } // Add last error to error vector if (javacError != null) { errors.add(javacError); } reader.close(); JavacErrorDetail[] errDetails = null; if (errors.size() > 0) { errDetails = new JavacErrorDetail[errors.size()]; errors.toArray(errDetails); } return errDetails; }
// in java/org/apache/jasper/compiler/AntCompiler.java
Override public void write(byte[] b) throws IOException { findStream().write(b); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile) throws ServletException, IOException, FileNotFoundException { Servlet servlet; try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if ((available > 0L) && (available < Long.MAX_VALUE)) { if (available > System.currentTimeMillis()) { response.setDateHeader("Retry-After", available); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, Localizer.getMessage("jsp.error.unavailable")); return; } // Wait period has expired. Reset. available = 0; } /* * (1) Compile */ if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; // The following sets reload to true, if necessary ctxt.compile(); } } else { if (compileException != null) { // Throw cached compilation exception throw compileException; } } /* * (2) (Re)load servlet class file */ servlet = getServlet(); // If a page is to be precompiled only, return. if (precompile) { return; } } catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; } catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } try { /* * (3) Handle limitation of number of loaded Jsps */ if (unloadAllowed) { synchronized(this) { if (unloadByCount) { if (unloadHandle == null) { unloadHandle = ctxt.getRuntimeContext().push(this); } else if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { ctxt.getRuntimeContext().makeYoungest(unloadHandle); lastUsageTime = System.currentTimeMillis(); } } else { if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { lastUsageTime = System.currentTimeMillis(); } } } } /* * (4) Service request */ if (servlet instanceof SingleThreadModel) { // sync on the wrapper so that the freshness // of the page is determined right before servicing synchronized (this) { servlet.service(request, response); } } else { servlet.service(request, response); } } catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); } catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public void init(ServletConfig config) throws ServletException { super.init(config); this.config = config; this.context = config.getServletContext(); // Initialize the JSP Runtime Context // Check for a custom Options implementation String engineOptionsName = config.getInitParameter("engineOptionsClass"); if (engineOptionsName != null) { // Instantiate the indicated Options implementation try { ClassLoader loader = Thread.currentThread() .getContextClassLoader(); Class<?> engineOptionsClass = loader.loadClass(engineOptionsName); Class<?>[] ctorSig = { ServletConfig.class, ServletContext.class }; Constructor<?> ctor = engineOptionsClass.getConstructor(ctorSig); Object[] args = { config, context }; options = (Options) ctor.newInstance(args); } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); // Need to localize this. log.warn("Failed to load engineOptionsClass", e); // Use the default Options implementation options = new EmbeddedServletOptions(config, context); } } else { // Use the default Options implementation options = new EmbeddedServletOptions(config, context); } rctxt = new JspRuntimeContext(context, options); if (config.getInitParameter("jspFile") != null) { jspFile = config.getInitParameter("jspFile"); try { if (null == context.getResource(jspFile)) { throw new ServletException("missing jspFile"); } } catch (MalformedURLException e) { throw new ServletException("Can not locate jsp file", e); } try { if (SecurityUtil.isPackageProtectionEnabled()){ AccessController.doPrivileged(new PrivilegedExceptionAction<Object>(){ @Override public Object run() throws IOException, ServletException { serviceJspFile(null, null, jspFile, true); return null; } }); } else { serviceJspFile(null, null, jspFile, true); } } catch (IOException e) { throw new ServletException("Could not precompile jsp: " + jspFile, e); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ServletException) throw (ServletException)t; throw new ServletException("Could not precompile jsp: " + jspFile, e); } }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public Object run() throws IOException, ServletException { serviceJspFile(null, null, jspFile, true); return null; }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //jspFile may be configured as an init-param for this servlet instance String jspUri = jspFile; if (jspUri == null) { // JSP specified via <jsp-file> in <servlet> declaration and supplied through //custom servlet container code jspUri = (String) request.getAttribute(Constants.JSP_FILE); } if (jspUri == null) { /* * Check to see if the requested JSP has been the target of a * RequestDispatcher.include() */ jspUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); if (jspUri != null) { /* * Requested JSP has been target of * RequestDispatcher.include(). Its path is assembled from the * relevant javax.servlet.include.* request attributes */ String pathInfo = (String) request.getAttribute( RequestDispatcher.INCLUDE_PATH_INFO); if (pathInfo != null) { jspUri += pathInfo; } } else { /* * Requested JSP has not been the target of a * RequestDispatcher.include(). Reconstruct its path from the * request's getServletPath() and getPathInfo() */ jspUri = request.getServletPath(); String pathInfo = request.getPathInfo(); if (pathInfo != null) { jspUri += pathInfo; } } } if (log.isDebugEnabled()) { log.debug("JspEngine --> " + jspUri); log.debug("\t ServletPath: " + request.getServletPath()); log.debug("\t PathInfo: " + request.getPathInfo()); log.debug("\t RealPath: " + context.getRealPath(jspUri)); log.debug("\t RequestURI: " + request.getRequestURI()); log.debug("\t QueryString: " + request.getQueryString()); } try { boolean precompile = preCompile(request); serviceJspFile(request, response, jspUri, precompile); } catch (RuntimeException e) { throw e; } catch (ServletException e) { throw e; } catch (IOException e) { throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException(e); } }
// in java/org/apache/jasper/servlet/JspServlet.java
private void serviceJspFile(HttpServletRequest request, HttpServletResponse response, String jspUri, boolean precompile) throws ServletException, IOException { JspServletWrapper wrapper = rctxt.getWrapper(jspUri); if (wrapper == null) { synchronized(this) { wrapper = rctxt.getWrapper(jspUri); if (wrapper == null) { // Check if the requested JSP page exists, to avoid // creating unnecessary directories and files. if (null == context.getResource(jspUri)) { handleMissingResource(request, response, jspUri); return; } wrapper = new JspServletWrapper(config, options, jspUri, rctxt); rctxt.addWrapper(jspUri,wrapper); } } } try { wrapper.service(request, response, precompile); } catch (FileNotFoundException fnfe) { handleMissingResource(request, response, jspUri); } }
// in java/org/apache/jasper/servlet/JspServlet.java
private void handleMissingResource(HttpServletRequest request, HttpServletResponse response, String jspUri) throws ServletException, IOException { String includeRequestUri = (String)request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored String msg = Localizer.getMessage("jsp.error.file.not.found",jspUri); // Strictly, filtering this is an application // responsibility but just in case... throw new ServletException(SecurityUtil.filter(msg)); } else { try { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); } catch (IllegalStateException ise) { log.error(Localizer.getMessage("jsp.error.file.not.found", jspUri)); } } return; }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(this.mark); out.writeObject(this.target); }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.mark = in.readUTF(); this.target = (MethodExpression) in.readObject(); }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(this.mark); out.writeObject(this.target); }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.mark = in.readUTF(); this.target = (ValueExpression) in.readObject(); }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public static Object[] getEncoding(String fname, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err) throws IOException, JasperException { InputStream inStream = JspUtil.getInputStream(fname, jarFile, ctxt); XMLEncodingDetector detector = new XMLEncodingDetector(); Object[] ret = detector.getEncoding(inStream, err); inStream.close(); return ret; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private Object[] getEncoding(InputStream in, ErrorDispatcher err) throws IOException, JasperException { this.stream = in; this.err=err; createInitialReader(); scanXMLDecl(); return new Object[] { this.encoding, Boolean.valueOf(this.isEncodingSetInProlog), Boolean.valueOf(this.isBomPresent), Integer.valueOf(this.skip) }; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void createInitialReader() throws IOException, JasperException { // wrap this stream in RewindableInputStream stream = new RewindableInputStream(stream); // perform auto-detect of encoding if necessary if (encoding == null) { // read first four bytes and determine encoding final byte[] b4 = new byte[4]; int count = 0; for (; count<4; count++ ) { b4[count] = (byte)stream.read(); } if (count == 4) { Object [] encodingDesc = getEncodingName(b4, count); encoding = (String)(encodingDesc[0]); isBigEndian = (Boolean)(encodingDesc[1]); if (encodingDesc.length > 3) { isBomPresent = ((Boolean)(encodingDesc[2])).booleanValue(); skip = ((Integer)(encodingDesc[3])).intValue(); } else { isBomPresent = true; skip = ((Integer)(encodingDesc[2])).intValue(); } stream.reset(); // Special case UTF-8 files with BOM created by Microsoft // tools. It's more efficient to consume the BOM than make // the reader perform extra checks. -Ac if (count > 2 && encoding.equals("UTF-8")) { int b0 = b4[0] & 0xFF; int b1 = b4[1] & 0xFF; int b2 = b4[2] & 0xFF; if (b0 == 0xEF && b1 == 0xBB && b2 == 0xBF) { // ignore first three bytes... long skipped = stream.skip(3); if (skipped != 3) { throw new IOException(Localizer.getMessage( "xmlParser.skipBomFail")); } } } reader = createReader(stream, encoding, isBigEndian); } else { reader = createReader(stream, encoding, isBigEndian); } } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private Reader createReader(InputStream inputStream, String encoding, Boolean isBigEndian) throws IOException, JasperException { // normalize encoding name if (encoding == null) { encoding = "UTF-8"; } // try to use an optimized reader String ENCODING = encoding.toUpperCase(Locale.ENGLISH); if (ENCODING.equals("UTF-8")) { return new UTF8Reader(inputStream, fBufferSize); } if (ENCODING.equals("US-ASCII")) { return new ASCIIReader(inputStream, fBufferSize); } if (ENCODING.equals("ISO-10646-UCS-4")) { if (isBigEndian != null) { boolean isBE = isBigEndian.booleanValue(); if (isBE) { return new UCSReader(inputStream, UCSReader.UCS4BE); } else { return new UCSReader(inputStream, UCSReader.UCS4LE); } } else { err.jspError("jsp.error.xml.encodingByteOrderUnsupported", encoding); } } if (ENCODING.equals("ISO-10646-UCS-2")) { if (isBigEndian != null) { // sould never happen with this encoding... boolean isBE = isBigEndian.booleanValue(); if (isBE) { return new UCSReader(inputStream, UCSReader.UCS2BE); } else { return new UCSReader(inputStream, UCSReader.UCS2LE); } } else { err.jspError("jsp.error.xml.encodingByteOrderUnsupported", encoding); } } // check for valid name boolean validIANA = XMLChar.isValidIANAEncoding(encoding); boolean validJava = XMLChar.isValidJavaEncoding(encoding); if (!validIANA || (fAllowJavaEncodings && !validJava)) { err.jspError("jsp.error.xml.encodingDeclInvalid", encoding); // NOTE: AndyH suggested that, on failure, we use ISO Latin 1 // because every byte is a valid ISO Latin 1 character. // It may not translate correctly but if we failed on // the encoding anyway, then we're expecting the content // of the document to be bad. This will just prevent an // invalid UTF-8 sequence to be detected. This is only // important when continue-after-fatal-error is turned // on. -Ac encoding = "ISO-8859-1"; } // try to use a Java reader String javaEncoding = EncodingMap.getIANA2JavaMapping(ENCODING); if (javaEncoding == null) { if (fAllowJavaEncodings) { javaEncoding = encoding; } else { err.jspError("jsp.error.xml.encodingDeclInvalid", encoding); // see comment above. javaEncoding = "ISO8859_1"; } } return new InputStreamReader(inputStream, javaEncoding); }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public int peekChar() throws IOException { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } // peek at character int c = fCurrentEntity.ch[fCurrentEntity.position]; // return peeked character if (fCurrentEntity.isExternal()) { return c != '\r' ? c : '\n'; } else { return c; } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public int scanChar() throws IOException { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } // scan character int c = fCurrentEntity.ch[fCurrentEntity.position++]; boolean external = false; if (c == '\n' || (c == '\r' && (external = fCurrentEntity.isExternal()))) { if (fCurrentEntity.position == fCurrentEntity.count) { fCurrentEntity.ch[0] = (char)c; load(1, false); } if (c == '\r' && external) { if (fCurrentEntity.ch[fCurrentEntity.position++] != '\n') { fCurrentEntity.position--; } c = '\n'; } } // return character that was scanned return c; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public String scanName() throws IOException { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } // scan name int offset = fCurrentEntity.position; if (XMLChar.isNameStart(fCurrentEntity.ch[offset])) { if (++fCurrentEntity.position == fCurrentEntity.count) { fCurrentEntity.ch[0] = fCurrentEntity.ch[offset]; offset = 0; if (load(1, false)) { String symbol = fSymbolTable.addSymbol(fCurrentEntity.ch, 0, 1); return symbol; } } while (XMLChar.isName(fCurrentEntity.ch[fCurrentEntity.position])) { if (++fCurrentEntity.position == fCurrentEntity.count) { int length = fCurrentEntity.position - offset; if (length == fBufferSize) { // bad luck we have to resize our buffer char[] tmp = new char[fBufferSize * 2]; System.arraycopy(fCurrentEntity.ch, offset, tmp, 0, length); fCurrentEntity.ch = tmp; fBufferSize *= 2; } else { System.arraycopy(fCurrentEntity.ch, offset, fCurrentEntity.ch, 0, length); } offset = 0; if (load(length, false)) { break; } } } } int length = fCurrentEntity.position - offset; // return name String symbol = null; if (length > 0) { symbol = fSymbolTable.addSymbol(fCurrentEntity.ch, offset, length); } return symbol; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public int scanLiteral(int quote, XMLString content) throws IOException { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } else if (fCurrentEntity.position == fCurrentEntity.count - 1) { fCurrentEntity.ch[0] = fCurrentEntity.ch[fCurrentEntity.count - 1]; load(1, false); fCurrentEntity.position = 0; } // normalize newlines int offset = fCurrentEntity.position; int c = fCurrentEntity.ch[offset]; int newlines = 0; boolean external = fCurrentEntity.isExternal(); if (c == '\n' || (c == '\r' && external)) { do { c = fCurrentEntity.ch[fCurrentEntity.position++]; if (c == '\r' && external) { newlines++; if (fCurrentEntity.position == fCurrentEntity.count) { offset = 0; fCurrentEntity.position = newlines; if (load(newlines, false)) { break; } } if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') { fCurrentEntity.position++; offset++; } /*** NEWLINE NORMALIZATION ***/ else { newlines++; } /***/ } else if (c == '\n') { newlines++; if (fCurrentEntity.position == fCurrentEntity.count) { offset = 0; fCurrentEntity.position = newlines; if (load(newlines, false)) { break; } } /*** NEWLINE NORMALIZATION *** if (fCurrentEntity.ch[fCurrentEntity.position] == '\r' && external) { fCurrentEntity.position++; offset++; } /***/ } else { fCurrentEntity.position--; break; } } while (fCurrentEntity.position < fCurrentEntity.count - 1); for (int i = offset; i < fCurrentEntity.position; i++) { fCurrentEntity.ch[i] = '\n'; } int length = fCurrentEntity.position - offset; if (fCurrentEntity.position == fCurrentEntity.count - 1) { content.setValues(fCurrentEntity.ch, offset, length); return -1; } } // scan literal value while (fCurrentEntity.position < fCurrentEntity.count) { c = fCurrentEntity.ch[fCurrentEntity.position++]; if ((c == quote && (!fCurrentEntity.literal || external)) || c == '%' || !XMLChar.isContent(c)) { fCurrentEntity.position--; break; } } int length = fCurrentEntity.position - offset; content.setValues(fCurrentEntity.ch, offset, length); // return next character if (fCurrentEntity.position != fCurrentEntity.count) { c = fCurrentEntity.ch[fCurrentEntity.position]; // NOTE: We don't want to accidentally signal the // end of the literal if we're expanding an // entity appearing in the literal. -Ac if (c == quote && fCurrentEntity.literal) { c = -1; } } else { c = -1; } return c; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public boolean scanData(String delimiter, XMLStringBuffer buffer) throws IOException { boolean done = false; int delimLen = delimiter.length(); char charAt0 = delimiter.charAt(0); boolean external = fCurrentEntity.isExternal(); do { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } else if (fCurrentEntity.position >= fCurrentEntity.count - delimLen) { System.arraycopy(fCurrentEntity.ch, fCurrentEntity.position, fCurrentEntity.ch, 0, fCurrentEntity.count - fCurrentEntity.position); load(fCurrentEntity.count - fCurrentEntity.position, false); fCurrentEntity.position = 0; } if (fCurrentEntity.position >= fCurrentEntity.count - delimLen) { // something must be wrong with the input: e.g., file ends an // unterminated comment int length = fCurrentEntity.count - fCurrentEntity.position; buffer.append (fCurrentEntity.ch, fCurrentEntity.position, length); fCurrentEntity.position = fCurrentEntity.count; load(0,true); return false; } // normalize newlines int offset = fCurrentEntity.position; int c = fCurrentEntity.ch[offset]; int newlines = 0; if (c == '\n' || (c == '\r' && external)) { do { c = fCurrentEntity.ch[fCurrentEntity.position++]; if (c == '\r' && external) { newlines++; if (fCurrentEntity.position == fCurrentEntity.count) { offset = 0; fCurrentEntity.position = newlines; if (load(newlines, false)) { break; } } if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') { fCurrentEntity.position++; offset++; } /*** NEWLINE NORMALIZATION ***/ else { newlines++; } } else if (c == '\n') { newlines++; if (fCurrentEntity.position == fCurrentEntity.count) { offset = 0; fCurrentEntity.position = newlines; fCurrentEntity.count = newlines; if (load(newlines, false)) { break; } } } else { fCurrentEntity.position--; break; } } while (fCurrentEntity.position < fCurrentEntity.count - 1); for (int i = offset; i < fCurrentEntity.position; i++) { fCurrentEntity.ch[i] = '\n'; } int length = fCurrentEntity.position - offset; if (fCurrentEntity.position == fCurrentEntity.count - 1) { buffer.append(fCurrentEntity.ch, offset, length); return true; } } // iterate over buffer looking for delimiter OUTER: while (fCurrentEntity.position < fCurrentEntity.count) { c = fCurrentEntity.ch[fCurrentEntity.position++]; if (c == charAt0) { // looks like we just hit the delimiter int delimOffset = fCurrentEntity.position - 1; for (int i = 1; i < delimLen; i++) { if (fCurrentEntity.position == fCurrentEntity.count) { fCurrentEntity.position -= i; break OUTER; } c = fCurrentEntity.ch[fCurrentEntity.position++]; if (delimiter.charAt(i) != c) { fCurrentEntity.position--; break; } } if (fCurrentEntity.position == delimOffset + delimLen) { done = true; break; } } else if (c == '\n' || (external && c == '\r')) { fCurrentEntity.position--; break; } else if (XMLChar.isInvalid(c)) { fCurrentEntity.position--; int length = fCurrentEntity.position - offset; buffer.append(fCurrentEntity.ch, offset, length); return true; } } int length = fCurrentEntity.position - offset; if (done) { length -= delimLen; } buffer.append (fCurrentEntity.ch, offset, length); // return true if string was skipped } while (!done); return !done; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public boolean skipChar(int c) throws IOException { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } // skip character int cc = fCurrentEntity.ch[fCurrentEntity.position]; if (cc == c) { fCurrentEntity.position++; return true; } else if (c == '\n' && cc == '\r' && fCurrentEntity.isExternal()) { // handle newlines if (fCurrentEntity.position == fCurrentEntity.count) { fCurrentEntity.ch[0] = (char)cc; load(1, false); } fCurrentEntity.position++; if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') { fCurrentEntity.position++; } return true; } // character was not skipped return false; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public boolean skipSpaces() throws IOException { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } // skip spaces int c = fCurrentEntity.ch[fCurrentEntity.position]; if (XMLChar.isSpace(c)) { boolean external = fCurrentEntity.isExternal(); do { boolean entityChanged = false; // handle newlines if (c == '\n' || (external && c == '\r')) { if (fCurrentEntity.position == fCurrentEntity.count - 1) { fCurrentEntity.ch[0] = (char)c; entityChanged = load(1, true); if (!entityChanged) // the load change the position to be 1, // need to restore it when entity not changed fCurrentEntity.position = 0; } if (c == '\r' && external) { // REVISIT: Does this need to be updated to fix the // #x0D ^#x0A newline normalization problem? -Ac if (fCurrentEntity.ch[++fCurrentEntity.position] != '\n') { fCurrentEntity.position--; } } /*** NEWLINE NORMALIZATION *** else { if (fCurrentEntity.ch[fCurrentEntity.position + 1] == '\r' && external) { fCurrentEntity.position++; } } /***/ } // load more characters, if needed if (!entityChanged) fCurrentEntity.position++; if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } } while (XMLChar.isSpace(c = fCurrentEntity.ch[fCurrentEntity.position])); return true; } // no spaces were found return false; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public boolean skipString(String s) throws IOException { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } // skip string final int length = s.length(); for (int i = 0; i < length; i++) { char c = fCurrentEntity.ch[fCurrentEntity.position++]; if (c != s.charAt(i)) { fCurrentEntity.position -= i + 1; return false; } if (i < length - 1 && fCurrentEntity.position == fCurrentEntity.count) { System.arraycopy(fCurrentEntity.ch, fCurrentEntity.count - i - 1, fCurrentEntity.ch, 0, i + 1); // REVISIT: Can a string to be skipped cross an // entity boundary? -Ac if (load(i + 1, false)) { fCurrentEntity.position -= i + 1; return false; } } } return true; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
final boolean load(int offset, boolean changeEntity) throws IOException { // read characters int length = fCurrentEntity.mayReadChunks? (fCurrentEntity.ch.length - offset): (DEFAULT_XMLDECL_BUFFER_SIZE); int count = fCurrentEntity.reader.read(fCurrentEntity.ch, offset, length); // reset count and position boolean entityChanged = false; if (count != -1) { if (count != 0) { fCurrentEntity.count = count + offset; fCurrentEntity.position = offset; } } // end of this entity else { fCurrentEntity.count = offset; fCurrentEntity.position = offset; entityChanged = true; if (changeEntity) { endEntity(); if (fCurrentEntity == null) { throw new EOFException(); } // handle the trailing edges if (fCurrentEntity.position == fCurrentEntity.count) { load(0, false); } } } return entityChanged; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
Override public int read() throws IOException { int b = 0; if (fOffset < fLength) { return fData[fOffset++] & 0xff; } if (fOffset == fEndOffset) { return -1; } if (fOffset == fData.length) { byte[] newData = new byte[fOffset << 1]; System.arraycopy(fData, 0, newData, 0, fOffset); fData = newData; } b = fInputStream.read(); if (b == -1) { fEndOffset = fOffset; return -1; } fData[fLength++] = (byte)b; fOffset++; return b & 0xff; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
Override public int read(byte[] b, int off, int len) throws IOException { int bytesLeft = fLength - fOffset; if (bytesLeft == 0) { if (fOffset == fEndOffset) { return -1; } // better get some more for the voracious reader... if (fCurrentEntity.mayReadChunks) { return fInputStream.read(b, off, len); } int returnedVal = read(); if (returnedVal == -1) { fEndOffset = fOffset; return -1; } b[off] = (byte)returnedVal; return 1; } if (len < bytesLeft) { if (len <= 0) { return 0; } } else { len = bytesLeft; } if (b != null) { System.arraycopy(fData, fOffset, b, off, len); } fOffset += len; return len; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
Override public long skip(long n) throws IOException { int bytesLeft; if (n <= 0) { return 0; } bytesLeft = fLength - fOffset; if (bytesLeft == 0) { if (fOffset == fEndOffset) { return 0; } return fInputStream.skip(n); } if (n <= bytesLeft) { fOffset += n; return n; } fOffset += bytesLeft; if (fOffset == fEndOffset) { return bytesLeft; } n -= bytesLeft; /* * In a manner of speaking, when this class isn't permitting more * than one byte at a time to be read, it is "blocking". The * available() method should indicate how much can be read without * blocking, so while we're in this mode, it should only indicate * that bytes in its buffer are available; otherwise, the result of * available() on the underlying InputStream is appropriate. */ return fInputStream.skip(n) + bytesLeft; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
Override public int available() throws IOException { int bytesLeft = fLength - fOffset; if (bytesLeft == 0) { if (fOffset == fEndOffset) { return -1; } return fCurrentEntity.mayReadChunks ? fInputStream.available() : 0; } return bytesLeft; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
Override public void close() throws IOException { if (fInputStream != null) { fInputStream.close(); fInputStream = null; } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanXMLDecl() throws IOException, JasperException { if (skipString("<?xml")) { // NOTE: special case where document starts with a PI // whose name starts with "xml" (e.g. "xmlfoo") if (XMLChar.isName(peekChar())) { fStringBuffer.clear(); fStringBuffer.append("xml"); while (XMLChar.isName(peekChar())) { fStringBuffer.append((char)scanChar()); } String target = fSymbolTable.addSymbol(fStringBuffer.ch, fStringBuffer.offset, fStringBuffer.length); scanPIData(target, fString); } // standard XML declaration else { scanXMLDeclOrTextDecl(false); } } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanXMLDeclOrTextDecl(boolean scanningTextDecl) throws IOException, JasperException { // scan decl scanXMLDeclOrTextDecl(scanningTextDecl, fStrings); // pseudo-attribute values String encodingPseudoAttr = fStrings[1]; // set encoding on reader if (encodingPseudoAttr != null) { isEncodingSetInProlog = true; encoding = encodingPseudoAttr; } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanXMLDeclOrTextDecl(boolean scanningTextDecl, String[] pseudoAttributeValues) throws IOException, JasperException { // pseudo-attribute values String version = null; String encoding = null; String standalone = null; // scan pseudo-attributes final int STATE_VERSION = 0; final int STATE_ENCODING = 1; final int STATE_STANDALONE = 2; final int STATE_DONE = 3; int state = STATE_VERSION; boolean dataFoundForTarget = false; boolean sawSpace = skipSpaces(); while (peekChar() != '?') { dataFoundForTarget = true; String name = scanPseudoAttribute(scanningTextDecl, fString); switch (state) { case STATE_VERSION: { if (name == fVersionSymbol) { if (!sawSpace) { reportFatalError(scanningTextDecl ? "jsp.error.xml.spaceRequiredBeforeVersionInTextDecl" : "jsp.error.xml.spaceRequiredBeforeVersionInXMLDecl", null); } version = fString.toString(); state = STATE_ENCODING; if (!version.equals("1.0")) { // REVISIT: XML REC says we should throw an error // in such cases. // some may object the throwing of fatalError. err.jspError("jsp.error.xml.versionNotSupported", version); } } else if (name == fEncodingSymbol) { if (!scanningTextDecl) { err.jspError("jsp.error.xml.versionInfoRequired"); } if (!sawSpace) { reportFatalError(scanningTextDecl ? "jsp.error.xml.spaceRequiredBeforeEncodingInTextDecl" : "jsp.error.xml.spaceRequiredBeforeEncodingInXMLDecl", null); } encoding = fString.toString(); state = scanningTextDecl ? STATE_DONE : STATE_STANDALONE; } else { if (scanningTextDecl) { err.jspError("jsp.error.xml.encodingDeclRequired"); } else { err.jspError("jsp.error.xml.versionInfoRequired"); } } break; } case STATE_ENCODING: { if (name == fEncodingSymbol) { if (!sawSpace) { reportFatalError(scanningTextDecl ? "jsp.error.xml.spaceRequiredBeforeEncodingInTextDecl" : "jsp.error.xml.spaceRequiredBeforeEncodingInXMLDecl", null); } encoding = fString.toString(); state = scanningTextDecl ? STATE_DONE : STATE_STANDALONE; // TODO: check encoding name; set encoding on // entity scanner } else if (!scanningTextDecl && name == fStandaloneSymbol) { if (!sawSpace) { err.jspError("jsp.error.xml.spaceRequiredBeforeStandalone"); } standalone = fString.toString(); state = STATE_DONE; if (!standalone.equals("yes") && !standalone.equals("no")) { err.jspError("jsp.error.xml.sdDeclInvalid"); } } else { err.jspError("jsp.error.xml.encodingDeclRequired"); } break; } case STATE_STANDALONE: { if (name == fStandaloneSymbol) { if (!sawSpace) { err.jspError("jsp.error.xml.spaceRequiredBeforeStandalone"); } standalone = fString.toString(); state = STATE_DONE; if (!standalone.equals("yes") && !standalone.equals("no")) { err.jspError("jsp.error.xml.sdDeclInvalid"); } } else { err.jspError("jsp.error.xml.encodingDeclRequired"); } break; } default: { err.jspError("jsp.error.xml.noMorePseudoAttributes"); } } sawSpace = skipSpaces(); } // REVISIT: should we remove this error reporting? if (scanningTextDecl && state != STATE_DONE) { err.jspError("jsp.error.xml.morePseudoAttributes"); } // If there is no data in the xml or text decl then we fail to report // error for version or encoding info above. if (scanningTextDecl) { if (!dataFoundForTarget && encoding == null) { err.jspError("jsp.error.xml.encodingDeclRequired"); } } else { if (!dataFoundForTarget && version == null) { err.jspError("jsp.error.xml.versionInfoRequired"); } } // end if (!skipChar('?')) { err.jspError("jsp.error.xml.xmlDeclUnterminated"); } if (!skipChar('>')) { err.jspError("jsp.error.xml.xmlDeclUnterminated"); } // fill in return array pseudoAttributeValues[0] = version; pseudoAttributeValues[1] = encoding; pseudoAttributeValues[2] = standalone; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public String scanPseudoAttribute(boolean scanningTextDecl, XMLString value) throws IOException, JasperException { String name = scanName(); if (name == null) { err.jspError("jsp.error.xml.pseudoAttrNameExpected"); } skipSpaces(); if (!skipChar('=')) { reportFatalError(scanningTextDecl ? "jsp.error.xml.eqRequiredInTextDecl" : "jsp.error.xml.eqRequiredInXMLDecl", name); } skipSpaces(); int quote = peekChar(); if (quote != '\'' && quote != '"') { reportFatalError(scanningTextDecl ? "jsp.error.xml.quoteRequiredInTextDecl" : "jsp.error.xml.quoteRequiredInXMLDecl" , name); } scanChar(); int c = scanLiteral(quote, value); if (c != quote) { fStringBuffer2.clear(); do { fStringBuffer2.append(value); if (c != -1) { if (c == '&' || c == '%' || c == '<' || c == ']') { fStringBuffer2.append((char)scanChar()); } else if (XMLChar.isHighSurrogate(c)) { scanSurrogates(fStringBuffer2); } else if (XMLChar.isInvalid(c)) { String key = scanningTextDecl ? "jsp.error.xml.invalidCharInTextDecl" : "jsp.error.xml.invalidCharInXMLDecl"; reportFatalError(key, Integer.toString(c, 16)); scanChar(); } } c = scanLiteral(quote, value); } while (c != quote); fStringBuffer2.append(value); value.setValues(fStringBuffer2); } if (!skipChar(quote)) { reportFatalError(scanningTextDecl ? "jsp.error.xml.closeQuoteMissingInTextDecl" : "jsp.error.xml.closeQuoteMissingInXMLDecl", name); } // return return name; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanPIData(String target, XMLString data) throws IOException, JasperException { // check target if (target.length() == 3) { char c0 = Character.toLowerCase(target.charAt(0)); char c1 = Character.toLowerCase(target.charAt(1)); char c2 = Character.toLowerCase(target.charAt(2)); if (c0 == 'x' && c1 == 'm' && c2 == 'l') { err.jspError("jsp.error.xml.reservedPITarget"); } } // spaces if (!skipSpaces()) { if (skipString("?>")) { // we found the end, there is no data data.clear(); return; } else { // if there is data there should be some space err.jspError("jsp.error.xml.spaceRequiredInPI"); } } fStringBuffer.clear(); // data if (scanData("?>", fStringBuffer)) { do { int c = peekChar(); if (c != -1) { if (XMLChar.isHighSurrogate(c)) { scanSurrogates(fStringBuffer); } else if (XMLChar.isInvalid(c)) { err.jspError("jsp.error.xml.invalidCharInPI", Integer.toHexString(c)); scanChar(); } } } while (scanData("?>", fStringBuffer)); } data.setValues(fStringBuffer); }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private boolean scanSurrogates(XMLStringBuffer buf) throws IOException, JasperException { int high = scanChar(); int low = peekChar(); if (!XMLChar.isLowSurrogate(low)) { err.jspError("jsp.error.xml.invalidCharInContent", Integer.toString(high, 16)); return false; } scanChar(); // convert surrogates to supplemental character int c = XMLChar.supplemental((char)high, (char)low); // supplemental character must be a valid XML character if (!XMLChar.isValid(c)) { err.jspError("jsp.error.xml.invalidCharInContent", Integer.toString(c, 16)); return false; } // fill in the buffer buf.append((char)high); buf.append((char)low); return true; }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public int read() throws IOException { // decode character int c = fSurrogate; if (fSurrogate == -1) { // NOTE: We use the index into the buffer if there are remaining // bytes from the last block read. -Ac int index = 0; // get first byte int b0 = index == fOffset ? fInputStream.read() : fBuffer[index++] & 0x00FF; if (b0 == -1) { return -1; } // UTF-8: [0xxx xxxx] // Unicode: [0000 0000] [0xxx xxxx] if (b0 < 0x80) { c = (char)b0; } // UTF-8: [110y yyyy] [10xx xxxx] // Unicode: [0000 0yyy] [yyxx xxxx] else if ((b0 & 0xE0) == 0xC0) { int b1 = index == fOffset ? fInputStream.read() : fBuffer[index++] & 0x00FF; if (b1 == -1) { expectedByte(2, 2); } if ((b1 & 0xC0) != 0x80) { invalidByte(2, 2); } c = ((b0 << 6) & 0x07C0) | (b1 & 0x003F); } // UTF-8: [1110 zzzz] [10yy yyyy] [10xx xxxx] // Unicode: [zzzz yyyy] [yyxx xxxx] else if ((b0 & 0xF0) == 0xE0) { int b1 = index == fOffset ? fInputStream.read() : fBuffer[index++] & 0x00FF; if (b1 == -1) { expectedByte(2, 3); } if ((b1 & 0xC0) != 0x80) { invalidByte(2, 3); } int b2 = index == fOffset ? fInputStream.read() : fBuffer[index++] & 0x00FF; if (b2 == -1) { expectedByte(3, 3); } if ((b2 & 0xC0) != 0x80) { invalidByte(3, 3); } c = ((b0 << 12) & 0xF000) | ((b1 << 6) & 0x0FC0) | (b2 & 0x003F); } // UTF-8: [1111 0uuu] [10uu zzzz] [10yy yyyy] [10xx xxxx]* // Unicode: [1101 10ww] [wwzz zzyy] (high surrogate) // [1101 11yy] [yyxx xxxx] (low surrogate) // * uuuuu = wwww + 1 else if ((b0 & 0xF8) == 0xF0) { int b1 = index == fOffset ? fInputStream.read() : fBuffer[index++] & 0x00FF; if (b1 == -1) { expectedByte(2, 4); } if ((b1 & 0xC0) != 0x80) { invalidByte(2, 3); } int b2 = index == fOffset ? fInputStream.read() : fBuffer[index++] & 0x00FF; if (b2 == -1) { expectedByte(3, 4); } if ((b2 & 0xC0) != 0x80) { invalidByte(3, 3); } int b3 = index == fOffset ? fInputStream.read() : fBuffer[index++] & 0x00FF; if (b3 == -1) { expectedByte(4, 4); } if ((b3 & 0xC0) != 0x80) { invalidByte(4, 4); } int uuuuu = ((b0 << 2) & 0x001C) | ((b1 >> 4) & 0x0003); if (uuuuu > 0x10) { invalidSurrogate(uuuuu); } int wwww = uuuuu - 1; int hs = 0xD800 | ((wwww << 6) & 0x03C0) | ((b1 << 2) & 0x003C) | ((b2 >> 4) & 0x0003); int ls = 0xDC00 | ((b2 << 6) & 0x03C0) | (b3 & 0x003F); c = hs; fSurrogate = ls; } // error else { invalidByte(1, 1); } } // use surrogate else { fSurrogate = -1; } // return character if (DEBUG_READ) { if (log.isDebugEnabled()) log.debug("read(): 0x"+Integer.toHexString(c)); } return c; }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public int read(char ch[], int offset, int length) throws IOException { // handle surrogate int out = offset; if (fSurrogate != -1) { ch[offset + 1] = (char)fSurrogate; fSurrogate = -1; length--; out++; } // read bytes int count = 0; if (fOffset == 0) { // adjust length to read if (length > fBuffer.length) { length = fBuffer.length; } // perform read operation count = fInputStream.read(fBuffer, 0, length); if (count == -1) { return -1; } count += out - offset; } // skip read; last character was in error // NOTE: Having an offset value other than zero means that there was // an error in the last character read. In this case, we have // skipped the read so we don't consume any bytes past the // error. By signaling the error on the next block read we // allow the method to return the most valid characters that // it can on the previous block read. -Ac else { count = fOffset; fOffset = 0; } // convert bytes to characters final int total = count; for (int in = 0; in < total; in++) { int b0 = fBuffer[in] & 0x00FF; // UTF-8: [0xxx xxxx] // Unicode: [0000 0000] [0xxx xxxx] if (b0 < 0x80) { ch[out++] = (char)b0; continue; } // UTF-8: [110y yyyy] [10xx xxxx] // Unicode: [0000 0yyy] [yyxx xxxx] if ((b0 & 0xE0) == 0xC0) { int b1 = -1; if (++in < total) { b1 = fBuffer[in] & 0x00FF; } else { b1 = fInputStream.read(); if (b1 == -1) { if (out > offset) { fBuffer[0] = (byte)b0; fOffset = 1; return out - offset; } expectedByte(2, 2); } count++; } if ((b1 & 0xC0) != 0x80) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fOffset = 2; return out - offset; } invalidByte(2, 2); } int c = ((b0 << 6) & 0x07C0) | (b1 & 0x003F); ch[out++] = (char)c; count -= 1; continue; } // UTF-8: [1110 zzzz] [10yy yyyy] [10xx xxxx] // Unicode: [zzzz yyyy] [yyxx xxxx] if ((b0 & 0xF0) == 0xE0) { int b1 = -1; if (++in < total) { b1 = fBuffer[in] & 0x00FF; } else { b1 = fInputStream.read(); if (b1 == -1) { if (out > offset) { fBuffer[0] = (byte)b0; fOffset = 1; return out - offset; } expectedByte(2, 3); } count++; } if ((b1 & 0xC0) != 0x80) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fOffset = 2; return out - offset; } invalidByte(2, 3); } int b2 = -1; if (++in < total) { b2 = fBuffer[in] & 0x00FF; } else { b2 = fInputStream.read(); if (b2 == -1) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fOffset = 2; return out - offset; } expectedByte(3, 3); } count++; } if ((b2 & 0xC0) != 0x80) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fBuffer[2] = (byte)b2; fOffset = 3; return out - offset; } invalidByte(3, 3); } int c = ((b0 << 12) & 0xF000) | ((b1 << 6) & 0x0FC0) | (b2 & 0x003F); ch[out++] = (char)c; count -= 2; continue; } // UTF-8: [1111 0uuu] [10uu zzzz] [10yy yyyy] [10xx xxxx]* // Unicode: [1101 10ww] [wwzz zzyy] (high surrogate) // [1101 11yy] [yyxx xxxx] (low surrogate) // * uuuuu = wwww + 1 if ((b0 & 0xF8) == 0xF0) { int b1 = -1; if (++in < total) { b1 = fBuffer[in] & 0x00FF; } else { b1 = fInputStream.read(); if (b1 == -1) { if (out > offset) { fBuffer[0] = (byte)b0; fOffset = 1; return out - offset; } expectedByte(2, 4); } count++; } if ((b1 & 0xC0) != 0x80) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fOffset = 2; return out - offset; } invalidByte(2, 4); } int b2 = -1; if (++in < total) { b2 = fBuffer[in] & 0x00FF; } else { b2 = fInputStream.read(); if (b2 == -1) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fOffset = 2; return out - offset; } expectedByte(3, 4); } count++; } if ((b2 & 0xC0) != 0x80) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fBuffer[2] = (byte)b2; fOffset = 3; return out - offset; } invalidByte(3, 4); } int b3 = -1; if (++in < total) { b3 = fBuffer[in] & 0x00FF; } else { b3 = fInputStream.read(); if (b3 == -1) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fBuffer[2] = (byte)b2; fOffset = 3; return out - offset; } expectedByte(4, 4); } count++; } if ((b3 & 0xC0) != 0x80) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fBuffer[2] = (byte)b2; fBuffer[3] = (byte)b3; fOffset = 4; return out - offset; } invalidByte(4, 4); } // decode bytes into surrogate characters int uuuuu = ((b0 << 2) & 0x001C) | ((b1 >> 4) & 0x0003); if (uuuuu > 0x10) { invalidSurrogate(uuuuu); } int wwww = uuuuu - 1; int zzzz = b1 & 0x000F; int yyyyyy = b2 & 0x003F; int xxxxxx = b3 & 0x003F; int hs = 0xD800 | ((wwww << 6) & 0x03C0) | (zzzz << 2) | (yyyyyy >> 4); int ls = 0xDC00 | ((yyyyyy << 6) & 0x03C0) | xxxxxx; // set characters ch[out++] = (char)hs; ch[out++] = (char)ls; count -= 2; continue; } // error if (out > offset) { fBuffer[0] = (byte)b0; fOffset = 1; return out - offset; } invalidByte(1, 1); } // return number of characters converted if (DEBUG_READ) { if (log.isDebugEnabled()) log.debug("read(char[],"+offset+','+length+"): count="+count); } return count; }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public long skip(long n) throws IOException { long remaining = n; final char[] ch = new char[fBuffer.length]; do { int length = ch.length < remaining ? ch.length : (int)remaining; int count = read(ch, 0, length); if (count > 0) { remaining -= count; } else { break; } } while (remaining > 0); long skipped = n - remaining; return skipped; }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public boolean ready() throws IOException { return false; }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public void mark(int readAheadLimit) throws IOException { throw new IOException( Localizer.getMessage("jsp.error.xml.operationNotSupported", "mark()", "UTF-8")); }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public void reset() throws IOException { fOffset = 0; fSurrogate = -1; }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public void close() throws IOException { fInputStream.close(); }
// in java/org/apache/jasper/xmlparser/UCSReader.java
Override public int read() throws IOException { int b0 = fInputStream.read() & 0xff; if (b0 == 0xff) return -1; int b1 = fInputStream.read() & 0xff; if (b1 == 0xff) return -1; if(fEncoding >=4) { int b2 = fInputStream.read() & 0xff; if (b2 == 0xff) return -1; int b3 = fInputStream.read() & 0xff; if (b3 == 0xff) return -1; if (log.isDebugEnabled()) log.debug("b0 is " + (b0 & 0xff) + " b1 " + (b1 & 0xff) + " b2 " + (b2 & 0xff) + " b3 " + (b3 & 0xff)); if (fEncoding == UCS4BE) return (b0<<24)+(b1<<16)+(b2<<8)+b3; else return (b3<<24)+(b2<<16)+(b1<<8)+b0; } else { // UCS-2 if (fEncoding == UCS2BE) return (b0<<8)+b1; else return (b1<<8)+b0; } }
// in java/org/apache/jasper/xmlparser/UCSReader.java
Override public int read(char ch[], int offset, int length) throws IOException { int byteLength = length << ((fEncoding >= 4)?2:1); if (byteLength > fBuffer.length) { byteLength = fBuffer.length; } int count = fInputStream.read(fBuffer, 0, byteLength); if(count == -1) return -1; // try and make count be a multiple of the number of bytes we're looking for if(fEncoding >= 4) { // BigEndian // this looks ugly, but it avoids an if at any rate... int numToRead = (4 - (count & 3) & 3); for(int i=0; i<numToRead; i++) { int charRead = fInputStream.read(); if(charRead == -1) { // end of input; something likely went wrong!A Pad buffer with nulls. for (int j = i;j<numToRead; j++) fBuffer[count+j] = 0; break; } else { fBuffer[count+i] = (byte)charRead; } } count += numToRead; } else { int numToRead = count & 1; if(numToRead != 0) { count++; int charRead = fInputStream.read(); if(charRead == -1) { // end of input; something likely went wrong!A Pad buffer with nulls. fBuffer[count] = 0; } else { fBuffer[count] = (byte)charRead; } } } // now count is a multiple of the right number of bytes int numChars = count >> ((fEncoding >= 4)?2:1); int curPos = 0; for (int i = 0; i < numChars; i++) { int b0 = fBuffer[curPos++] & 0xff; int b1 = fBuffer[curPos++] & 0xff; if(fEncoding >=4) { int b2 = fBuffer[curPos++] & 0xff; int b3 = fBuffer[curPos++] & 0xff; if (fEncoding == UCS4BE) ch[offset+i] = (char)((b0<<24)+(b1<<16)+(b2<<8)+b3); else ch[offset+i] = (char)((b3<<24)+(b2<<16)+(b1<<8)+b0); } else { // UCS-2 if (fEncoding == UCS2BE) ch[offset+i] = (char)((b0<<8)+b1); else ch[offset+i] = (char)((b1<<8)+b0); } } return numChars; }
// in java/org/apache/jasper/xmlparser/UCSReader.java
Override public long skip(long n) throws IOException { // charWidth will represent the number of bits to move // n leftward to get num of bytes to skip, and then move the result rightward // to get num of chars effectively skipped. // The trick with &'ing, as with elsewhere in this dcode, is // intended to avoid an expensive use of / that might not be optimized // away. int charWidth = (fEncoding >=4)?2:1; long bytesSkipped = fInputStream.skip(n<<charWidth); if((bytesSkipped & (charWidth | 1)) == 0) return bytesSkipped >> charWidth; return (bytesSkipped >> charWidth) + 1; }
// in java/org/apache/jasper/xmlparser/UCSReader.java
Override public boolean ready() throws IOException { return false; }
// in java/org/apache/jasper/xmlparser/UCSReader.java
Override public void mark(int readAheadLimit) throws IOException { fInputStream.mark(readAheadLimit); }
// in java/org/apache/jasper/xmlparser/UCSReader.java
Override public void reset() throws IOException { fInputStream.reset(); }
// in java/org/apache/jasper/xmlparser/UCSReader.java
Override public void close() throws IOException { fInputStream.close(); }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public int read() throws IOException { int b0 = fInputStream.read(); if (b0 > 0x80) { throw new IOException(Localizer.getMessage("jsp.error.xml.invalidASCII", Integer.toString(b0))); } return b0; }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public int read(char ch[], int offset, int length) throws IOException { if (length > fBuffer.length) { length = fBuffer.length; } int count = fInputStream.read(fBuffer, 0, length); for (int i = 0; i < count; i++) { int b0 = (0xff & fBuffer[i]); // Convert to unsigned if (b0 > 0x80) { throw new IOException(Localizer.getMessage("jsp.error.xml.invalidASCII", Integer.toString(b0))); } ch[offset + i] = (char)b0; } return count; }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public long skip(long n) throws IOException { return fInputStream.skip(n); }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public boolean ready() throws IOException { return false; }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public void mark(int readAheadLimit) throws IOException { fInputStream.mark(readAheadLimit); }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public void reset() throws IOException { fInputStream.reset(); }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public void close() throws IOException { fInputStream.close(); }
// in java/org/apache/jasper/JspC.java
public void generateWebMapping( String file, JspCompilationContext clctxt ) throws IOException { if (log.isDebugEnabled()) { log.debug("Generating web mapping for file " + file + " using compilation context " + clctxt); } String className = clctxt.getServletClassName(); String packageName = clctxt.getServletPackageName(); String thisServletName; if ("".equals(packageName)) { thisServletName = className; } else { thisServletName = packageName + '.' + className; } if (servletout != null) { servletout.write("\n <servlet>\n <servlet-name>"); servletout.write(thisServletName); servletout.write("</servlet-name>\n <servlet-class>"); servletout.write(thisServletName); servletout.write("</servlet-class>\n </servlet>\n"); } if (mappingout != null) { mappingout.write("\n <servlet-mapping>\n <servlet-name>"); mappingout.write(thisServletName); mappingout.write("</servlet-name>\n <url-pattern>"); mappingout.write(file.replace('\\', '/')); mappingout.write("</url-pattern>\n </servlet-mapping>\n"); } }
// in java/org/apache/jasper/JspC.java
protected void mergeIntoWebXml() throws IOException { File webappBase = new File(uriRoot); File webXml = new File(webappBase, "WEB-INF/web.xml"); File webXml2 = new File(webappBase, "WEB-INF/web2.xml"); String insertStartMarker = Localizer.getMessage("jspc.webinc.insertStart"); String insertEndMarker = Localizer.getMessage("jspc.webinc.insertEnd"); BufferedReader reader = new BufferedReader(openWebxmlReader(webXml)); BufferedReader fragmentReader = new BufferedReader( openWebxmlReader(new File(webxmlFile))); PrintWriter writer = new PrintWriter(openWebxmlWriter(webXml2)); // Insert the <servlet> and <servlet-mapping> declarations boolean inserted = false; int current = reader.read(); while (current > -1) { if (current == '<') { String element = getElement(reader); if (!inserted && insertBefore.contains(element)) { // Insert generated content here writer.println(insertStartMarker); while (true) { String line = fragmentReader.readLine(); if (line == null) { writer.println(); break; } writer.println(line); } writer.println(insertEndMarker); writer.println(); writer.write(element); inserted = true; } else if (element.equals(insertStartMarker)) { // Skip the previous auto-generated content while (true) { current = reader.read(); if (current < 0) { throw new EOFException(); } if (current == '<') { element = getElement(reader); if (element.equals(insertEndMarker)) { break; } } } current = reader.read(); while (current == '\n' || current == '\r') { current = reader.read(); } continue; } else { writer.write(element); } } else { writer.write(current); } current = reader.read(); } writer.close(); reader.close(); fragmentReader.close(); FileInputStream fis = new FileInputStream(webXml2); FileOutputStream fos = new FileOutputStream(webXml); byte buf[] = new byte[512]; while (true) { int n = fis.read(buf); if (n < 0) { break; } fos.write(buf, 0, n); } fis.close(); fos.close(); if(!webXml2.delete() && log.isDebugEnabled()) log.debug(Localizer.getMessage("jspc.delete.fail", webXml2.toString())); if (!(new File(webxmlFile)).delete() && log.isDebugEnabled()) log.debug(Localizer.getMessage("jspc.delete.fail", webxmlFile)); }
// in java/org/apache/jasper/JspC.java
private String getElement(Reader reader) throws IOException { StringBuilder result = new StringBuilder(); result.append('<'); boolean done = false; while (!done) { int current = reader.read(); while (current != '>') { if (current < 0) { throw new EOFException(); } result.append((char) current); current = reader.read(); } result.append((char) current); int len = result.length(); if (len > 4 && result.substring(0, 4).equals("<!--")) { // This is a comment - make sure we are at the end if (len >= 7 && result.substring(len - 3, len).equals("-->")) { done = true; } } else { done = true; } } return result.toString(); }
// in java/org/apache/jasper/JspC.java
protected void initClassLoader(JspCompilationContext clctxt) throws IOException { classPath = getClassPath(); ClassLoader jspcLoader = getClass().getClassLoader(); if (jspcLoader instanceof AntClassLoader) { classPath += File.pathSeparator + ((AntClassLoader) jspcLoader).getClasspath(); } // Turn the classPath into URLs ArrayList<URL> urls = new ArrayList<URL>(); StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { String path = tokenizer.nextToken(); try { File libFile = new File(path); urls.add(libFile.toURI().toURL()); } catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); } } File webappBase = new File(uriRoot); if (webappBase.exists()) { File classes = new File(webappBase, "/WEB-INF/classes"); try { if (classes.exists()) { classPath = classPath + File.pathSeparator + classes.getCanonicalPath(); urls.add(classes.getCanonicalFile().toURI().toURL()); } } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } File lib = new File(webappBase, "/WEB-INF/lib"); if (lib.exists() && lib.isDirectory()) { String[] libs = lib.list(); for (int i = 0; i < libs.length; i++) { if( libs[i].length() <5 ) continue; String ext=libs[i].substring( libs[i].length() - 4 ); if (! ".jar".equalsIgnoreCase(ext)) { if (".tld".equalsIgnoreCase(ext)) { log.warn("TLD files should not be placed in " + "/WEB-INF/lib"); } continue; } try { File libFile = new File(lib, libs[i]); classPath = classPath + File.pathSeparator + libFile.getAbsolutePath(); urls.add(libFile.getAbsoluteFile().toURI().toURL()); } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } } } } // What is this ?? urls.add(new File( clctxt.getRealPath("/")).getCanonicalFile().toURI().toURL()); URL urlsA[]=new URL[urls.size()]; urls.toArray(urlsA); loader = new URLClassLoader(urlsA, this.getClass().getClassLoader()); }
// in java/org/apache/jasper/JspC.java
private Reader openWebxmlReader(File file) throws IOException { FileInputStream fis = new FileInputStream(file); try { return webxmlEncoding != null ? new InputStreamReader(fis, webxmlEncoding) : new InputStreamReader(fis); } catch (IOException ex) { fis.close(); throw ex; } }
// in java/org/apache/jasper/JspC.java
private Writer openWebxmlWriter(File file) throws IOException { FileOutputStream fos = new FileOutputStream(file); try { return webxmlEncoding != null ? new OutputStreamWriter(fos, webxmlEncoding) : new OutputStreamWriter(fos); } catch (IOException ex) { fos.close(); throw ex; } }
// in java/org/apache/naming/resources/WARDirContext.java
Override public InputStream streamContent() throws IOException { try { if (binaryContent == null) { InputStream is = base.getInputStream(entry); inputStream = is; return is; } } catch (ZipException e) { throw new IOException(e.getMessage(), e); } return super.streamContent(); }
// in java/org/apache/naming/resources/DirContextURLConnection.java
Override public void connect() throws IOException { if (!connected) { try { date = System.currentTimeMillis(); String path = getURL().getFile(); if (context instanceof ProxyDirContext) { ProxyDirContext proxyDirContext = (ProxyDirContext) context; String hostName = proxyDirContext.getHostName(); String contextPath = proxyDirContext.getContextPath(); if (hostName != null) { if (!path.startsWith("/" + hostName + "/")) return; path = path.substring(hostName.length()+ 1); } if (contextPath != null) { if (!path.startsWith(contextPath + "/")) { return; } path = path.substring(contextPath.length()); } } path = URLDecoder.decode(path, "UTF-8"); object = context.lookup(path); attributes = context.getAttributes(path); if (object instanceof Resource) resource = (Resource) object; if (object instanceof DirContext) collection = (DirContext) object; } catch (NamingException e) { // Object not found } connected = true; } }
// in java/org/apache/naming/resources/DirContextURLConnection.java
Override public Object getContent() throws IOException { if (!connected) connect(); if (resource != null) return getInputStream(); if (collection != null) return collection; if (object != null) return object; throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); }
// in java/org/apache/naming/resources/DirContextURLConnection.java
Override public InputStream getInputStream() throws IOException { if (!connected) connect(); if (resource == null) { throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); } // Reopen resource try { resource = (Resource) context.lookup( URLDecoder.decode(getURL().getFile(), "UTF-8")); } catch (NamingException e) { // Ignore } return (resource.streamContent()); }
// in java/org/apache/naming/resources/DirContextURLConnection.java
public Enumeration<String> list() throws IOException { if (!connected) { connect(); } if ((resource == null) && (collection == null)) { throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); } Vector<String> result = new Vector<String>(); if (collection != null) { try { String file = getURL().getFile(); // This will be of the form /<hostname>/<contextpath>/file name // if <contextpath> is not empty otherwise this will be of the // form /<hostname>/file name // Strip off the hostname and the contextpath (note that context // path may contain '/' int start; if (context instanceof ProxyDirContext) { String cp = ((ProxyDirContext)context).getContextPath(); String h = ((ProxyDirContext)context).getHostName(); if ("".equals(cp)) { start = h.length() + 2; } else { start = h.length() + cp.length() + 2; } } else { start = file.indexOf('/', file.indexOf('/', 1) + 1); } NamingEnumeration<NameClassPair> enumeration = context.list(file.substring(start)); while (enumeration.hasMoreElements()) { NameClassPair ncp = enumeration.nextElement(); result.addElement( URLEncoder.encode(ncp.getName(), "UTF-8")); } } catch (NamingException e) { // Unexpected exception throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); } } return result.elements(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public InputStream streamContent() throws IOException { if (binaryContent == null) { FileInputStream fis = new FileInputStream(file); inputStream = fis; return fis; } return super.streamContent(); }
// in java/org/apache/naming/resources/Resource.java
public InputStream streamContent() throws IOException { if (binaryContent != null) { return new ByteArrayInputStream(binaryContent); } return inputStream; }
// in java/org/apache/naming/resources/DirContextURLStreamHandler.java
Override protected URLConnection openConnection(URL u) throws IOException { DirContext currentContext = this.context; if (currentContext == null) currentContext = get(); return new DirContextURLConnection(currentContext, u); }
// in java/org/apache/juli/ClassLoaderLogManager.java
Override public void readConfiguration() throws IOException, SecurityException { checkAccess(); readConfiguration(Thread.currentThread().getContextClassLoader()); }
// in java/org/apache/juli/ClassLoaderLogManager.java
Override public void readConfiguration(InputStream is) throws IOException, SecurityException { checkAccess(); reset(); readConfiguration(is, Thread.currentThread().getContextClassLoader()); }
// in java/org/apache/juli/ClassLoaderLogManager.java
protected void readConfiguration(ClassLoader classLoader) throws IOException { InputStream is = null; // Special case for URL classloaders which are used in containers: // only look in the local repositories to avoid redefining loggers 20 times try { if ((classLoader instanceof URLClassLoader) && (((URLClassLoader) classLoader).findResource("logging.properties") != null)) { is = classLoader.getResourceAsStream("logging.properties"); } } catch (AccessControlException ace) { // No permission to configure logging in context // Log and carry on ClassLoaderLogInfo info = classLoaderLoggers.get(ClassLoader.getSystemClassLoader()); if (info != null) { Logger log = info.loggers.get(""); if (log != null) { Permission perm = ace.getPermission(); if (perm instanceof FilePermission && perm.getActions().equals("read")) { log.warning("Reading " + perm.getName() + " is not permitted. See \"per context logging\" in the default catalina.policy file."); } else { log.warning("Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file."); log.warning("Original error was: " + ace.getMessage()); } } } } if ((is == null) && (classLoader == ClassLoader.getSystemClassLoader())) { String configFileStr = System.getProperty("java.util.logging.config.file"); if (configFileStr != null) { try { is = new FileInputStream(replace(configFileStr)); } catch (IOException e) { // Ignore } } // Try the default JVM configuration if (is == null) { File defaultFile = new File(new File(System.getProperty("java.home"), "lib"), "logging.properties"); try { is = new FileInputStream(defaultFile); } catch (IOException e) { // Critical problem, do something ... } } } Logger localRootLogger = new RootLogger(); if (is == null) { // Retrieve the root logger of the parent classloader instead ClassLoader current = classLoader.getParent(); ClassLoaderLogInfo info = null; while (current != null && info == null) { info = getClassLoaderInfo(current); current = current.getParent(); } if (info != null) { localRootLogger.setParent(info.rootNode.logger); } } ClassLoaderLogInfo info = new ClassLoaderLogInfo(new LogNode(null, localRootLogger)); classLoaderLoggers.put(classLoader, info); if (is != null) { readConfiguration(is, classLoader); } addLogger(localRootLogger); }
// in java/org/apache/juli/ClassLoaderLogManager.java
protected void readConfiguration(InputStream is, ClassLoader classLoader) throws IOException { ClassLoaderLogInfo info = classLoaderLoggers.get(classLoader); try { info.props.load(is); } catch (IOException e) { // Report error System.err.println("Configuration error"); e.printStackTrace(); } finally { try { is.close(); } catch (IOException ioe) { // Ignore } } // Create handlers for the root logger of this classloader String rootHandlers = info.props.getProperty(".handlers"); String handlers = info.props.getProperty("handlers"); Logger localRootLogger = info.rootNode.logger; if (handlers != null) { StringTokenizer tok = new StringTokenizer(handlers, ","); while (tok.hasMoreTokens()) { String handlerName = (tok.nextToken().trim()); String handlerClassName = handlerName; String prefix = ""; if (handlerClassName.length() <= 0) { continue; } // Parse and remove a prefix (prefix start with a digit, such as // "10WebappFooHanlder.") if (Character.isDigit(handlerClassName.charAt(0))) { int pos = handlerClassName.indexOf('.'); if (pos >= 0) { prefix = handlerClassName.substring(0, pos + 1); handlerClassName = handlerClassName.substring(pos + 1); } } try { this.prefix.set(prefix); Handler handler = (Handler) classLoader.loadClass(handlerClassName).newInstance(); // The specification strongly implies all configuration should be done // during the creation of the handler object. // This includes setting level, filter, formatter and encoding. this.prefix.set(null); info.handlers.put(handlerName, handler); if (rootHandlers == null) { localRootLogger.addHandler(handler); } } catch (Exception e) { // Report error System.err.println("Handler error"); e.printStackTrace(); } } } }
// in java/org/apache/coyote/Request.java
public int doRead(ByteChunk chunk) throws IOException { int n = inputBuffer.doRead(chunk, this); if (n > 0) { bytesRead+=n; } return n; }
// in java/org/apache/coyote/Response.java
public void doWrite(ByteChunk chunk/*byte buffer[], int pos, int count*/) throws IOException { outputBuffer.doWrite(chunk, this); contentWritten+=chunk.getLength(); }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
Override public SocketState process(SocketWrapper<Long> socket) throws IOException { RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); // Setting up the socket this.socket = socket; long socketRef = socket.getSocket().longValue(); Socket.setrbb(socketRef, inputBuffer); Socket.setsbb(socketRef, outputBuffer); boolean cping = false; // Error flag error = false; boolean keptAlive = false; while (!error && !endpoint.isPaused()) { // Parsing the request header try { // Get first message of the request if (!readMessage(requestHeaderMessage, true, keptAlive)) { // This means that no data is available right now // (long keepalive), so that the processor should be recycled // and the method should return true break; } // Check message type, process right away and break if // not regular request processing int type = requestHeaderMessage.getByte(); if (type == Constants.JK_AJP13_CPING_REQUEST) { if (endpoint.isPaused()) { recycle(true); break; } cping = true; if (Socket.send(socketRef, pongMessageArray, 0, pongMessageArray.length) < 0) { error = true; } continue; } else if(type != Constants.JK_AJP13_FORWARD_REQUEST) { // Unexpected packet type. Unread body packets should have // been swallowed in finish(). if (log.isDebugEnabled()) { log.debug("Unexpected message: " + type); } error = true; break; } keptAlive = true; request.setStartTime(System.currentTimeMillis()); } catch (IOException e) { error = true; break; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; } if (!error) { // Setting up filters, and parse some request headers rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); try { prepareRequest(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; } } if (!error && !cping && endpoint.isPaused()) { // 503 - Service unavailable response.setStatus(503); adapter.log(request, response, 0); error = true; } cping = false; // Process the request in the adapter if (!error) { try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); adapter.service(request, response); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; } } if (isAsync() && !error) { break; } // Finish the response if not done yet if (!finished) { try { finish(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; } } // If there was an error, make sure the request is counted as // and error, and update the statistics counter if (error) { response.setStatus(500); } request.updateCounters(); rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); recycle(false); } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (!error && !endpoint.isPaused()) { if (isAsync()) { return SocketState.LONG; } else { return SocketState.OPEN; } } else { return SocketState.CLOSED; } }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
Override protected void output(byte[] src, int offset, int length) throws IOException { outputBuffer.put(src, offset, length); long socketRef = socket.getSocket().longValue(); if (outputBuffer.position() > 0) { if ((socketRef != 0) && Socket.sendbb(socketRef, 0, outputBuffer.position()) < 0) { throw new IOException(sm.getString("ajpprocessor.failedsend")); } outputBuffer.clear(); } }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
protected boolean read(int n) throws IOException { if (inputBuffer.capacity() - inputBuffer.limit() <= n - inputBuffer.remaining()) { inputBuffer.compact(); inputBuffer.limit(inputBuffer.position()); inputBuffer.position(0); } int nRead; while (inputBuffer.remaining() < n) { nRead = Socket.recvbb (socket.getSocket().longValue(), inputBuffer.limit(), inputBuffer.capacity() - inputBuffer.limit()); if (nRead > 0) { inputBuffer.limit(inputBuffer.limit() + nRead); } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } } return true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
protected boolean readt(int n, boolean useAvailableData) throws IOException { if (useAvailableData && inputBuffer.remaining() == 0) { return false; } if (inputBuffer.capacity() - inputBuffer.limit() <= n - inputBuffer.remaining()) { inputBuffer.compact(); inputBuffer.limit(inputBuffer.position()); inputBuffer.position(0); } int nRead; while (inputBuffer.remaining() < n) { nRead = Socket.recvbb (socket.getSocket().longValue(), inputBuffer.limit(), inputBuffer.capacity() - inputBuffer.limit()); if (nRead > 0) { inputBuffer.limit(inputBuffer.limit() + nRead); } else { if ((-nRead) == Status.ETIMEDOUT || (-nRead) == Status.TIMEUP) { return false; } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } } } return true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
Override public boolean receive() throws IOException { first = false; bodyMessage.reset(); if (!readMessage(bodyMessage, false, false)) { // Invalid message return false; } // No data received. if (bodyMessage.getLen() == 0) { // just the header // Don't mark 'end of stream' for the first chunk. return false; } int blen = bodyMessage.peekInt(); if (blen == 0) { return false; } bodyMessage.getBodyBytes(bodyBytes); empty = false; return true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
protected boolean readMessage(AjpMessage message, boolean first, boolean useAvailableData) throws IOException { int headerLength = message.getHeaderLength(); if (first) { if (!readt(headerLength, useAvailableData)) { return false; } } else { read(headerLength); } inputBuffer.get(message.getBuffer(), 0, headerLength); int messageLength = message.processHeader(true); if (messageLength < 0) { // Invalid AJP header signature // TODO: Throw some exception and close the connection to frontend. return false; } else if (messageLength == 0) { // Zero length message. return true; } else { if (messageLength > message.getBuffer().length) { // Message too long for the buffer // Need to trigger a 400 response throw new IllegalArgumentException(sm.getString( "ajpprocessor.header.tooLong", Integer.valueOf(messageLength), Integer.valueOf(message.getBuffer().length))); } read(messageLength); inputBuffer.get(message.getBuffer(), headerLength, messageLength); return true; } }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
Override public SocketState process(SocketWrapper<NioChannel> socket) throws IOException { RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); // Setting up the socket this.socket = socket.getSocket(); long soTimeout = endpoint.getSoTimeout(); boolean cping = false; // Error flag error = false; while (!error && !endpoint.isPaused()) { // Parsing the request header try { // Get first message of the request int bytesRead = readMessage(requestHeaderMessage, false); if (bytesRead == 0) { break; } // Set back timeout if keep alive timeout is enabled if (keepAliveTimeout > 0) { socket.setTimeout(soTimeout); } // Check message type, process right away and break if // not regular request processing int type = requestHeaderMessage.getByte(); if (type == Constants.JK_AJP13_CPING_REQUEST) { if (endpoint.isPaused()) { recycle(true); break; } cping = true; try { output(pongMessageArray, 0, pongMessageArray.length); } catch (IOException e) { error = true; } recycle(false); continue; } else if(type != Constants.JK_AJP13_FORWARD_REQUEST) { // Unexpected packet type. Unread body packets should have // been swallowed in finish(). if (log.isDebugEnabled()) { log.debug("Unexpected message: " + type); } error = true; recycle(true); break; } request.setStartTime(System.currentTimeMillis()); } catch (IOException e) { error = true; break; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; } if (!error) { // Setting up filters, and parse some request headers rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); try { prepareRequest(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; } } if (!error && !cping && endpoint.isPaused()) { // 503 - Service unavailable response.setStatus(503); adapter.log(request, response, 0); error = true; } cping = false; // Process the request in the adapter if (!error) { try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); adapter.service(request, response); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; } } if (isAsync() && !error) { break; } // Finish the response if not done yet if (!finished) { try { finish(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; } } // If there was an error, make sure the request is counted as // and error, and update the statistics counter if (error) { response.setStatus(500); } request.updateCounters(); rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); // Set keep alive timeout if enabled if (keepAliveTimeout > 0) { socket.setTimeout(keepAliveTimeout); } recycle(false); } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (!error && !endpoint.isPaused()) { if (isAsync()) { return SocketState.LONG; } else { return SocketState.OPEN; } } else { return SocketState.CLOSED; } }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
Override protected void output(byte[] src, int offset, int length) throws IOException { ByteBuffer writeBuffer = socket.getBufHandler() .getWriteBuffer(); writeBuffer.put(src, offset, length); writeBuffer.flip(); NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled"); long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { pool.write(writeBuffer, socket, selector, writeTimeout, true); }finally { if ( selector != null ) pool.put(selector); } writeBuffer.clear(); }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
protected int read(byte[] buf, int pos, int n, boolean blockFirstRead) throws IOException { int read = 0; int res = 0; boolean block = blockFirstRead; while (read < n) { res = readSocket(buf, read + pos, n, block); if (res > 0) { read += res; } else if (res == 0 && !block) { break; } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } block = true; } return read; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
private int readSocket(byte[] buf, int pos, int n, boolean block) throws IOException { int nRead = 0; socket.getBufHandler().getReadBuffer().clear(); socket.getBufHandler().getReadBuffer().limit(n); if ( block ) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled."); nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout()); } catch ( EOFException eof ) { nRead = -1; } finally { if ( selector != null ) pool.put(selector); } } else { nRead = socket.read(socket.getBufHandler().getReadBuffer()); } if (nRead > 0) { socket.getBufHandler().getReadBuffer().flip(); socket.getBufHandler().getReadBuffer().limit(nRead); socket.getBufHandler().getReadBuffer().get(buf, pos, nRead); return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("iib.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
Override public boolean receive() throws IOException { first = false; bodyMessage.reset(); readMessage(bodyMessage, true); // No data received. if (bodyMessage.getLen() == 0) { // just the header // Don't mark 'end of stream' for the first chunk. return false; } int blen = bodyMessage.peekInt(); if (blen == 0) { return false; } bodyMessage.getBodyBytes(bodyBytes); empty = false; return true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
protected int readMessage(AjpMessage message, boolean blockFirstRead) throws IOException { byte[] buf = message.getBuffer(); int headerLength = message.getHeaderLength(); int bytesRead = read(buf, 0, headerLength, blockFirstRead); if (bytesRead == 0) { return 0; } int messageLength = message.processHeader(true); if (messageLength < 0) { // Invalid AJP header signature throw new IOException(sm.getString("ajpmessage.invalidLength", Integer.valueOf(messageLength))); } else if (messageLength == 0) { // Zero length message. return bytesRead; } else { if (messageLength > buf.length) { // Message too long for the buffer // Need to trigger a 400 response throw new IllegalArgumentException(sm.getString( "ajpprocessor.header.tooLong", Integer.valueOf(messageLength), Integer.valueOf(buf.length))); } bytesRead += read(buf, headerLength, messageLength, true); return bytesRead; } }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public SocketState event(SocketStatus status) throws IOException { // Should never reach this code but in case we do... throw new IOException( sm.getString("ajpprocessor.comet.notsupported")); }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public SocketState upgradeDispatch() throws IOException { // Should never reach this code but in case we do... throw new IOException( sm.getString("ajpprocessor.httpupgrade.notsupported")); }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
protected boolean refillReadBuffer() throws IOException { // If the server returns an empty packet, assume that that end of // the stream has been reached (yuck -- fix protocol??). // FORM support if (replay) { endOfStream = true; // we've read everything there is } if (endOfStream) { return false; } // Request more data immediately output(getBodyMessageArray, 0, getBodyMessageArray.length); boolean moreData = receive(); if( !moreData ) { endOfStream = true; } return moreData; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
protected void prepareResponse() throws IOException { response.setCommitted(true); responseMessage.reset(); responseMessage.appendByte(Constants.JK_AJP13_SEND_HEADERS); // HTTP header contents responseMessage.appendInt(response.getStatus()); String message = null; if (org.apache.coyote.Constants.USE_CUSTOM_STATUS_MSG_IN_HEADER && HttpMessages.isSafeInHttpHeader(response.getMessage())) { message = response.getMessage(); } if (message == null){ message = HttpMessages.getMessage(response.getStatus()); } if (message == null) { // mod_jk + httpd 2.x fails with a null status message - bug 45026 message = Integer.toString(response.getStatus()); } tmpMB.setString(message); responseMessage.appendBytes(tmpMB); // Special headers MimeHeaders headers = response.getMimeHeaders(); String contentType = response.getContentType(); if (contentType != null) { headers.setValue("Content-Type").setString(contentType); } String contentLanguage = response.getContentLanguage(); if (contentLanguage != null) { headers.setValue("Content-Language").setString(contentLanguage); } long contentLength = response.getContentLengthLong(); if (contentLength >= 0) { headers.setValue("Content-Length").setLong(contentLength); } // Other headers int numHeaders = headers.size(); responseMessage.appendInt(numHeaders); for (int i = 0; i < numHeaders; i++) { MessageBytes hN = headers.getName(i); int hC = Constants.getResponseAjpIndex(hN.toString()); if (hC > 0) { responseMessage.appendInt(hC); } else { responseMessage.appendBytes(hN); } MessageBytes hV=headers.getValue(i); responseMessage.appendBytes(hV); } // Write to buffer responseMessage.end(); output(responseMessage.getBuffer(), 0, responseMessage.getLen()); }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
protected void flush(boolean explicit) throws IOException { if (explicit && !finished) { // Send the flush message output(flushMessageArray, 0, flushMessageArray.length); } }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
protected void finish() throws IOException { if (!response.isCommitted()) { // Validate and write response headers try { prepareResponse(); } catch (IOException e) { // Set error flag error = true; } } if (finished) return; finished = true; // Swallow the unread body packet if present if (first && request.getContentLengthLong() > 0) { receive(); } // Add the end message if (error) { output(endAndCloseMessageArray, 0, endAndCloseMessageArray.length); } else { output(endMessageArray, 0, endMessageArray.length); } }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public int doRead(ByteChunk chunk, Request req) throws IOException { if (endOfStream) { return -1; } if (first && req.getContentLengthLong() > 0) { // Handle special first-body-chunk if (!receive()) { return 0; } } else if (empty) { if (!refillReadBuffer()) { return -1; } } ByteChunk bc = bodyBytes.getByteChunk(); chunk.setBytes(bc.getBuffer(), bc.getStart(), bc.getLength()); empty = true; return chunk.getLength(); }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { if (!response.isCommitted()) { // Validate and write response headers try { prepareResponse(); } catch (IOException e) { // Set error flag error = true; } } int len = chunk.getLength(); // 4 - hardcoded, byte[] marshaling overhead // Adjust allowed size if packetSize != default (Constants.MAX_PACKET_SIZE) int chunkSize = Constants.MAX_SEND_SIZE + packetSize - Constants.MAX_PACKET_SIZE; int off = 0; while (len > 0) { int thisTime = len; if (thisTime > chunkSize) { thisTime = chunkSize; } len -= thisTime; responseMessage.reset(); responseMessage.appendByte(Constants.JK_AJP13_SEND_BODY_CHUNK); responseMessage.appendBytes(chunk.getBytes(), chunk.getOffset() + off, thisTime); responseMessage.end(); output(responseMessage.getBuffer(), 0, responseMessage.getLen()); off += thisTime; } bytesWritten += chunk.getLength(); return chunk.getLength(); }
// in java/org/apache/coyote/ajp/AjpProcessor.java
Override public SocketState process(SocketWrapper<Socket> socket) throws IOException { RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); // Setting up the socket this.socket = socket; input = socket.getSocket().getInputStream(); output = socket.getSocket().getOutputStream(); int soTimeout = -1; if (keepAliveTimeout > 0) { soTimeout = socket.getSocket().getSoTimeout(); } boolean cping = false; // Error flag error = false; while (!error && !endpoint.isPaused()) { // Parsing the request header try { // Set keep alive timeout if enabled if (keepAliveTimeout > 0) { socket.getSocket().setSoTimeout(keepAliveTimeout); } // Get first message of the request if (!readMessage(requestHeaderMessage)) { // This means a connection timeout break; } // Set back timeout if keep alive timeout is enabled if (keepAliveTimeout > 0) { socket.getSocket().setSoTimeout(soTimeout); } // Check message type, process right away and break if // not regular request processing int type = requestHeaderMessage.getByte(); if (type == Constants.JK_AJP13_CPING_REQUEST) { if (endpoint.isPaused()) { recycle(true); break; } cping = true; try { output.write(pongMessageArray); } catch (IOException e) { error = true; } continue; } else if(type != Constants.JK_AJP13_FORWARD_REQUEST) { // Unexpected packet type. Unread body packets should have // been swallowed in finish(). if (log.isDebugEnabled()) { log.debug("Unexpected message: " + type); } error = true; break; } request.setStartTime(System.currentTimeMillis()); } catch (IOException e) { error = true; break; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; } if (!error) { // Setting up filters, and parse some request headers rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); try { prepareRequest(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; } } if (!error && !cping && endpoint.isPaused()) { // 503 - Service unavailable response.setStatus(503); adapter.log(request, response, 0); error = true; } cping = false; // Process the request in the adapter if (!error) { try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); adapter.service(request, response); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; } } if (isAsync() && !error) { break; } // Finish the response if not done yet if (!finished) { try { finish(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; } } // If there was an error, make sure the request is counted as // and error, and update the statistics counter if (error) { response.setStatus(500); } request.updateCounters(); rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); recycle(false); } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (isAsync() && !error && !endpoint.isPaused()) { return SocketState.LONG; } else { input = null; output = null; return SocketState.CLOSED; } }
// in java/org/apache/coyote/ajp/AjpProcessor.java
Override protected void output(byte[] src, int offset, int length) throws IOException { output.write(src, offset, length); }
// in java/org/apache/coyote/ajp/AjpProcessor.java
protected boolean read(byte[] buf, int pos, int n) throws IOException { int read = 0; int res = 0; while (read < n) { res = input.read(buf, read + pos, n - read); if (res > 0) { read += res; } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } } return true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
Override public boolean receive() throws IOException { first = false; bodyMessage.reset(); if (!readMessage(bodyMessage)) { // Invalid message return false; } // No data received. if (bodyMessage.getLen() == 0) { // just the header // Don't mark 'end of stream' for the first chunk. return false; } int blen = bodyMessage.peekInt(); if (blen == 0) { return false; } bodyMessage.getBodyBytes(bodyBytes); empty = false; return true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
protected boolean readMessage(AjpMessage message) throws IOException { byte[] buf = message.getBuffer(); int headerLength = message.getHeaderLength(); read(buf, 0, headerLength); int messageLength = message.processHeader(true); if (messageLength < 0) { // Invalid AJP header signature // TODO: Throw some exception and close the connection to frontend. return false; } else if (messageLength == 0) { // Zero length message. return true; } else { if (messageLength > buf.length) { // Message too long for the buffer // Need to trigger a 400 response throw new IllegalArgumentException(sm.getString( "ajpprocessor.header.tooLong", Integer.valueOf(messageLength), Integer.valueOf(buf.length))); } read(buf, headerLength, messageLength); return true; } }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
Override public SocketState event(SocketStatus status) throws IOException { RequestInfo rp = request.getRequestProcessor(); try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); error = !adapter.event(request, response, status); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (error) { return SocketState.CLOSED; } else if (!comet) { inputBuffer.nextRequest(); outputBuffer.nextRequest(); return SocketState.OPEN; } else { return SocketState.LONG; } }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
Override protected void setRequestLineReadTimeout() throws IOException { // Timeouts while in the poller are handled entirely by the poller // Only need to be concerned with socket timeouts // APR uses simulated blocking so if some request line data is present // then it must all be presented (with the normal socket timeout). // When entering the processing loop for the first time there will // always be some data to read so the keep-alive timeout is not required // For the second and subsequent executions of the processing loop, if // there is no request line data present then no further data will be // read from the socket. If there is request line data present then it // must all be presented (with the normal socket timeout) // When the socket is created it is given the correct timeout. // sendfile may change the timeout but will restore it // This processor may change the timeout for uploads but will restore it // NO-OP }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
Override public SocketState event(SocketStatus status) throws IOException { long soTimeout = endpoint.getSoTimeout(); RequestInfo rp = request.getRequestProcessor(); final NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment)socket.getSocket().getAttachment(false); try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); error = !adapter.event(request, response, status); if ( !error ) { if (attach != null) { attach.setComet(comet); if (comet) { Integer comettimeout = (Integer) request.getAttribute( org.apache.coyote.Constants.COMET_TIMEOUT_ATTR); if (comettimeout != null) { attach.setTimeout(comettimeout.longValue()); } } else { //reset the timeout if (keepAlive) { attach.setTimeout(keepAliveTimeout); } else { attach.setTimeout(soTimeout); } } } } } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (error) { return SocketState.CLOSED; } else if (!comet) { if (keepAlive) { inputBuffer.nextRequest(); outputBuffer.nextRequest(); return SocketState.OPEN; } else { return SocketState.CLOSED; } } else { return SocketState.LONG; } }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
Override protected void setRequestLineReadTimeout() throws IOException { // socket.setTimeout() // - timeout used by poller // socket.getSocket().getIOChannel().socket().setSoTimeout() // - timeout used for blocking reads // When entering the processing loop there will always be data to read // so no point changing timeouts at this point // For the second and subsequent executions of the processing loop, a // non-blocking read is used so again no need to set the timeouts // Because NIO supports non-blocking reading of the request line and // headers the timeouts need to be set when returning the socket to // the poller rather than here. // NO-OP }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
Override protected void setSocketTimeout(int timeout) throws IOException { socket.getSocket().getIOChannel().socket().setSoTimeout(timeout); }
// in java/org/apache/coyote/http11/InternalOutputBuffer.java
Override public void init(SocketWrapper<Socket> socketWrapper, AbstractEndpoint endpoint) throws IOException { outputStream = socketWrapper.getSocket().getOutputStream(); }
// in java/org/apache/coyote/http11/InternalOutputBuffer.java
Override public void flush() throws IOException { super.flush(); // Flush the current buffer if (useSocketBuffer) { socketBuffer.flushBuffer(); } }
// in java/org/apache/coyote/http11/InternalOutputBuffer.java
Override public void endRequest() throws IOException { super.endRequest(); if (useSocketBuffer) { socketBuffer.flushBuffer(); } }
// in java/org/apache/coyote/http11/InternalOutputBuffer.java
Override public void sendAck() throws IOException { if (!committed) outputStream.write(Constants.ACK_BYTES); }
// in java/org/apache/coyote/http11/InternalOutputBuffer.java
Override protected void commit() throws IOException { // The response is now committed committed = true; response.setCommitted(true); if (pos > 0) { // Sending the response header buffer if (useSocketBuffer) { socketBuffer.append(buf, 0, pos); } else { outputStream.write(buf, 0, pos); } } }
// in java/org/apache/coyote/http11/InternalOutputBuffer.java
Override public void realWriteBytes(byte cbuf[], int off, int len) throws IOException { if (len > 0) { outputStream.write(cbuf, off, len); } }
// in java/org/apache/coyote/http11/InternalOutputBuffer.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { int length = chunk.getLength(); if (useSocketBuffer) { socketBuffer.append(chunk.getBuffer(), chunk.getStart(), length); } else { outputStream.write(chunk.getBuffer(), chunk.getStart(), length); } byteCount += chunk.getLength(); return chunk.getLength(); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableDataOnly) throws IOException { //check state if ( !parsingRequestLine ) return true; // // Skipping blank lines // if ( parsingRequestLinePhase == 0 ) { byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (useAvailableDataOnly) { return false; } // Ignore bytes that were read pos = lastValid = 0; // Do a simple read with a short timeout if ( readSocket(true, false)==0 ) return false; } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; if (pos >= skipBlankLinesSize) { // Move data, to have enough space for further reading // of headers and body System.arraycopy(buf, pos, buf, 0, lastValid - pos); lastValid -= pos; pos = 0; } skipBlankLinesBytes = pos; parsingRequestLineStart = pos; parsingRequestLinePhase = 2; if (log.isDebugEnabled()) { log.debug("Received [" + new String(buf, pos, lastValid - pos, DEFAULT_CHARSET) + "]"); } } if ( parsingRequestLinePhase == 2 ) { // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, parsingRequestLineStart, pos - parsingRequestLineStart); } pos++; } parsingRequestLinePhase = 3; } if ( parsingRequestLinePhase == 3 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 4; } if (parsingRequestLinePhase == 4) { // Mark the current buffer position int end = 0; // // Reading the URI // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request parsingRequestLineEol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (parsingRequestLineQPos == -1)) { parsingRequestLineQPos = pos; } pos++; } request.unparsedURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); if (parsingRequestLineQPos >= 0) { request.queryString().setBytes(buf, parsingRequestLineQPos + 1, end - parsingRequestLineQPos - 1); request.requestURI().setBytes(buf, parsingRequestLineStart, parsingRequestLineQPos - parsingRequestLineStart); } else { request.requestURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } parsingRequestLinePhase = 5; } if ( parsingRequestLinePhase == 5 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 6; } if (parsingRequestLinePhase == 6) { // Mark the current buffer position end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!parsingRequestLineEol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; parsingRequestLineEol = true; } pos++; } if ( (end - parsingRequestLineStart) > 0) { request.protocol().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } else { request.protocol().setString(""); } parsingRequestLine = false; parsingRequestLinePhase = 0; parsingRequestLineEol = false; parsingRequestLineStart = 0; return true; } throw new IllegalStateException("Invalid request line parse phase:"+parsingRequestLinePhase); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
private int readSocket(boolean timeout, boolean block) throws IOException { int nRead = 0; socket.getBufHandler().getReadBuffer().clear(); if ( block ) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled."); nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout()); } catch ( EOFException eof ) { nRead = -1; } finally { if ( selector != null ) pool.put(selector); } } else { nRead = socket.read(socket.getBufHandler().getReadBuffer()); } if (nRead > 0) { socket.getBufHandler().getReadBuffer().flip(); socket.getBufHandler().getReadBuffer().limit(nRead); expand(nRead + pos); socket.getBufHandler().getReadBuffer().get(buf, pos, nRead); lastValid = pos + nRead; return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("iib.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } HeaderParseStatus status = HeaderParseStatus.HAVE_MORE_HEADERS; do { status = parseHeader(); } while ( status == HeaderParseStatus.HAVE_MORE_HEADERS ); if (status == HeaderParseStatus.DONE) { parsingHeader = false; end = pos; // Checking that // (1) Headers plus request line size does not exceed its limit // (2) There are enough bytes to avoid expanding the buffer when // reading body // Technically, (2) is technical limitation, (1) is logical // limitation to enforce the meaning of headerBufferSize // From the way how buf is allocated and how blank lines are being // read, it should be enough to check (1) only. if (end - skipBlankLinesBytes > headerBufferSize || buf.length - end < socketReadBufferSize) { throw new IllegalArgumentException( sm.getString("iib.requestheadertoolarge.error")); } return true; } else { return false; } }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
private HeaderParseStatus parseHeader() throws IOException { // // Check for blank line // byte chr = 0; while (headerParsePos == HeaderParsePosition.HEADER_START) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header headerParsePos = HeaderParsePosition.HEADER_START; return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.CR) { // Skip } else if (chr == Constants.LF) { pos++; return HeaderParseStatus.DONE; } else { break; } pos++; } if ( headerParsePos == HeaderParsePosition.HEADER_START ) { // Mark the current buffer position headerData.start = pos; headerParsePos = HeaderParsePosition.HEADER_NAME; } // // Reading the header name // Header name is always US-ASCII // while (headerParsePos == HeaderParsePosition.HEADER_NAME) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) { //parse header return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.COLON) { headerParsePos = HeaderParsePosition.HEADER_VALUE_START; headerData.headerValue = headers.addValue(buf, headerData.start, pos - headerData.start); pos++; // Mark the current buffer position headerData.start = pos; headerData.realPos = pos; headerData.lastSignificantChar = pos; break; } else if (!HTTP_TOKEN_CHAR[chr]) { // If a non-token header is detected, skip the line and // ignore the header headerData.lastSignificantChar = pos; return skipLine(); } // chr is next byte of header name. Convert to lowercase. if ((chr >= Constants.A) && (chr <= Constants.Z)) { buf[pos] = (byte) (chr - Constants.LC_OFFSET); } pos++; } // Skip the line and ignore the header if (headerParsePos == HeaderParsePosition.HEADER_SKIPLINE) { return skipLine(); } // // Reading the header value (which can be spanned over multiple lines) // while (headerParsePos == HeaderParsePosition.HEADER_VALUE_START || headerParsePos == HeaderParsePosition.HEADER_VALUE || headerParsePos == HeaderParsePosition.HEADER_MULTI_LINE) { if ( headerParsePos == HeaderParsePosition.HEADER_VALUE_START ) { // Skipping spaces while (true) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header //HEADER_VALUE_START return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.SP || chr == Constants.HT) { pos++; } else { headerParsePos = HeaderParsePosition.HEADER_VALUE; break; } } } if ( headerParsePos == HeaderParsePosition.HEADER_VALUE ) { // Reading bytes until the end of the line boolean eol = false; while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header //HEADER_VALUE return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.CR) { // Skip } else if (chr == Constants.LF) { eol = true; } else if (chr == Constants.SP || chr == Constants.HT) { buf[headerData.realPos] = chr; headerData.realPos++; } else { buf[headerData.realPos] = chr; headerData.realPos++; headerData.lastSignificantChar = headerData.realPos; } pos++; } // Ignore whitespaces at the end of the line headerData.realPos = headerData.lastSignificantChar; // Checking the first character of the new line. If the character // is a LWS, then it's a multiline header headerParsePos = HeaderParsePosition.HEADER_MULTI_LINE; } // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header //HEADER_MULTI_LINE return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if ( headerParsePos == HeaderParsePosition.HEADER_MULTI_LINE ) { if ( (chr != Constants.SP) && (chr != Constants.HT)) { headerParsePos = HeaderParsePosition.HEADER_START; break; } else { // Copying one extra space in the buffer (since there must // be at least one space inserted between the lines) buf[headerData.realPos] = chr; headerData.realPos++; headerParsePos = HeaderParsePosition.HEADER_VALUE_START; } } } // Set the header value headerData.headerValue.setBytes(buf, headerData.start, headerData.lastSignificantChar - headerData.start); headerData.recycle(); return HeaderParseStatus.HAVE_MORE_HEADERS; }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
private HeaderParseStatus skipLine() throws IOException { headerParsePos = HeaderParsePosition.HEADER_SKIPLINE; boolean eol = false; // Reading bytes until the end of the line while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) { return HeaderParseStatus.NEED_MORE_DATA; } } if (buf[pos] == Constants.CR) { // Skip } else if (buf[pos] == Constants.LF) { eol = true; } else { headerData.lastSignificantChar = pos; } pos++; } if (log.isDebugEnabled()) { log.debug(sm.getString("iib.invalidheader", new String(buf, headerData.start, headerData.lastSignificantChar - headerData.start + 1, DEFAULT_CHARSET))); } headerParsePos = HeaderParsePosition.HEADER_START; return HeaderParseStatus.HAVE_MORE_HEADERS; }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override protected void init(SocketWrapper<NioChannel> socketWrapper, AbstractEndpoint endpoint) throws IOException { socket = socketWrapper.getSocket(); socketReadBufferSize = socket.getBufHandler().getReadBuffer().capacity(); int bufLength = skipBlankLinesSize + headerBufferSize + socketReadBufferSize; if (buf == null || buf.length < bufLength) { buf = new byte[bufLength]; } pool = ((NioEndpoint)endpoint).getSelectorPool(); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override protected boolean fill(boolean block) throws IOException, EOFException { return fill(true,block); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
protected boolean fill(boolean timeout, boolean block) throws IOException, EOFException { boolean read = false; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } // Do a simple read with a short timeout read = readSocket(timeout,block)>0; } else { lastValid = pos = end; // Do a simple read with a short timeout read = readSocket(timeout, block)>0; } return read; }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override public int doRead(ByteChunk chunk, Request req ) throws IOException { if (pos >= lastValid) { if (!fill(true,true)) //read body, must be blocking, as the thread is inside the app return -1; } int length = lastValid - pos; chunk.setBytes(buf, pos, length); pos = lastValid; return (length); }
// in java/org/apache/coyote/http11/upgrade/UpgradeProcessor.java
Override public final SocketState upgradeDispatch() throws IOException { return upgradeInbound.onData(); }
// in java/org/apache/coyote/http11/upgrade/UpgradeProcessor.java
Override public final SocketState process(SocketWrapper<S> socketWrapper) throws IOException { return null; }
// in java/org/apache/coyote/http11/upgrade/UpgradeProcessor.java
Override public final SocketState event(SocketStatus status) throws IOException { return null; }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
Override public void flush() throws IOException { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) nioChannel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled"); } long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { do { if (nioChannel.flush(true, selector, writeTimeout)) { break; } } while (true); } finally { if (selector != null) { pool.put(selector); } } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
Override public void write(int b) throws IOException { writeToSocket(new byte[] {(byte) b}, 0, 1); }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
Override public void write(byte[]b, int off, int len) throws IOException { int written = 0; while (len - written > maxWrite) { written += writeToSocket(b, off + written, maxWrite); } writeToSocket(b, off + written, len - written); }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
Override public int read() throws IOException { byte[] bytes = new byte[1]; int result = readSocket(true, bytes, 0, 1); if (result == -1) { return -1; } else { return bytes[0] & 0xFF; } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
Override public int read(boolean block, byte[] bytes, int off, int len) throws IOException { if (len > maxRead) { return readSocket(block, bytes, off, maxRead); } else { return readSocket(block, bytes, off, len); } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
private int readSocket(boolean block, byte[] bytes, int offset, int len) throws IOException { int nRead = 0; nioChannel.getBufHandler().getReadBuffer().clear(); nioChannel.getBufHandler().getReadBuffer().limit(len); if (block) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) nioChannel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled."); } nRead = pool.read(nioChannel.getBufHandler().getReadBuffer(), nioChannel, selector, att.getTimeout()); } catch (EOFException eof) { nRead = -1; } finally { if (selector != null) { pool.put(selector); } } } else { nRead = nioChannel.read(nioChannel.getBufHandler().getReadBuffer()); } if (nRead > 0) { nioChannel.getBufHandler().getReadBuffer().flip(); nioChannel.getBufHandler().getReadBuffer().limit(nRead); nioChannel.getBufHandler().getReadBuffer().get(bytes, offset, nRead); return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("nio.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
private synchronized int writeToSocket(byte[] bytes, int off, int len) throws IOException { nioChannel.getBufHandler().getWriteBuffer().clear(); nioChannel.getBufHandler().getWriteBuffer().put(bytes, off, len); nioChannel.getBufHandler().getWriteBuffer().flip(); int written = 0; NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) nioChannel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled"); } long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { written = pool.write(nioChannel.getBufHandler().getWriteBuffer(), nioChannel, selector, writeTimeout, true); } finally { if (selector != null) { pool.put(selector); } } return written; }
// in java/org/apache/coyote/http11/upgrade/UpgradeBioProcessor.java
Override public void flush() throws IOException { outputStream.flush(); }
// in java/org/apache/coyote/http11/upgrade/UpgradeBioProcessor.java
Override public void write(int b) throws IOException { outputStream.write(b); }
// in java/org/apache/coyote/http11/upgrade/UpgradeBioProcessor.java
Override public void write(byte[]b, int off, int len) throws IOException { outputStream.write(b, off, len); }
// in java/org/apache/coyote/http11/upgrade/UpgradeBioProcessor.java
Override public int read() throws IOException { return inputStream.read(); }
// in java/org/apache/coyote/http11/upgrade/UpgradeBioProcessor.java
Override public int read(boolean block, byte[] bytes, int off, int len) throws IOException { // The BIO endpoint always uses blocking IO so the block parameter is // ignored and a blocking read is performed. return inputStream.read(bytes, off, len); }
// in java/org/apache/coyote/http11/upgrade/UpgradeAprProcessor.java
Override public void flush() throws IOException { // NOOP }
// in java/org/apache/coyote/http11/upgrade/UpgradeAprProcessor.java
Override public void write(int b) throws IOException { Socket.send(socket, new byte[] {(byte) b}, 0, 1); }
// in java/org/apache/coyote/http11/upgrade/UpgradeAprProcessor.java
Override public void write(byte[]b, int off, int len) throws IOException { Socket.send(socket, b, off, len); }
// in java/org/apache/coyote/http11/upgrade/UpgradeAprProcessor.java
Override public int read() throws IOException { byte[] bytes = new byte[1]; int result = Socket.recv(socket, bytes, 0, 1); if (result == -1) { return -1; } else { return bytes[0] & 0xFF; } }
// in java/org/apache/coyote/http11/upgrade/UpgradeAprProcessor.java
Override public int read(boolean block, byte[] bytes, int off, int len) throws IOException { if (!block) { Socket.optSet(socket, Socket.APR_SO_NONBLOCK, -1); } try { int result = Socket.recv(socket, bytes, off, len); if (result > 0) { return result; } else if (-result == Status.EAGAIN) { return 0; } else { throw new IOException(sm.getString("apr.error", Integer.valueOf(-result))); } } finally { if (!block) { Socket.optSet(socket, Socket.APR_SO_NONBLOCK, 0); } } }
// in java/org/apache/coyote/http11/upgrade/UpgradeOutbound.java
Override public void flush() throws IOException { processor.flush(); }
// in java/org/apache/coyote/http11/upgrade/UpgradeOutbound.java
Override public void write(int b) throws IOException { processor.write(b); }
// in java/org/apache/coyote/http11/upgrade/UpgradeOutbound.java
Override public void write(byte[] b, int off, int len) throws IOException { processor.write(b, off, len); }
// in java/org/apache/coyote/http11/Http11NioProtocol.java
Override protected Processor<NioChannel> createUpgradeProcessor( SocketWrapper<NioChannel> socket, UpgradeInbound inbound) throws IOException { return new UpgradeNioProcessor(socket, inbound, ((Http11NioProtocol) getProtocol()).getEndpoint().getSelectorPool()); }
// in java/org/apache/coyote/http11/filters/SavedRequestInputFilter.java
Override public int doRead(ByteChunk chunk, org.apache.coyote.Request request) throws IOException { int writeLength = 0; if (chunk.getLimit() > 0 && chunk.getLimit() < input.getLength()) { writeLength = chunk.getLimit(); } else { writeLength = input.getLength(); } if(input.getOffset()>= input.getEnd()) return -1; input.substract(chunk.getBuffer(), 0, writeLength); chunk.setOffset(0); chunk.setEnd(writeLength); return writeLength; }
// in java/org/apache/coyote/http11/filters/SavedRequestInputFilter.java
Override public long end() throws IOException { return 0; }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
Override public int doRead(ByteChunk chunk, Request req) throws IOException { if (endChunk) return -1; if(needCRLFParse) { needCRLFParse = false; parseCRLF(); } if (remaining <= 0) { if (!parseChunkHeader()) { throw new IOException("Invalid chunk header"); } if (endChunk) { parseEndChunk(); return -1; } } int result = 0; if (pos >= lastValid) { readBytes(); } if (remaining > (lastValid - pos)) { result = lastValid - pos; remaining = remaining - result; chunk.setBytes(buf, pos, result); pos = lastValid; } else { result = remaining; chunk.setBytes(buf, pos, remaining); pos = pos + remaining; remaining = 0; //we need a CRLF if ((pos+1) >= lastValid) { //if we call parseCRLF we overrun the buffer here //so we defer it to the next call BZ 11117 needCRLFParse = true; } else { parseCRLF(); //parse the CRLF immediately } } return result; }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
Override public long end() throws IOException { // Consume extra bytes : parse the stream until the end chunk is found while (doRead(readChunk, null) >= 0) { // NOOP: Just consume the input } // Return the number of extra bytes which were consumed return (lastValid - pos); }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
protected int readBytes() throws IOException { int nRead = buffer.doRead(readChunk, null); pos = readChunk.getStart(); lastValid = pos + nRead; buf = readChunk.getBytes(); return nRead; }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
protected boolean parseChunkHeader() throws IOException { int result = 0; boolean eol = false; boolean readDigit = false; boolean trailer = false; while (!eol) { if (pos >= lastValid) { if (readBytes() <= 0) return false; } if (buf[pos] == Constants.CR) { // FIXME: Improve parsing to check for CRLF } else if (buf[pos] == Constants.LF) { eol = true; } else if (buf[pos] == Constants.SEMI_COLON) { trailer = true; } else if (!trailer) { //don't read data after the trailer if (HexUtils.getDec(buf[pos]) != -1) { readDigit = true; result *= 16; result += HexUtils.getDec(buf[pos]); } else { //we shouldn't allow invalid, non hex characters //in the chunked header return false; } } pos++; } if (!readDigit) return false; if (result == 0) endChunk = true; remaining = result; if (remaining < 0) return false; return true; }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
protected boolean parseCRLF() throws IOException { boolean eol = false; boolean crfound = false; while (!eol) { if (pos >= lastValid) { if (readBytes() <= 0) throw new IOException("Invalid CRLF"); } if (buf[pos] == Constants.CR) { if (crfound) throw new IOException("Invalid CRLF, two CR characters encountered."); crfound = true; } else if (buf[pos] == Constants.LF) { if (!crfound) throw new IOException("Invalid CRLF, no CR character encountered."); eol = true; } else { throw new IOException("Invalid CRLF"); } pos++; } return true; }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
protected void parseEndChunk() throws IOException { // Handle option trailer headers while (parseHeader()) { // Loop until we run out of headers } }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
private boolean parseHeader() throws IOException { MimeHeaders headers = request.getMimeHeaders(); byte chr = 0; while (true) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr == Constants.CR) || (chr == Constants.LF)) { if (chr == Constants.LF) { pos++; return false; } } else { break; } pos++; } // Mark the current buffer position int start = trailingHeaders.getEnd(); // // Reading the header name // Header name is always US-ASCII // boolean colon = false; while (!colon) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr >= Constants.A) && (chr <= Constants.Z)) { chr = (byte) (chr - Constants.LC_OFFSET); } if (chr == Constants.COLON) { colon = true; } else { trailingHeaders.append(chr); } pos++; } MessageBytes headerValue = headers.addValue(trailingHeaders.getBytes(), start, trailingHeaders.getEnd() - start); // Mark the current buffer position start = trailingHeaders.getEnd(); // // Reading the header value (which can be spanned over multiple lines) // boolean eol = false; boolean validLine = true; int lastSignificantChar = 0; while (validLine) { boolean space = true; // Skipping spaces while (space) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr == Constants.SP) || (chr == Constants.HT)) { pos++; } else { space = false; } } // Reading bytes until the end of the line while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if (chr == Constants.CR) { // Skip } else if (chr == Constants.LF) { eol = true; } else if (chr == Constants.SP) { trailingHeaders.append(chr); } else { trailingHeaders.append(chr); lastSignificantChar = trailingHeaders.getEnd(); } pos++; } // Checking the first character of the new line. If the character // is a LWS, then it's a multiline header // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr != Constants.SP) && (chr != Constants.HT)) { validLine = false; } else { eol = false; // Copying one extra space in the buffer (since there must // be at least one space inserted between the lines) trailingHeaders.append(chr); } } // Set the header value headerValue.setBytes(trailingHeaders.getBytes(), start, lastSignificantChar - start); return true; }
// in java/org/apache/coyote/http11/filters/IdentityInputFilter.java
Override public int doRead(ByteChunk chunk, Request req) throws IOException { int result = -1; if (contentLength >= 0) { if (remaining > 0) { int nRead = buffer.doRead(chunk, req); if (nRead > remaining) { // The chunk is longer than the number of bytes remaining // in the body; changing the chunk length to the number // of bytes remaining chunk.setBytes(chunk.getBytes(), chunk.getStart(), (int) remaining); result = (int) remaining; } else { result = nRead; } remaining = remaining - nRead; } else { // No more bytes left to be read : return -1 and clear the // buffer chunk.recycle(); result = -1; } } return result; }
// in java/org/apache/coyote/http11/filters/IdentityInputFilter.java
Override public long end() throws IOException { // Consume extra bytes. while (remaining > 0) { int nread = buffer.doRead(endChunk, null); if (nread > 0 ) { remaining = remaining - nread; } else { // errors are handled higher up. remaining = 0; } } // If too many bytes were read, return the amount. return -remaining; }
// in java/org/apache/coyote/http11/filters/ChunkedOutputFilter.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { int result = chunk.getLength(); if (result <= 0) { return 0; } // Calculate chunk header int pos = 7; int current = result; while (current > 0) { int digit = current % 16; current = current / 16; chunkLength[pos--] = HexUtils.getHex(digit); } chunkHeader.setBytes(chunkLength, pos + 1, 9 - pos); buffer.doWrite(chunkHeader, res); buffer.doWrite(chunk, res); chunkHeader.setBytes(chunkLength, 8, 2); buffer.doWrite(chunkHeader, res); return result; }
// in java/org/apache/coyote/http11/filters/ChunkedOutputFilter.java
Override public long end() throws IOException { // Write end chunk buffer.doWrite(END_CHUNK, null); return 0; }
// in java/org/apache/coyote/http11/filters/VoidOutputFilter.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { return chunk.getLength(); }
// in java/org/apache/coyote/http11/filters/VoidOutputFilter.java
Override public long end() throws IOException { return 0; }
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { if (compressionStream == null) { compressionStream = new FlushableGZIPOutputStream(fakeOutputStream); } compressionStream.write(chunk.getBytes(), chunk.getStart(), chunk.getLength()); return chunk.getLength(); }
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
Override public long end() throws IOException { if (compressionStream == null) { compressionStream = new FlushableGZIPOutputStream(fakeOutputStream); } compressionStream.finish(); compressionStream.close(); return ((OutputFilter) buffer).end(); }
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
Override public void write(int b) throws IOException { // Shouldn't get used for good performance, but is needed for // compatibility with Sun JDK 1.4.0 singleByteBuffer[0] = (byte) (b & 0xff); outputChunk.setBytes(singleByteBuffer, 0, 1); buffer.doWrite(outputChunk, null); }
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
Override public void write(byte[] b, int off, int len) throws IOException { outputChunk.setBytes(b, off, len); buffer.doWrite(outputChunk, null); }
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
Override public void flush() throws IOException {/*NOOP*/}
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
Override public void close() throws IOException {/*NOOP*/}
// in java/org/apache/coyote/http11/filters/BufferedInputFilter.java
Override public int doRead(ByteChunk chunk, Request request) throws IOException { if (hasRead || buffered.getLength() <= 0) { return -1; } chunk.setBytes(buffered.getBytes(), buffered.getStart(), buffered.getLength()); hasRead = true; return chunk.getLength(); }
// in java/org/apache/coyote/http11/filters/BufferedInputFilter.java
Override public long end() throws IOException { return 0; }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
Override public void write(byte[] bytes) throws IOException { write(bytes, 0, bytes.length); }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
Override public synchronized void write(byte[] bytes, int offset, int length) throws IOException { if (length > 0) { flushLastByte(); if (length > 1) { super.write(bytes, offset, length - 1); } rememberLastByte(bytes[offset + length - 1]); } }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
Override public synchronized void write(int i) throws IOException { flushLastByte(); rememberLastByte((byte) i); }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
Override public synchronized void finish() throws IOException { try { flushLastByte(); } catch (IOException ignore) { // If our write failed, then trailer write in finish() will fail // with IOException as well, but it will leave Deflater in more // consistent state. } super.finish(); }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
Override public synchronized void close() throws IOException { try { flushLastByte(); } catch (IOException ignored) { // Ignore. As OutputStream#close() says, the contract of close() // is to close the stream. It does not matter much if the // stream is not writable any more. } super.close(); }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
private void flushLastByte() throws IOException { if (hasLastByte) { // Clear the flag first, because write() may fail hasLastByte = false; super.write(lastByte, 0, 1); } }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
Override public synchronized void flush() throws IOException { if (hasLastByte) { // - do not allow the gzip header to be flushed on its own // - do not do anything if there is no data to send // trick the deflater to flush /** * Now this is tricky: We force the Deflater to flush its data by * switching compression level. As yet, a perplexingly simple workaround * for * http://developer.java.sun.com/developer/bugParade/bugs/4255743.html */ if (!def.finished()) { def.setLevel(Deflater.NO_COMPRESSION); flushLastByte(); def.setLevel(Deflater.DEFAULT_COMPRESSION); } } out.flush(); }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
Override protected void deflate() throws IOException { int len; do { len = def.deflate(buf, 0, buf.length); if (len > 0) { out.write(buf, 0, len); } } while (len != 0); }
// in java/org/apache/coyote/http11/filters/IdentityOutputFilter.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { int result = -1; if (contentLength >= 0) { if (remaining > 0) { result = chunk.getLength(); if (result > remaining) { // The chunk is longer than the number of bytes remaining // in the body; changing the chunk length to the number // of bytes remaining chunk.setBytes(chunk.getBytes(), chunk.getStart(), (int) remaining); result = (int) remaining; remaining = 0; } else { remaining = remaining - result; } buffer.doWrite(chunk, res); } else { // No more bytes left to be written : return -1 and clear the // buffer chunk.recycle(); result = -1; } } else { // If no content length was set, just write the bytes buffer.doWrite(chunk, res); result = chunk.getLength(); } return result; }
// in java/org/apache/coyote/http11/filters/IdentityOutputFilter.java
Override public long end() throws IOException { if (remaining > 0) return remaining; return 0; }
// in java/org/apache/coyote/http11/filters/VoidInputFilter.java
Override public int doRead(ByteChunk chunk, Request req) throws IOException { return -1; }
// in java/org/apache/coyote/http11/filters/VoidInputFilter.java
Override public long end() throws IOException { return 0; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
Override public SocketState process(SocketWrapper<S> socketWrapper) throws IOException { RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); // Setting up the I/O setSocketWrapper(socketWrapper); getInputBuffer().init(socketWrapper, endpoint); getOutputBuffer().init(socketWrapper, endpoint); // Flags error = false; keepAlive = true; comet = false; openSocket = false; sendfileInProgress = false; readComplete = true; if (endpoint.getUsePolling()) { keptAlive = false; } else { keptAlive = socketWrapper.isKeptAlive(); } if (disableKeepAlive()) { socketWrapper.setKeepAliveLeft(0); } while (!error && keepAlive && !comet && !isAsync() && upgradeInbound == null && !endpoint.isPaused()) { // Parsing the request header try { setRequestLineReadTimeout(); if (!getInputBuffer().parseRequestLine(keptAlive)) { if (handleIncompleteRequestLineRead()) { break; } } if (endpoint.isPaused()) { // 503 - Service unavailable response.setStatus(503); error = true; } else { request.setStartTime(System.currentTimeMillis()); keptAlive = true; // Currently only NIO will ever return false here if (!getInputBuffer().parseHeaders()) { // We've read part of the request, don't recycle it // instead associate it with the socket openSocket = true; readComplete = false; break; } if (!disableUploadTimeout) { setSocketTimeout(connectionUploadTimeout); } } } catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), e); } error = true; break; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), t); } // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; } if (!error) { // Setting up filters, and parse some request headers rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); try { prepareRequest(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug(sm.getString( "http11processor.request.prepare"), t); } // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; } } if (maxKeepAliveRequests == 1) { keepAlive = false; } else if (maxKeepAliveRequests > 0 && socketWrapper.decrementKeepAlive() <= 0) { keepAlive = false; } // Process the request in the adapter if (!error) { try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); adapter.service(request, response); // Handle when the response was committed before a serious // error occurred. Throwing a ServletException should both // set the status to 500 and set the errorException. // If we fail here, then the response is likely already // committed, so we can't try and set headers. if(keepAlive && !error) { // Avoid checking twice. error = response.getErrorException() != null || (!isAsync() && statusDropsConnection(response.getStatus())); } setCometTimeouts(socketWrapper); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString( "http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; } } // Finish the handling of the request rp.setStage(org.apache.coyote.Constants.STAGE_ENDINPUT); if (!isAsync() && !comet) { if (error) { // If we know we are closing the connection, don't drain // input. This way uploading a 100GB file doesn't tie up the // thread if the servlet has rejected it. getInputBuffer().setSwallowInput(false); } endRequest(); } rp.setStage(org.apache.coyote.Constants.STAGE_ENDOUTPUT); // If there was an error, make sure the request is counted as // and error, and update the statistics counter if (error) { response.setStatus(500); } request.updateCounters(); if (!isAsync() && !comet || error) { getInputBuffer().nextRequest(); getOutputBuffer().nextRequest(); } if (!disableUploadTimeout) { setSocketTimeout(endpoint.getSoTimeout()); } rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); if (breakKeepAliveLoop(socketWrapper)) { break; } } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (error || endpoint.isPaused()) { return SocketState.CLOSED; } else if (isAsync() || comet) { return SocketState.LONG; } else if (isUpgrade()) { return SocketState.UPGRADING; } else { if (sendfileInProgress) { return SocketState.SENDFILE; } else { if (openSocket) { if (readComplete) { return SocketState.OPEN; } else { return SocketState.LONG; } } else { return SocketState.CLOSED; } } } }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
Override public SocketState upgradeDispatch() throws IOException { // Should never reach this code but in case we do... // TODO throw new IOException( sm.getString("TODO")); }
// in java/org/apache/coyote/http11/Http11Protocol.java
Override protected Processor<Socket> createUpgradeProcessor( SocketWrapper<Socket> socket, UpgradeInbound inbound) throws IOException { return new UpgradeBioProcessor(socket, inbound); }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableDataOnly) throws IOException { int start = 0; // // Skipping blank lines // byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; // Mark the current buffer position start = pos; // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, start, pos - start); } pos++; } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; int end = 0; int questionPos = -1; // // Reading the URI // boolean eol = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request eol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (questionPos == -1)) { questionPos = pos; } pos++; } request.unparsedURI().setBytes(buf, start, end - start); if (questionPos >= 0) { request.queryString().setBytes(buf, questionPos + 1, end - questionPos - 1); request.requestURI().setBytes(buf, start, questionPos - start); } else { request.requestURI().setBytes(buf, start, end - start); } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; eol = true; } pos++; } if ((end - start) > 0) { request.protocol().setBytes(buf, start, end - start); } else { request.protocol().setString(""); } return true; }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } while (parseHeader()) { // Loop until we run out of headers } parsingHeader = false; end = pos; return true; }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override protected void init(SocketWrapper<Socket> socketWrapper, AbstractEndpoint endpoint) throws IOException { inputStream = socketWrapper.getSocket().getInputStream(); }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
private void skipLine(int start) throws IOException { boolean eol = false; int lastRealByte = start; if (pos - 1 > start) { lastRealByte = pos - 1; } while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { // Skip } else if (buf[pos] == Constants.LF) { eol = true; } else { lastRealByte = pos; } pos++; } if (log.isDebugEnabled()) { log.debug(sm.getString("iib.invalidheader", new String(buf, start, lastRealByte - start + 1, Charset.forName("ISO-8859-1")))); } }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
protected boolean fill() throws IOException { return fill(true); }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override protected boolean fill(boolean block) throws IOException { int nRead = 0; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } nRead = inputStream.read(buf, pos, buf.length - lastValid); if (nRead > 0) { lastValid = pos + nRead; } } else { if (buf.length - end < 4500) { // In this case, the request header was really large, so we allocate a // brand new one; the old one will get GCed when subsequent requests // clear all references buf = new byte[buf.length]; end = 0; } pos = end; lastValid = pos; nRead = inputStream.read(buf, pos, buf.length - lastValid); if (nRead > 0) { lastValid = pos + nRead; } } return (nRead > 0); }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override public int doRead(ByteChunk chunk, Request req ) throws IOException { if (pos >= lastValid) { if (!fill()) return -1; } int length = lastValid - pos; chunk.setBytes(buf, pos, length); pos = lastValid; return (length); }
// in java/org/apache/coyote/http11/Http11Processor.java
Override protected void setRequestLineReadTimeout() throws IOException { /* * When there is no data in the buffer and this is not the first * request on this connection and timeouts are being used the * first read for this request may need a different timeout to * take account of time spent waiting for a processing thread. * * This is a little hacky but better than exposing the socket * and the timeout info to the InputBuffer */ if (inputBuffer.lastValid == 0 && socket.getLastAccess() > -1) { int firstReadTimeout; if (keepAliveTimeout == -1) { firstReadTimeout = 0; } else { long queueTime = System.currentTimeMillis() - socket.getLastAccess(); if (queueTime >= keepAliveTimeout) { // Queued for longer than timeout but there might be // data so use shortest possible timeout firstReadTimeout = 1; } else { // Cast is safe since queueTime must be less than // keepAliveTimeout which is an int firstReadTimeout = keepAliveTimeout - (int) queueTime; } } socket.getSocket().setSoTimeout(firstReadTimeout); if (!inputBuffer.fill()) { throw new EOFException(sm.getString("iib.eof.error")); } // Once the first byte has been read, the standard timeout should be // used so restore it here. socket.getSocket().setSoTimeout(endpoint.getSoTimeout()); } }
// in java/org/apache/coyote/http11/Http11Processor.java
Override protected void setSocketTimeout(int timeout) throws IOException { socket.getSocket().setSoTimeout(timeout); }
// in java/org/apache/coyote/http11/Http11Processor.java
Override public SocketState event(SocketStatus status) throws IOException { // Should never reach this code but in case we do... throw new IOException( sm.getString("http11processor.comet.notsupported")); }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
Override public void init(SocketWrapper<Long> socketWrapper, AbstractEndpoint endpoint) throws IOException { socket = socketWrapper.getSocket().longValue(); Socket.setsbb(this.socket, bbuf); }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
Override public void flush() throws IOException { super.flush(); // Flush the current buffer flushBuffer(); }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
Override public void endRequest() throws IOException { if (!committed) { // Send the connector a request for commit. The connector should // then validate the headers, send them (using sendHeader) and // set the filters accordingly. response.action(ActionCode.COMMIT, null); } if (finished) return; if (lastActiveFilter != -1) activeFilters[lastActiveFilter].end(); flushBuffer(); finished = true; }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
Override public void sendAck() throws IOException { if (!committed) { if (Socket.send(socket, Constants.ACK_BYTES, 0, Constants.ACK_BYTES.length) < 0) throw new IOException(sm.getString("iib.failedwrite")); } }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
Override protected void commit() throws IOException { // The response is now committed committed = true; response.setCommitted(true); if (pos > 0) { // Sending the response header buffer bbuf.put(buf, 0, pos); } }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
private void flushBuffer() throws IOException { if (bbuf.position() > 0) { if (Socket.sendbb(socket, 0, bbuf.position()) < 0) { throw new IOException(); } bbuf.clear(); } }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { int len = chunk.getLength(); int start = chunk.getStart(); byte[] b = chunk.getBuffer(); while (len > 0) { int thisTime = len; if (bbuf.position() == bbuf.capacity()) { flushBuffer(); } if (thisTime > bbuf.capacity() - bbuf.position()) { thisTime = bbuf.capacity() - bbuf.position(); } bbuf.put(b, start, thisTime); len = len - thisTime; start = start + thisTime; } byteCount += chunk.getLength(); return chunk.getLength(); }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableData) throws IOException { int start = 0; // // Skipping blank lines // byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (useAvailableData) { return false; } if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; // Mark the current buffer position start = pos; if (pos >= lastValid) { if (useAvailableData) { return false; } if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, start, pos - start); } pos++; } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; int end = 0; int questionPos = -1; // // Reading the URI // boolean eol = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request eol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (questionPos == -1)) { questionPos = pos; } pos++; } request.unparsedURI().setBytes(buf, start, end - start); if (questionPos >= 0) { request.queryString().setBytes(buf, questionPos + 1, end - questionPos - 1); request.requestURI().setBytes(buf, start, questionPos - start); } else { request.requestURI().setBytes(buf, start, end - start); } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; eol = true; } pos++; } if ((end - start) > 0) { request.protocol().setBytes(buf, start, end - start); } else { request.protocol().setString(""); } return true; }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } while (parseHeader()) { // Loop until there are no more headers } parsingHeader = false; end = pos; return true; }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
private void skipLine(int start) throws IOException { boolean eol = false; int lastRealByte = start; if (pos - 1 > start) { lastRealByte = pos - 1; } while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { // Skip } else if (buf[pos] == Constants.LF) { eol = true; } else { lastRealByte = pos; } pos++; } if (log.isDebugEnabled()) { log.debug(sm.getString("iib.invalidheader", new String(buf, start, lastRealByte - start + 1, Charset.forName("ISO-8859-1")))); } }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override public int doRead(ByteChunk chunk, Request req) throws IOException { if (lastActiveFilter == -1) return inputStreamInputBuffer.doRead(chunk, req); else return activeFilters[lastActiveFilter].doRead(chunk,req); }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override protected void init(SocketWrapper<Long> socketWrapper, AbstractEndpoint endpoint) throws IOException { socket = socketWrapper.getSocket().longValue(); Socket.setrbb(this.socket, bbuf); }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override protected boolean fill(boolean block) throws IOException { // Ignore the block parameter and just call fill return fill(); }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
protected boolean fill() throws IOException { int nRead = 0; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.EAGAIN) { return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } else { if (buf.length - end < 4500) { // In this case, the request header was really large, so we allocate a // brand new one; the old one will get GCed when subsequent requests // clear all references buf = new byte[buf.length]; end = 0; } pos = end; lastValid = pos; bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.ETIMEDOUT || (-nRead) == Status.TIMEUP) { throw new SocketTimeoutException(sm.getString("iib.failedread")); } else if (nRead == 0) { // APR_STATUS_IS_EOF, since native 1.1.22 return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } return (nRead > 0); }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override public int doRead(ByteChunk chunk, Request req ) throws IOException { if (pos >= lastValid) { if (!fill()) return -1; } int length = lastValid - pos; chunk.setBytes(buf, pos, length); pos = lastValid; return (length); }
// in java/org/apache/coyote/http11/AbstractInputBuffer.java
public void endRequest() throws IOException { if (swallowInput && (lastActiveFilter != -1)) { int extraBytes = (int) activeFilters[lastActiveFilter].end(); pos = pos - extraBytes; } }
// in java/org/apache/coyote/http11/AbstractInputBuffer.java
Override public int doRead(ByteChunk chunk, Request req) throws IOException { if (lastActiveFilter == -1) return inputStreamInputBuffer.doRead(chunk, req); else return activeFilters[lastActiveFilter].doRead(chunk,req); }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
Override public void flush() throws IOException { super.flush(); // Flush the current buffer flushBuffer(); }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
Override public void endRequest() throws IOException { super.endRequest(); flushBuffer(); }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
Override public void sendAck() throws IOException { if (!committed) { //Socket.send(socket, Constants.ACK_BYTES, 0, Constants.ACK_BYTES.length) < 0 socket.getBufHandler() .getWriteBuffer().put(Constants.ACK_BYTES,0,Constants.ACK_BYTES.length); writeToSocket(socket.getBufHandler() .getWriteBuffer(),true,true); } }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
private synchronized int writeToSocket(ByteBuffer bytebuffer, boolean block, boolean flip) throws IOException { if ( flip ) bytebuffer.flip(); int written = 0; NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled"); long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { written = pool.write(bytebuffer, socket, selector, writeTimeout, block); //make sure we are flushed do { if (socket.flush(true,selector,writeTimeout)) break; }while ( true ); }finally { if ( selector != null ) pool.put(selector); } if ( block ) bytebuffer.clear(); //only clear return written; }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
Override public void init(SocketWrapper<NioChannel> socketWrapper, AbstractEndpoint endpoint) throws IOException { socket = socketWrapper.getSocket(); pool = ((NioEndpoint)endpoint).getSelectorPool(); }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
Override protected void commit() throws IOException { // The response is now committed committed = true; response.setCommitted(true); if (pos > 0) { // Sending the response header buffer addToBB(buf, 0, pos); } }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
private synchronized void addToBB(byte[] buf, int offset, int length) throws IOException { while (length > 0) { int thisTime = length; if (socket.getBufHandler().getWriteBuffer().position() == socket.getBufHandler().getWriteBuffer().capacity() || socket.getBufHandler().getWriteBuffer().remaining()==0) { flushBuffer(); } if (thisTime > socket.getBufHandler().getWriteBuffer().remaining()) { thisTime = socket.getBufHandler().getWriteBuffer().remaining(); } socket.getBufHandler().getWriteBuffer().put(buf, offset, thisTime); length = length - thisTime; offset = offset + thisTime; } NioEndpoint.KeyAttachment ka = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( ka!= null ) ka.access();//prevent timeouts for just doing client writes }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
private void flushBuffer() throws IOException { //prevent timeout for async, SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if (key != null) { NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment) key.attachment(); attach.access(); } //write to the socket, if there is anything to write if (socket.getBufHandler().getWriteBuffer().position() > 0) { socket.getBufHandler().getWriteBuffer().flip(); writeToSocket(socket.getBufHandler().getWriteBuffer(),true, false); } }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { int len = chunk.getLength(); int start = chunk.getStart(); byte[] b = chunk.getBuffer(); addToBB(b, start, len); byteCount += chunk.getLength(); return chunk.getLength(); }
// in java/org/apache/coyote/http11/AbstractOutputBuffer.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { if (!committed) { // Send the connector a request for commit. The connector should // then validate the headers, send them (using sendHeaders) and // set the filters accordingly. response.action(ActionCode.COMMIT, null); } if (lastActiveFilter == -1) return outputStreamOutputBuffer.doWrite(chunk, res); else return activeFilters[lastActiveFilter].doWrite(chunk, res); }
// in java/org/apache/coyote/http11/AbstractOutputBuffer.java
public void flush() throws IOException { if (!committed) { // Send the connector a request for commit. The connector should // then validate the headers, send them (using sendHeader) and // set the filters accordingly. response.action(ActionCode.COMMIT, null); } // go through the filters and if there is gzip filter // invoke it to flush for (int i = 0; i <= lastActiveFilter; i++) { if (activeFilters[i] instanceof GzipOutputFilter) { if (log.isDebugEnabled()) { log.debug("Flushing the gzip filter at position " + i + " of the filter chain..."); } ((GzipOutputFilter) activeFilters[i]).flush(); break; } } }
// in java/org/apache/coyote/http11/AbstractOutputBuffer.java
public void endRequest() throws IOException { if (!committed) { // Send the connector a request for commit. The connector should // then validate the headers, send them (using sendHeader) and // set the filters accordingly. response.action(ActionCode.COMMIT, null); } if (finished) return; if (lastActiveFilter != -1) activeFilters[lastActiveFilter].end(); finished = true; }
// in java/org/apache/coyote/http11/Http11AprProtocol.java
Override protected Processor<Long> createUpgradeProcessor( SocketWrapper<Long> socket, UpgradeInbound inbound) throws IOException { return new UpgradeAprProcessor(socket, inbound); }
// in java/org/apache/coyote/spdy/SpdyAprNpnHandler.java
Override public void init(final AbstractEndpoint ep, long sslContext, final Adapter adapter) { spdyContext = new SpdyContext(); if (sslContext == 0) { // Apr endpoint without SSL - proxy mode. spdyContext.setTlsComprression(false, false); return; } if (0 != SSLExt.setNPN(sslContext, SpdyContext.SPDY_NPN_OUT)) { log.warn("SPDY/NPN not supported"); } spdyContext.setNetSupport(new NetSupportOpenSSL()); spdyContext.setExecutor(ep.getExecutor()); spdyContext.setHandler(new SpdyHandler() { @Override public void onStream(SpdyConnection con, SpdyStream ch) throws IOException { SpdyProcessor sp = new SpdyProcessor(con, ep); sp.setAdapter(adapter); sp.onSynStream(ch); } }); }
// in java/org/apache/coyote/spdy/SpdyAprNpnHandler.java
Override public void onStream(SpdyConnection con, SpdyStream ch) throws IOException { SpdyProcessor sp = new SpdyProcessor(con, ep); sp.setAdapter(adapter); sp.onSynStream(ch); }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
Override public int doRead(ByteChunk bchunk, Request request) throws IOException { if (inFrame == null) { // blocking inFrame = spdyStream.getDataFrame(endpoint.getSoTimeout()); } if (inFrame == null) { return -1; // timeout } if (inFrame.remaining() == 0 && inFrame.isHalfClose()) { return -1; } int rd = Math.min(inFrame.remaining(), bchunk.getBytes().length); System.arraycopy(inFrame.data, inFrame.off, bchunk.getBytes(), bchunk.getStart(), rd); inFrame.advance(rd); if (inFrame.remaining() == 0) { spdy.getSpdyContext().releaseFrame(inFrame); if (!inFrame.isHalfClose()) { inFrame = null; } } bchunk.setEnd(bchunk.getEnd() + rd); return rd; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
Override public int doWrite(org.apache.tomcat.util.buf.ByteChunk chunk, Response response) throws IOException { if (!response.isCommitted()) { // Send the connector a request for commit. The connector should // then validate the headers, send them (using sendHeader) and // set the filters accordingly. response.action(ActionCode.COMMIT, null); } spdyStream.sendDataFrame(chunk.getBuffer(), chunk.getStart(), chunk.getLength(), false); byteCount += chunk.getLength(); return chunk.getLength(); }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
protected void sendSynReply() throws IOException { response.setCommitted(true); // Special headers MimeHeaders headers = response.getMimeHeaders(); String contentType = response.getContentType(); if (contentType != null) { headers.setValue("Content-Type").setString(contentType); } String contentLanguage = response.getContentLanguage(); if (contentLanguage != null) { headers.setValue("Content-Language").setString(contentLanguage); } long contentLength = response.getContentLengthLong(); if (contentLength >= 0) { headers.setValue("Content-Length").setLong(contentLength); } sendResponseHead(); }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
private void sendResponseHead() throws IOException { SpdyFrame rframe = spdy.getFrame(SpdyConnection.TYPE_SYN_REPLY); rframe.associated = 0; MimeHeaders headers = response.getMimeHeaders(); for (int i = 0; i < headers.size(); i++) { MessageBytes mb = headers.getName(i); mb.toBytes(); ByteChunk bc = mb.getByteChunk(); byte[] bb = bc.getBuffer(); for (int j = bc.getStart(); j < bc.getEnd(); j++) { bb[j] = (byte) Ascii.toLower(bb[j]); } // TODO: filter headers: Connection, Keep-Alive, Proxy-Connection, rframe.headerName(bc.getBuffer(), bc.getStart(), bc.getLength()); mb = headers.getValue(i); mb.toBytes(); bc = mb.getByteChunk(); rframe.headerValue(bc.getBuffer(), bc.getStart(), bc.getLength()); } if (response.getStatus() == 0) { rframe.addHeader(SpdyFrame.STATUS, SpdyFrame.OK200); } else { // HTTP header contents String message = null; if (org.apache.coyote.Constants.USE_CUSTOM_STATUS_MSG_IN_HEADER && HttpMessages.isSafeInHttpHeader(response.getMessage())) { message = response.getMessage(); } if (message == null) { message = HttpMessages.getMessage(response.getStatus()); } if (message == null) { // mod_jk + httpd 2.x fails with a null status message - bug // 45026 message = Integer.toString(response.getStatus()); } // TODO: optimize String status = response.getStatus() + " " + message; byte[] statusB = status.getBytes(); rframe.headerName(SpdyFrame.STATUS, 0, SpdyFrame.STATUS.length); rframe.headerValue(statusB, 0, statusB.length); } rframe.addHeader(SpdyFrame.VERSION, SpdyFrame.HTTP11); rframe.streamId = spdyStream.reqFrame.streamId; spdy.send(rframe, spdyStream); // we can't reuse the frame - it'll be queued, the coyote processor // may be reused as well. outCommit = true; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
Override public SocketState process(SocketWrapper<Object> socket) throws IOException { throw new IOException("Unimplemented"); }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
Override public SocketState event(SocketStatus status) throws IOException { System.err.println("EVENT: " + status); return null; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
Override public SocketState upgradeDispatch() throws IOException { return null; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
public void onSynStream(SpdyStream str) throws IOException { this.spdyStream = str; SpdyFrame frame = str.reqFrame; // We need to make a copy - the frame buffer will be reused. // We use the 'wrap' methods of MimeHeaders - which should be // lighter on mem in some cases. RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); // Request received. MimeHeaders mimeHeaders = request.getMimeHeaders(); for (int i = 0; i < frame.nvCount; i++) { int nameLen = frame.read16(); if (nameLen > frame.remaining()) { throw new IOException("Name too long"); } keyBuffer.setBytes(frame.data, frame.off, nameLen); if (keyBuffer.equals("method")) { frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } request.method().setBytes(frame.data, frame.off, valueLen); frame.advance(valueLen); } else if (keyBuffer.equals("url")) { frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } request.requestURI().setBytes(frame.data, frame.off, valueLen); if (SpdyContext.debug) { System.err.println("URL= " + request.requestURI()); } frame.advance(valueLen); } else if (keyBuffer.equals("version")) { frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } frame.advance(valueLen); } else { MessageBytes value = mimeHeaders.addValue(frame.data, frame.off, nameLen); frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } value.setBytes(frame.data, frame.off, valueLen); frame.advance(valueLen); } } onRequest(); }
// in java/org/apache/coyote/spdy/SpdyProxyProtocol.java
Override public void start() throws Exception { super.start(); spdyContext = new SpdyContext(); spdyContext.setTlsComprression(false, false); spdyContext.setHandler(new SpdyHandler() { @Override public void onStream(SpdyConnection con, SpdyStream ch) throws IOException { SpdyProcessor sp = new SpdyProcessor(con, endpoint); sp.setAdapter(adapter); sp.onSynStream(ch); } }); spdyContext.setNetSupport(new NetSupportSocket()); spdyContext.setExecutor(endpoint.getExecutor()); }
// in java/org/apache/coyote/spdy/SpdyProxyProtocol.java
Override public void onStream(SpdyConnection con, SpdyStream ch) throws IOException { SpdyProcessor sp = new SpdyProcessor(con, endpoint); sp.setAdapter(adapter); sp.onSynStream(ch); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public AprSocketContext setKeys(String certPemFile, String keyDerFile) throws IOException { this.sslMode = true; setTls(); certFile = certPemFile; keyFile = keyDerFile; return this; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public void listen(final int port) throws IOException { if (acceptor != null) { throw new IOException("Already accepting on " + acceptor.port); } if (sslMode && certFile == null) { throw new IOException("Missing certificates for server"); } if (sslMode || !nonBlockingAccept) { acceptorDispatch = new AcceptorDispatchThread(port); acceptorDispatch.setName("AprAcceptorDispatch-" + port); acceptorDispatch.start(); } acceptor = new AcceptorThread(port); acceptor.prepare(); acceptor.setName("AprAcceptor-" + port); acceptor.start(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public AprSocket socket(String host, int port, boolean ssl) throws IOException { HostInfo hi = getHostInfo(host, port, ssl); return socket(hi); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public AprSocket socket(HostInfo hi) throws IOException { AprSocket sock = newSocket(this); sock.setHost(hi); return sock; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public AprSocket socket(long socket) throws IOException { AprSocket sock = newSocket(this); // Tomcat doesn't set this SSLExt.sslSetMode(socket, SSLExt.SSL_MODE_ENABLE_PARTIAL_WRITE | SSLExt.SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); sock.setStatus(AprSocket.ACCEPTED); sock.socket = socket; return sock; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
protected void connectBlocking(AprSocket apr) throws IOException { try { if (!running) { throw new IOException("Stopped"); } HostInfo hi = apr.getHost(); long clientSockP; synchronized (pollers) { long socketpool = Pool.create(getRootPool()); int family = Socket.APR_INET; clientSockP = Socket.create(family, Socket.SOCK_STREAM, Socket.APR_PROTO_TCP, socketpool); // or rootPool ? } Socket.timeoutSet(clientSockP, connectTimeout * 1000); if (OS.IS_UNIX) { Socket.optSet(clientSockP, Socket.APR_SO_REUSEADDR, 1); } Socket.optSet(clientSockP, Socket.APR_SO_KEEPALIVE, 1); // Blocking // TODO: use socket pool // TODO: cache it ( and TTL ) in hi long inetAddress = Address.info(hi.host, Socket.APR_INET, hi.port, 0, rootPool); // this may take a long time - stop/destroy must wait // at least connect timeout int rc = Socket.connect(clientSockP, inetAddress); if (rc != 0) { synchronized (pollers) { Socket.close(clientSockP); Socket.destroy(clientSockP); } /////Pool.destroy(socketpool); throw new IOException("Socket.connect(): " + rc + " " + Error.strerror(rc) + " " + connectTimeout); } if (!running) { throw new IOException("Stopped"); } connectionsCount.incrementAndGet(); if (tcpNoDelay) { Socket.optSet(clientSockP, Socket.APR_TCP_NODELAY, 1); } Socket.timeoutSet(clientSockP, defaultTimeout * 1000); apr.socket = clientSockP; apr.afterConnect(); } catch (IOException e) { apr.reset(); throw e; } catch (Throwable e) { apr.reset(); e.printStackTrace(); throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
AprSocket newSocket(AprSocketContext context) throws IOException { return new AprSocket(context); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public void stop() throws IOException { synchronized (pollers) { if (!running) { return; } running = false; } if (rootPool != 0) { if (acceptor != null) { try { acceptor.unblock(); acceptor.join(); } catch (InterruptedException e) { e.printStackTrace(); } } if (acceptorDispatch != null) { acceptedQueue.add(END); try { acceptorDispatch.join(); } catch (InterruptedException e) { e.printStackTrace(); } } if (threadPool != null) { threadPool.shutdownNow(); } log.info("Stopping pollers " + contextId); while (true) { AprPoller a; synchronized (pollers) { if (pollers.size() == 0) { break; } a = pollers.remove(0); } a.interruptPoll(); try { a.join(); log.info("Poller " + a.id + " done "); } catch (InterruptedException e) { e.printStackTrace(); } } } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
private long getRootPool() throws IOException { if (rootPool == 0) { if (noApr != null) { throw noApr; } // Create the root APR memory pool rootPool = Pool.create(0); // Adjust poller sizes if ((OS.IS_WIN32 || OS.IS_WIN64) && (maxConnections > 1024)) { // The maximum per poller to get reasonable performance is 1024 pollerThreadCount = maxConnections / 1024; // Adjust poller size so that it won't reach the limit maxConnections = maxConnections - (maxConnections % 1024); } } return rootPool; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
void findPollerAndAdd(AprSocket ch) throws IOException { if (ch.poller != null) { ch.poller.requestUpdate(ch); return; } assignPoller(ch); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
void assignPoller(AprSocket ch) throws IOException { AprPoller target = null; synchronized (pollers) { // Make sure we have min number of pollers int needPollers = pollerThreadCount - pollers.size(); if (needPollers > 0) { for (int i = needPollers; i > 0; i--) { pollers.add(allocatePoller()); } } int max = 0; for (AprPoller poller: pollers) { int rem = poller.remaining(); if (rem > max) { target = poller; max = rem; } } } if (target != null && target.add(ch)) { return; } // can't be added - add a new poller synchronized (pollers) { AprPoller poller = allocatePoller(); poller.add(ch); pollers.add(poller); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
protected void onSocket(AprSocket s) throws IOException { }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
void prepare() throws IOException { try { // Create the pool for the server socket serverSockPool = Pool.create(getRootPool()); int family = Socket.APR_INET; inetAddress = Address.info(addressStr, family, port, 0, serverSockPool); // Create the APR server socket serverSock = Socket.create(family, Socket.SOCK_STREAM, Socket.APR_PROTO_TCP, serverSockPool); if (OS.IS_UNIX) { Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Deal with the firewalls that tend to drop the inactive sockets Socket.optSet(serverSock, Socket.APR_SO_KEEPALIVE, 1); // Bind the server socket int ret = Socket.bind(serverSock, inetAddress); if (ret != 0) { throw new IOException("Socket.bind " + ret + " " + Error.strerror(ret) + " port=" + port); } // Start listening on the server socket ret = Socket.listen(serverSock, backlog ); if (ret != 0) { throw new IOException("endpoint.init.listen" + ret + " " + Error.strerror(ret)); } if (OS.IS_WIN32 || OS.IS_WIN64) { // On Windows set the reuseaddr flag after the bind/listen Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Sendfile usage on systems which don't support it cause major problems if (useSendfile && !Library.APR_HAS_SENDFILE) { useSendfile = false; } // Delay accepting of new connections until data is available // Only Linux kernels 2.4 + have that implemented // on other platforms this call is noop and will return APR_ENOTIMPL. if (deferAccept) { if (Socket.optSet(serverSock, Socket.APR_TCP_DEFER_ACCEPT, 1) == Status.APR_ENOTIMPL) { deferAccept = false; } } } catch (Throwable t) { throw new IOException(t); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
AprPoller allocatePoller() throws IOException { long pool = Pool.create(getRootPool()); int size = maxConnections / pollerThreadCount; int timeout = keepAliveTimeout; long serverPollset = allocatePoller(size, pool, timeout); if (serverPollset == 0 && size > 1024) { log.severe("Falling back to 1024-sized poll, won't scale"); size = 1024; serverPollset = allocatePoller(size, pool, timeout); } if (serverPollset == 0) { log.severe("Falling back to 62-sized poll, won't scale"); size = 62; serverPollset = allocatePoller(size, pool, timeout); } AprPoller res = new AprPoller(); res.pool = pool; res.serverPollset = serverPollset; res.desc = new long[size * 2]; res.size = size; res.id = contextId++; res.setDaemon(true); res.setName("AprPoller-" + res.id); res.start(); if (debugPoll && !sizeLogged) { sizeLogged = true; log.info("Poller size " + (res.desc.length / 2)); } return res; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
protected void updates() throws IOException { synchronized (this) { for (AprSocket up: updates) { updateIOThread(up); } updates.clear(); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
boolean add(AprSocket ch) throws IOException { synchronized (this) { if (!running) { return false; } if (keepAliveCount.get() >= size) { return false; } keepAliveCount.incrementAndGet(); ch.poller = this; } requestUpdate(ch); return true; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
protected void requestUpdate(AprSocket ch) throws IOException { synchronized (this) { if (!running) { return; } } if (isPollerThread()) { updateIOThread(ch); } else { synchronized (this) { if (!updates.contains(ch)) { updates.add(ch); } interruptPoll(); } if (debugPoll) { log.info("Poll: requestUpdate " + id + " " + ch); } } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
private void updateIOThread(AprSocket ch) throws IOException { if (!running || ch.socket == 0) { return; } // called from IO thread, either in 'updates' or after // poll. //synchronized (ch) boolean polling = ch.checkPreConnect(AprSocket.POLL); int requested = ch.requestedPolling(); if (requested == 0) { if (polling) { removeSafe(ch); } if (ch.isClosed()) { synchronized (channels) { ch.poller = null; channels.remove(ch.socket); } keepAliveCount.decrementAndGet(); ch.reset(); } } else { if (polling) { removeSafe(ch); } // will close if error pollAdd(ch, requested); } if (debugPoll) { log.info("Poll: updated=" + id + " " + ch); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
private void pollAdd(AprSocket up, int req) throws IOException { boolean failed = false; int rv; synchronized (channels) { if (up.isClosed()) { return; } rv = Poll.add(serverPollset, up.socket, req); if (rv != Status.APR_SUCCESS) { up.poller = null; keepAliveCount.decrementAndGet(); failed = true; } else { polledCount.incrementAndGet(); channels.put(up.socket, up); up.setStatus(AprSocket.POLL); } } if (failed) { up.reset(); throw new IOException("poll add error " + rv + " " + up + " " + Error.strerror(rv)); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
private void removeSafe(AprSocket up) throws IOException { int rv = Status.APR_EGENERAL; if (running && serverPollset != 0 && up.socket != 0 && !up.isClosed()) { rv = Poll.remove(serverPollset, up.socket); } up.clearStatus(AprSocket.POLL); if (rv != Status.APR_SUCCESS) { log.severe("poll remove error " + Error.strerror(rv) + " " + up); } else { polledCount.decrementAndGet(); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public void connect() throws IOException { if (isBlocking()) { // will call handleConnected() at the end. context.connectBlocking(this); } else { synchronized(this) { if ((status & CONNECTING) != 0) { return; } status |= CONNECTING; } context.connectExecutor.execute(this); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
void afterConnect() throws IOException { if (hostInfo.secure) { blockingStartTLS(); } setNonBlocking(); // call again, to set the bits ( connect was blocking ) setStatus(CONNECTED); clearStatus(CONNECTING); notifyConnected(false); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int write(byte[] data, int off, int len, long to) throws IOException { long max = System.currentTimeMillis() + to; while (true) { int rc = writeInternal(data, off, len); if (rc < 0) { throw new IOException("Write error " + rc); } else if (rc == 0) { // need poll out - do we need to update polling ? context.findPollerAndAdd(this); } else { return rc; } try { long waitTime = max - System.currentTimeMillis(); if (waitTime <= 0) { return 0; } wait(waitTime); } catch (InterruptedException e) { return 0; } } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int write(byte[] data, int off, int len) throws IOException { // In SSL mode, read/write can't be called at the same time. int rc = writeInternal(data, off, len); if (rc < 0) { throw new IOException("Write error " + rc); } else if (rc == 0) { // need poll out - do we need to update polling ? synchronized (this) { context.findPollerAndAdd(this); } } return rc; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private int writeInternal(byte[] data, int off, int len) throws IOException { int rt = 0; int sent = 0; synchronized(this) { if ((status & CLOSED) != 0 || socket == 0 || !context.running) { throw new IOException("Closed"); } if ((status & WRITING) != 0) { throw new IOException("Write from 2 threads not allowed"); } status |= WRITING; while (len > 0) { sent = Socket.send(socket, data, off, len); if (sent <= 0) { break; } off += sent; len -= sent; } status &= ~WRITING; } if (context.rawDataHandler != null) { context.rawData(this, false, data, off, sent, len, false); } if (sent <= 0) { if (sent == -Status.TIMEUP || sent == -Status.EAGAIN || sent == 0) { setStatus(POLLOUT); updatePolling(); return rt; } if (context.debug) { log.warning("apr.send(): Failed to send, closing " + sent); } reset(); throw new IOException("Error sending " + sent + " " + Error.strerror(-sent)); } else { off += sent; len -= sent; rt += sent; return sent; } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int read(byte[] data, int off, int len, long to) throws IOException { int rd = readNB(data, off, len); if (rd == 0) { synchronized(this) { try { wait(to); } catch (InterruptedException e) { return 0; } } rd = readNB(data, off, len); } return processReadResult(data, off, len, rd); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int read(byte[] data, int off, int len) throws IOException { return readNB(data, off, len); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private int processReadResult(byte[] data, int off, int len, int read) throws IOException { if (context.rawDataHandler != null) { context.rawData(this, true, data, off, read, len, false); } if (read > 0) { return read; } if (read == 0 || read == -Status.TIMEUP || read == -Status.ETIMEDOUT || read == -Status.EAGAIN) { read = 0; setStatus(POLLIN); updatePolling(); return 0; } if (read == -Status.APR_EOF || read == -1) { close(); return -1; } // abrupt close reset(); throw new IOException("apr.read(): " + read + " " + Error.strerror(-read)); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int readNB(byte[] data, int off, int len) throws IOException { int read; synchronized(this) { if ((status & CLOSED) != 0 || socket == 0 || !context.running) { return -1; } if ((status & READING) != 0) { throw new IOException("Read from 2 threads not allowed"); } status |= READING; read = Socket.recv(socket, data, off, len); status &= ~READING; } return processReadResult(data, off, len, read); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public void close() throws IOException { synchronized (this) { if ((status & CLOSED) != 0 || socket == 0) { return; } status |= CLOSED; status &= ~POLLIN; status &= ~POLLOUT; } if (context.rawDataHandler != null) { context.rawDataHandler.rawData(this, false, null, 0, 0, 0, true); } Socket.close(socket); if (poller == null) { maybeDestroy(); } else { try { poller.requestUpdate(this); } catch (IOException e) { e.printStackTrace(); } } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public long getIOTimeout() throws IOException { if (socket != 0 && context.running) { try { return Socket.timeoutGet(socket) / 1000; } catch (Exception e) { throw new IOException(e); } } else { throw new IOException("Socket is closed"); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public byte[][] getPeerCert(boolean check) throws IOException { getHost(); if (hostInfo.certs != null && hostInfo.certs != NO_CERTS && !check) { return hostInfo.certs; } if (!checkBitAndSocket(SSL_ATTACHED)) { return NO_CERTS; } try { int certLength = SSLSocket.getInfoI(socket, SSL.SSL_INFO_CLIENT_CERT_CHAIN); // TODO: if resumed, old certs are good. // If not - warn if certs changed, remember first cert, etc. if (certLength <= 0) { // Can also happen on session resume - keep the old if (hostInfo.certs == null) { hostInfo.certs = NO_CERTS; } return hostInfo.certs; } hostInfo.certs = new byte[certLength + 1][]; hostInfo.certs[0] = SSLSocket.getInfoB(socket, SSL.SSL_INFO_CLIENT_CERT); for (int i = 0; i < certLength; i++) { hostInfo.certs[i + 1] = SSLSocket.getInfoB(socket, SSL.SSL_INFO_CLIENT_CERT_CHAIN + i); } return hostInfo.certs; } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public X509Certificate[] getPeerX509Cert() throws IOException { byte[][] certs = getPeerCert(false); X509Certificate[] xcerts = new X509Certificate[certs.length]; if (certs.length == 0) { return xcerts; } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (int i = 0; i < certs.length; i++) { if (certs[i] != null) { ByteArrayInputStream bis = new ByteArrayInputStream( certs[i]); xcerts[i] = (X509Certificate) cf.generateCertificate(bis); bis.close(); } } } catch (CertificateException ex) { throw new IOException(ex); } return xcerts; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getCipherSuite() throws IOException { if (checkBitAndSocket(SSL_ATTACHED)) { return null; } try { return SSLSocket.getInfoS(socket, SSL.SSL_INFO_CIPHER); } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int getKeySize() throws IOException { if (checkBitAndSocket(SSL_ATTACHED)) { return -1; } try { return SSLSocket.getInfoI(socket, SSL.SSL_INFO_CIPHER_USEKEYSIZE); } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int getRemotePort() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_REMOTE, socket); Sockaddr addr = Address.getInfo(sa); return addr.port; } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getRemoteAddress() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_REMOTE, socket); return Address.getip(sa); } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getRemoteHostname() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_REMOTE, socket); String remoteHost = Address.getnameinfo(sa, 0); if (remoteHost == null) { remoteHost = Address.getip(sa); } return remoteHost; } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int getLocalPort() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_LOCAL, socket); Sockaddr addr = Address.getInfo(sa); return addr.port; } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getLocalAddress() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_LOCAL, socket); return Address.getip(sa); } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getLocalHostname() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_LOCAL, socket); return Address.getnameinfo(sa, 0); } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
void notifyIO() throws IOException { long t0 = System.currentTimeMillis(); try { if (handler != null) { handler.process(this, true, false, false); } } catch (Throwable t) { throw new IOException(t); } finally { long t1 = System.currentTimeMillis(); t1 -= t0; if (t1 > context.maxHandlerTime.get()) { context.maxHandlerTime.set(t1); } context.totalHandlerTime.addAndGet(t1); context.handlerCount.incrementAndGet(); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private void notifyConnected(boolean server) throws IOException { // Will set the handler on the channel for accepted context.onSocket(this); if (handler instanceof AprSocketContext.NonBlockingPollHandler) { ((AprSocketContext.NonBlockingPollHandler) handler).connected(this); ((AprSocketContext.NonBlockingPollHandler) handler).process(this, true, true, false); // Now register for polling - unless process() set suspendRead and // doesn't need out notifications updatePolling(); } else { if (server) { // client will block in connect(). // Server: call process(); notifyIO(); } } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private void updatePolling() throws IOException { synchronized (this) { if ((status & CLOSED) != 0) { maybeDestroy(); return; } } context.findPollerAndAdd(this); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public void blockingStartTLS() throws IOException { synchronized(this) { if (socket == 0 || !context.running) { return; } if ((status & SSL_ATTACHED) != 0) { return; } status |= SSL_ATTACHED; } try { if (context.debug) { log.info(this + " StartSSL"); } AprSocketContext aprCon = context; SSLSocket.attach(aprCon.getSslCtx(), socket); if (context.debugSSL) { SSLExt.debug(socket); } if (!getContext().isServer()) { if (context.USE_TICKETS && hostInfo.ticketLen > 0) { SSLExt.setTicket(socket, hostInfo.ticket, hostInfo.ticketLen); } else if (hostInfo.sessDer != null) { SSLExt.setSessionData(socket, hostInfo.sessDer, hostInfo.sessDer.length); } } SSLExt.sslSetMode(socket, SSLExt.SSL_MODE_ENABLE_PARTIAL_WRITE | SSLExt.SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); int rc = SSLSocket.handshake(socket); // At this point we have the session ID, remote certs, etc // we can lookup host info if (hostInfo == null) { hostInfo = new HostInfo(); } if (rc != Status.APR_SUCCESS) { throw new IOException(this + " Handshake failed " + rc + " " + Error.strerror(rc) + " SSLL " + SSL.getLastError()); } else { // SUCCESS handshakeDone(); } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private void handshakeDone() throws IOException { getHost(); if (socket == 0 || !context.running) { throw new IOException("Socket closed"); } if (context.USE_TICKETS && ! context.isServer()) { if (hostInfo.ticket == null) { hostInfo.ticket = new byte[2048]; } int ticketLen = SSLExt.getTicket(socket, hostInfo.ticket); if (ticketLen > 0) { hostInfo.ticketLen = ticketLen; if (context.debug) { log.info("Received ticket: " + ticketLen); } } } // TODO: if the ticket, session id or session changed - callback to // save the session again try { hostInfo.sessDer = SSLExt.getSessionData(socket); getPeerCert(true); hostInfo.sessionId = SSLSocket.getInfoS(socket, SSL.SSL_INFO_SESSION_ID); } catch (Exception e) { throw new IOException(e); } hostInfo.npn = new byte[32]; hostInfo.npnLen = SSLExt.getNPN(socket, hostInfo.npn); // If custom verification is used - should check the certificates if (context.tlsCertVerifier != null) { context.tlsCertVerifier.handshakeDone(this); } }
// in java/org/apache/tomcat/buildutil/CheckEol.java
private void check(File file, List<CheckFailure> errors, Mode mode) throws IOException { BufferedInputStream is = new BufferedInputStream(new FileInputStream( file)); try { int line = 1; int prev = -1; int ch; while ((ch = is.read()) != -1) { if (ch == '\n') { if (mode == Mode.LF && prev == '\r') { errors.add(new CheckFailure(file, line, "CRLF")); return; } else if (mode == Mode.CRLF && prev != '\r') { errors.add(new CheckFailure(file, line, "LF")); return; } line++; } else if (prev == '\r') { errors.add(new CheckFailure(file, line, "CR")); return; } prev = ch; } } finally { is.close(); } }
// in java/org/apache/tomcat/buildutil/Txt2Html.java
private void convert( File from, File to ) throws IOException { // Open files: BufferedReader in = new BufferedReader( new FileReader( from ) ); PrintWriter out = new PrintWriter( new FileWriter( to ) ); // Output header: out.println( "<html><body><pre>" ); // Convert, line-by-line: String line; while( (line = in.readLine()) != null ) { StringBuilder result = new StringBuilder(); int len = line.length(); for( int i = 0; i < len; i++ ) { char c = line.charAt( i ); switch( c ) { case '&': result.append( "&amp;" ); break; case '<': result.append( "&lt;" ); break; default: result.append( c ); } } out.println( result.toString() ); } // Output footer: out.println( "</pre></body></html>" ); // Close streams: out.close(); in.close(); }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public void onCtlFrame(SpdyFrame frame) throws IOException { // TODO: handle RST if (frame.type == SpdyConnection.TYPE_SYN_STREAM) { reqFrame = frame; } else if (frame.type == SpdyConnection.TYPE_SYN_REPLY) { resFrame = frame; } synchronized (this) { inData.add(frame); if (frame.isHalfClose()) { finRcvd = true; } } }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public SpdyFrame getDataFrame(long to) throws IOException { while (true) { SpdyFrame res = getFrame(to); if (res == null || res.isData()) { return res; } if (res.type == SpdyConnection.TYPE_RST_STREAM) { throw new IOException("Reset"); } } }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public SpdyFrame getFrame(long to) throws IOException { SpdyFrame in; try { synchronized (this) { if (inData.size() == 0 && finRcvd) { return END_FRAME; } } in = inData.poll(to, TimeUnit.MILLISECONDS); return in; } catch (InterruptedException e) { return null; } }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public synchronized void sendDataFrame(byte[] data, int start, int length, boolean close) throws IOException { SpdyFrame oframe = spdy.getDataFrame(); // Options: // 1. wrap the byte[] data, use a separate header[], wait frame sent // -> 2 socket writes // 2. copy the data to frame byte[] -> non-blocking queue // 3. copy the data, blocking drain -> like 1, trade one copy to // avoid // 1 tcp packet. That's the current choice, seems closer to rest of // tomcat if (close) oframe.halfClose(); oframe.append(data, start, length); spdy.send(oframe, this); }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public void send() throws IOException { send("http", "GET"); }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public void send(String host, String url, String scheme, String method) throws IOException { getRequest().addHeader("host", host); getRequest().addHeader("url", url); send(scheme, method); }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public void send(String scheme, String method) throws IOException { getRequest(); if ("GET".equalsIgnoreCase(method)) { // TODO: add the others reqFrame.halfClose(); } getRequest().addHeader("scheme", "http"); // todo getRequest().addHeader("method", method); getRequest().addHeader("version", "HTTP/1.1"); if (reqFrame.isHalfClose()) { finSent = true; } spdy.send(reqFrame, this); }
// in java/org/apache/tomcat/spdy/SpdyStream.java
private void fill() throws IOException { if (current == null || current.off == current.endData) { if (current != null) { spdy.spdyContext.releaseFrame(current); } current = getFrame(to); } }
// in java/org/apache/tomcat/spdy/SpdyStream.java
Override public int read() throws IOException { fill(); if (current == null) { return -1; } return current.readByte(); }
// in java/org/apache/tomcat/spdy/SpdyStream.java
Override public int read(byte b[], int off, int len) throws IOException { fill(); if (current == null) { return -1; } // don't wait for next frame int rd = Math.min(len, current.endData - current.off); System.arraycopy(current.data, current.off, b, off, rd); current.off += rd; return rd; }
// in java/org/apache/tomcat/spdy/SpdyStream.java
Override public int available() throws IOException { return 0; }
// in java/org/apache/tomcat/spdy/SpdyStream.java
Override public void close() throws IOException { // send RST if not closed }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
public void nonBlockingSend(SpdyFrame oframe, SpdyStream proc) throws IOException { queueFrame(oframe, proc, oframe.pri == 0 ? outQueue : prioriyQueue); getSpdyContext().getExecutor().execute(nbDrain); }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
public void send(SpdyFrame oframe, SpdyStream proc) throws IOException { queueFrame(oframe, proc, oframe.pri == 0 ? outQueue : prioriyQueue); drain(); }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
private void queueFrame(SpdyFrame oframe, SpdyStream proc, LinkedList<SpdyFrame> queue) throws IOException { oframe.endData = oframe.off; oframe.off = 0; // We can't assing a stream ID until it is sent - priorities // we can't compress either - it's stateful. oframe.stream = proc; // all sync for adding/removing is on outQueue synchronized (outQueue) { queue.add(oframe); } }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
public int processInput() throws IOException { while (true) { if (inFrame == null) { inFrame = getSpdyContext().getFrame(); } if (inFrame.data == null) { inFrame.data = new byte[16 * 1024]; } // we might already have data from previous frame if (inFrame.endReadData < 8 || // we don't have the header inFrame.endReadData < inFrame.endData) { int rd = read(inFrame.data, inFrame.endReadData, inFrame.data.length - inFrame.endReadData); if (rd == -1) { if (channels.size() == 0) { return CLOSE; } else { abort("Closed"); } } else if (rd < 0) { abort("Closed - read error"); return CLOSE; } else if (rd == 0) { return LONG; // Non-blocking channel - will resume reading at off } inFrame.endReadData += rd; } if (inFrame.endReadData < 8) { continue; // keep reading } if (inFrame.endData == 0) { inFrame.parse(); if (inFrame.version != 2) { abort("Wrong version"); return CLOSE; } // MAX_FRAME_SIZE if (inFrame.endData < 0 || inFrame.endData > 32000) { abort("Framing error, size = " + inFrame.endData); return CLOSE; } // TODO: if data, split it in 2 frames // grow the buffer if needed. if (inFrame.data.length < inFrame.endData) { byte[] tmp = new byte[inFrame.endData]; System.arraycopy(inFrame.data, 0, tmp, 0, inFrame.endReadData); inFrame.data = tmp; } } if (inFrame.endReadData < inFrame.endData) { continue; // keep reading to fill current frame } // else: we have at least the current frame int extra = inFrame.endReadData - inFrame.endData; if (extra > 0) { // and a bit more - to keep things simple for now we // copy them to next frame, at least we saved reads. // it is possible to avoid copy - but later. nextFrame = getSpdyContext().getFrame(); nextFrame.makeSpace(extra); System.arraycopy(inFrame.data, inFrame.endData, nextFrame.data, 0, extra); nextFrame.endReadData = extra; inFrame.endReadData = inFrame.endData; } // decompress if (inFrame.type == TYPE_SYN_STREAM) { inFrame.streamId = inFrame.readInt(); // 4 lastChannel = inFrame.streamId; inFrame.associated = inFrame.readInt(); // 8 inFrame.pri = inFrame.read16(); // 10 pri and unused if (compressSupport != null) { compressSupport.decompress(inFrame, 18); } inFrame.nvCount = inFrame.read16(); } else if (inFrame.type == TYPE_SYN_REPLY || inFrame.type == TYPE_HEADERS) { inFrame.streamId = inFrame.readInt(); // 4 inFrame.read16(); if (compressSupport != null) { compressSupport.decompress(inFrame, 14); } inFrame.nvCount = inFrame.read16(); } if (SpdyContext.debug) { trace("< " + inFrame); } try { int state = handleFrame(); if (state == CLOSE) { return state; } } catch (Throwable t) { abort("Error handling frame"); t.printStackTrace(); return CLOSE; } if (inFrame != null) { inFrame.recyle(); if (nextFrame != null) { getSpdyContext().releaseFrame(inFrame); inFrame = nextFrame; nextFrame = null; } } else { inFrame = nextFrame; nextFrame = null; if (inFrame == null) { inFrame = getSpdyContext().getFrame(); } } } }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
protected int handleFrame() throws IOException { if (inFrame.c) { switch (inFrame.type) { case TYPE_SETTINGS: { int cnt = inFrame.readInt(); for (int i = 0; i < cnt; i++) { int flag = inFrame.readByte(); int id = inFrame.read24(); int value = inFrame.readInt(); } // TODO: save/interpret settings break; } case TYPE_GOAWAY: { int lastStream = inFrame.readInt(); log.info("GOAWAY last=" + lastStream); // Server will shut down - but will keep processing the current requests, // up to lastStream. If we sent any new ones - they need to be canceled. abort("GO_AWAY", lastStream); goAway = lastStream; return CLOSE; } case TYPE_RST_STREAM: { inFrame.streamId = inFrame.read32(); int errCode = inFrame.read32(); if (SpdyContext.debug) { trace("> RST " + inFrame.streamId + " " + ((errCode < RST_ERRORS.length) ? RST_ERRORS[errCode] : errCode)); } SpdyStream sch; synchronized(channels) { sch = channels.remove(inFrame.streamId); } // if RST stream is for a closed channel - we can ignore. if (sch != null) { sch.onReset(); } inFrame = null; break; } case TYPE_SYN_STREAM: { SpdyStream ch = getSpdyContext().getStream(this); synchronized (channels) { channels.put(inFrame.streamId, ch); } try { ch.onCtlFrame(inFrame); inFrame = null; } catch (Throwable t) { log.log(Level.SEVERE, "Error parsing head SYN_STREAM", t); abort("Error reading headers " + t); return CLOSE; } spdyContext.onStream(this, ch); break; } case TYPE_SYN_REPLY: { SpdyStream sch; synchronized(channels) { sch = channels.get(inFrame.streamId); } if (sch == null) { abort("Missing channel"); return CLOSE; } try { sch.onCtlFrame(inFrame); inFrame = null; } catch (Throwable t) { log.info("Error parsing head SYN_STREAM" + t); abort("Error reading headers " + t); return CLOSE; } break; } case TYPE_PING: { SpdyFrame oframe = getSpdyContext().getFrame(); oframe.type = TYPE_PING; oframe.c = true; oframe.append32(inFrame.read32()); oframe.pri = 0x80; send(oframe, null); break; } } } else { // Data frame SpdyStream sch; synchronized (channels) { sch = channels.get(inFrame.streamId); } if (sch == null) { abort("Missing channel"); return CLOSE; } sch.onDataFrame(inFrame); synchronized (channels) { if (sch.finRcvd && sch.finSent) { channels.remove(inFrame.streamId); } } inFrame = null; } return LONG; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
public SpdyStream get(String host, String url) throws IOException { SpdyStream sch = new SpdyStream(this); sch.getRequest().addHeader("host", host); sch.getRequest().addHeader("url", url); sch.send(); return sch; }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public SpdyConnection getConnection(String host, int port) throws IOException { SpdyConnectionAprSocket spdy = new SpdyConnectionAprSocket(ctx); AprSocket ch = con.socket(host, port, ctx.tls); spdy.setSocket(ch); ch.connect(); ch.setHandler(new SpdySocketHandler(spdy)); // need to consume the input to receive more read events int rc = spdy.processInput(); if (rc == SpdyConnection.CLOSE) { ch.close(); throw new IOException("Error connecting"); } return spdy; }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public void onAccept(Object socket) throws IOException { onAcceptLong((Long) socket); }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
public void onAcceptLong(long socket) throws IOException { SpdyConnectionAprSocket spdy = new SpdyConnectionAprSocket(ctx); AprSocket s = con.socket(socket); spdy.setSocket(s); SpdySocketHandler handler = new SpdySocketHandler(spdy); s.setHandler(handler); handler.process(s, true, true, false); }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public void listen(final int port, String cert, String key) throws IOException { con = new AprSocketContext() { @Override protected void onSocket(AprSocket s) throws IOException { SpdyConnectionAprSocket spdy = new SpdyConnectionAprSocket(ctx); spdy.setSocket(s); SpdySocketHandler handler = new SpdySocketHandler(spdy); s.setHandler(handler); } }; con.setNpn(SpdyContext.SPDY_NPN_OUT); con.setKeys(cert, key); con.listen(port); }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override protected void onSocket(AprSocket s) throws IOException { SpdyConnectionAprSocket spdy = new SpdyConnectionAprSocket(ctx); spdy.setSocket(s); SpdySocketHandler handler = new SpdySocketHandler(spdy); s.setHandler(handler); }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public void stop() throws IOException { con.stop(); }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public void close() throws IOException { socket.close(); }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public int write(byte[] data, int off, int len) throws IOException { if (socket == null) { return -1; } int sent = socket.write(data, off, len); if (sent < 0) { return -1; } return sent; }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public int read(byte[] data, int off, int len) throws IOException { if (socket == null) { return -1; } int rd = socket.read(data, off, len); // org.apache.tomcat.jni.Socket.recv(socket, data, off, len); if (rd == -Status.APR_EOF) { return -1; } if (rd == -Status.TIMEUP || rd == -Status.EINTR || rd == -Status.EAGAIN) { rd = 0; } if (rd < 0) { return -1; } off += rd; len -= rd; return rd; }
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
Override public synchronized void compress(SpdyFrame frame, int start) throws IOException { init(); if (compressBuffer == null) { compressBuffer = new byte[frame.data.length]; } // last byte for flush ? zipOut.setInput(frame.data, start, frame.endData - start - 1); int coff = start; zipOut.setLevel(Deflater.DEFAULT_COMPRESSION); while (true) { int rd = zipOut.deflate(compressBuffer, coff, compressBuffer.length - coff); if (rd == 0) { // needsInput needs to be called - we're done with this frame ? zipOut.setInput(frame.data, frame.endData - 1, 1); zipOut.setLevel(Deflater.BEST_SPEED); while (true) { rd = zipOut.deflate(compressBuffer, coff, compressBuffer.length - coff); coff += rd; if (rd == 0) { break; } byte[] b = new byte[compressBuffer.length * 2]; System.arraycopy(compressBuffer, 0, b, 0, coff); compressBuffer = b; } zipOut.setLevel(Deflater.DEFAULT_COMPRESSION); break; } coff += rd; } byte[] tmp = frame.data; frame.data = compressBuffer; compressBuffer = tmp; frame.endData = coff; }
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
Override public synchronized void decompress(SpdyFrame frame, int start) throws IOException { // stream id ( 4 ) + unused ( 2 ) // nvCount is compressed in impl - spec is different init(); if (decompressBuffer == null) { decompressBuffer = new byte[frame.data.length]; } // will read from dec buffer to frame.data decMax = frame.endData; decOff = start; int off = start; zipIn.setInput(frame.data, start, decMax - start); while (true) { int rd; try { rd = zipIn.inflate(decompressBuffer, off, decompressBuffer.length - off); if (rd == 0 && zipIn.needsDictionary()) { zipIn.setDictionary(SPDY_DICT); continue; } } catch (DataFormatException e) { throw new IOException(e); } if (rd == 0) { break; } if (rd == -1) { break; } off += rd; byte[] b = new byte[decompressBuffer.length * 2]; System.arraycopy(decompressBuffer, 0, b, 0, off); decompressBuffer = b; } byte[] tmpBuf = decompressBuffer; decompressBuffer = frame.data; frame.data = tmpBuf; frame.off = start; frame.endData = off; }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
Override public SpdyConnection getConnection(String host, int port) throws IOException { try { Socket sock = getSocket(host, port); sock.getInputStream(); SpdyConnectionSocket con = new SpdyConnectionSocket(ctx, sock); ctx.getExecutor().execute(con.inputThread); return con; } catch (IOException ex) { ex.printStackTrace(); throw ex; } }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
protected Socket getSocket(String host, int port) throws IOException { try { if (ctx.tls) { SSLContext sslCtx = SSLContext.getDefault(); SSLSocket socket = (SSLSocket) sslCtx.getSocketFactory().createSocket(host, port); //socket.setEnabledProtocols(new String[] {"TLS1"}); socket.startHandshake(); return socket; } else { return new Socket(host, port); } } catch (NoSuchAlgorithmException e) { throw new IOException(e); } }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
Override public void stop() throws IOException { running = false; serverSocket.close(); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
Override public void listen(final int port, String cert, String key) throws IOException { ctx.getExecutor().execute(new Runnable() { @Override public void run() { accept(port); } }); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
Override public void close() throws IOException { socket.close(); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
Override public synchronized int write(byte[] data, int off, int len) throws IOException { socket.getOutputStream().write(data, off, len); return len; }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
Override public int read(byte[] data, int off, int len) throws IOException { try { return socket.getInputStream().read(data, off, len); } catch (SocketTimeoutException ex) { return 0; } }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public void onAccept(Object socket) throws IOException { }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public void listen(int port, String cert, String key) throws IOException { }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public void stop() throws IOException { }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public SpdyConnection getConnection(String host, int port) throws IOException { return netSupport.getConnection(host, port); }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public final void listen(final int port, String cert, String key) throws IOException { netSupport.listen(port, cert, key); }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public final void stop() throws IOException { netSupport.stop(); }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public void onStream(SpdyConnection spdyConnection, SpdyStream ch) throws IOException { if (handler instanceof NonBlockingSpdyHandler) { handler.onStream(spdyConnection, ch); } else { getExecutor().execute(ch); } }
// in java/org/apache/tomcat/util/net/NioChannel.java
public void reset() throws IOException { bufHandler.getReadBuffer().clear(); bufHandler.getWriteBuffer().clear(); this.sendFile = false; }
// in java/org/apache/tomcat/util/net/NioChannel.java
public boolean flush(boolean block, Selector s, long timeout) throws IOException { return true; }
// in java/org/apache/tomcat/util/net/NioChannel.java
Override public void close() throws IOException { getIOChannel().socket().close(); getIOChannel().close(); }
// in java/org/apache/tomcat/util/net/NioChannel.java
public void close(boolean force) throws IOException { if (isOpen() || force ) close(); }
// in java/org/apache/tomcat/util/net/NioChannel.java
Override public int write(ByteBuffer src) throws IOException { return sc.write(src); }
// in java/org/apache/tomcat/util/net/NioChannel.java
Override public int read(ByteBuffer dst) throws IOException { return sc.read(dst); }
// in java/org/apache/tomcat/util/net/NioChannel.java
public int handshake(boolean read, boolean write) throws IOException { return 0; }
// in java/org/apache/tomcat/util/net/NioChannel.java
public boolean flushOutbound() throws IOException { return false; }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
public void reset(SSLEngine engine) throws IOException { this.sslEngine = engine; reset(); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public void reset() throws IOException { super.reset(); netOutBuffer.position(0); netOutBuffer.limit(0); netInBuffer.position(0); netInBuffer.limit(0); handshakeComplete = false; closed = false; closing = false; //initiate handshake sslEngine.beginHandshake(); handshakeStatus = sslEngine.getHandshakeStatus(); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public boolean flush(boolean block, Selector s, long timeout) throws IOException { if (!block) { flush(netOutBuffer); } else { pool.write(netOutBuffer, this, s, timeout,block); } return !netOutBuffer.hasRemaining(); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
protected boolean flush(ByteBuffer buf) throws IOException { int remaining = buf.remaining(); if ( remaining > 0 ) { int written = sc.write(buf); return written >= remaining; }else { return true; } }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int handshake(boolean read, boolean write) throws IOException { if ( handshakeComplete ) return 0; //we have done our initial handshake if (!flush(netOutBuffer)) return SelectionKey.OP_WRITE; //we still have data to write SSLEngineResult handshake = null; while (!handshakeComplete) { switch ( handshakeStatus ) { case NOT_HANDSHAKING: { //should never happen throw new IOException("NOT_HANDSHAKING during handshake"); } case FINISHED: { //we are complete if we have delivered the last package handshakeComplete = !netOutBuffer.hasRemaining(); //return 0 if we are complete, otherwise we still have data to write return handshakeComplete?0:SelectionKey.OP_WRITE; } case NEED_WRAP: { //perform the wrap function handshake = handshakeWrap(write); if ( handshake.getStatus() == Status.OK ){ if (handshakeStatus == HandshakeStatus.NEED_TASK) handshakeStatus = tasks(); } else { //wrap should always work with our buffers throw new IOException("Unexpected status:" + handshake.getStatus() + " during handshake WRAP."); } if ( handshakeStatus != HandshakeStatus.NEED_UNWRAP || (!flush(netOutBuffer)) ) { //should actually return OP_READ if we have NEED_UNWRAP return SelectionKey.OP_WRITE; } //fall down to NEED_UNWRAP on the same call, will result in a //BUFFER_UNDERFLOW if it needs data } //$FALL-THROUGH$ case NEED_UNWRAP: { //perform the unwrap function handshake = handshakeUnwrap(read); if ( handshake.getStatus() == Status.OK ) { if (handshakeStatus == HandshakeStatus.NEED_TASK) handshakeStatus = tasks(); } else if ( handshake.getStatus() == Status.BUFFER_UNDERFLOW ){ //read more data, reregister for OP_READ return SelectionKey.OP_READ; } else { throw new IOException("Invalid handshake status:"+handshakeStatus+" during handshake UNWRAP."); }//switch break; } case NEED_TASK: { handshakeStatus = tasks(); break; } default: throw new IllegalStateException("Invalid handshake status:"+handshakeStatus); }//switch }//while //return 0 if we are complete, otherwise reregister for any activity that //would cause this method to be called again. return handshakeComplete?0:(SelectionKey.OP_WRITE|SelectionKey.OP_READ); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
protected SSLEngineResult handshakeWrap(boolean doWrite) throws IOException { //this should never be called with a network buffer that contains data //so we can clear it here. netOutBuffer.clear(); //perform the wrap SSLEngineResult result = sslEngine.wrap(bufHandler.getWriteBuffer(), netOutBuffer); //prepare the results to be written netOutBuffer.flip(); //set the status handshakeStatus = result.getHandshakeStatus(); //optimization, if we do have a writable channel, write it now if ( doWrite ) flush(netOutBuffer); return result; }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
protected SSLEngineResult handshakeUnwrap(boolean doread) throws IOException { if (netInBuffer.position() == netInBuffer.limit()) { //clear the buffer if we have emptied it out on data netInBuffer.clear(); } if ( doread ) { //if we have data to read, read it int read = sc.read(netInBuffer); if (read == -1) throw new IOException("EOF encountered during handshake."); } SSLEngineResult result; boolean cont = false; //loop while we can perform pure SSLEngine data do { //prepare the buffer with the incoming data netInBuffer.flip(); //call unwrap result = sslEngine.unwrap(netInBuffer, bufHandler.getReadBuffer()); //compact the buffer, this is an optional method, wonder what would happen if we didn't netInBuffer.compact(); //read in the status handshakeStatus = result.getHandshakeStatus(); if ( result.getStatus() == SSLEngineResult.Status.OK && result.getHandshakeStatus() == HandshakeStatus.NEED_TASK ) { //execute tasks if we need to handshakeStatus = tasks(); } //perform another unwrap? cont = result.getStatus() == SSLEngineResult.Status.OK && handshakeStatus == HandshakeStatus.NEED_UNWRAP; }while ( cont ); return result; }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public void close() throws IOException { if (closing) return; closing = true; sslEngine.closeOutbound(); if (!flush(netOutBuffer)) { throw new IOException("Remaining data in the network buffer, can't send SSL close message, force a close with close(true) instead"); } //prep the buffer for the close message netOutBuffer.clear(); //perform the close, since we called sslEngine.closeOutbound SSLEngineResult handshake = sslEngine.wrap(getEmptyBuf(), netOutBuffer); //we should be in a close state if (handshake.getStatus() != SSLEngineResult.Status.CLOSED) { throw new IOException("Invalid close state, will not send network data."); } //prepare the buffer for writing netOutBuffer.flip(); //if there is data to be written flush(netOutBuffer); //is the channel closed? closed = (!netOutBuffer.hasRemaining() && (handshake.getHandshakeStatus() != HandshakeStatus.NEED_WRAP)); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public void close(boolean force) throws IOException { try { close(); }finally { if ( force || closed ) { closed = true; sc.socket().close(); sc.close(); } } }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int read(ByteBuffer dst) throws IOException { //if we want to take advantage of the expand function, make sure we only use the ApplicationBufferHandler's buffers if ( dst != bufHandler.getReadBuffer() ) throw new IllegalArgumentException("You can only read using the application read buffer provided by the handler."); //are we in the middle of closing or closed? if ( closing || closed) return -1; //did we finish our handshake? if (!handshakeComplete) throw new IllegalStateException("Handshake incomplete, you must complete handshake before reading data."); //read from the network int netread = sc.read(netInBuffer); //did we reach EOF? if so send EOF up one layer. if (netread == -1) return -1; //the data read int read = 0; //the SSL engine result SSLEngineResult unwrap; do { //prepare the buffer netInBuffer.flip(); //unwrap the data unwrap = sslEngine.unwrap(netInBuffer, dst); //compact the buffer netInBuffer.compact(); if ( unwrap.getStatus()==Status.OK || unwrap.getStatus()==Status.BUFFER_UNDERFLOW ) { //we did receive some data, add it to our total read += unwrap.bytesProduced(); //perform any tasks if needed if (unwrap.getHandshakeStatus() == HandshakeStatus.NEED_TASK) tasks(); //if we need more network data, then bail out for now. if ( unwrap.getStatus() == Status.BUFFER_UNDERFLOW ) break; }else if ( unwrap.getStatus()==Status.BUFFER_OVERFLOW && read>0 ) { //buffer overflow can happen, if we have read data, then //empty out the dst buffer before we do another read break; }else { //here we should trap BUFFER_OVERFLOW and call expand on the buffer //for now, throw an exception, as we initialized the buffers //in the constructor throw new IOException("Unable to unwrap data, invalid status: " + unwrap.getStatus()); } } while ( (netInBuffer.position() != 0)); //continue to unwrapping as long as the input buffer has stuff return (read); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int write(ByteBuffer src) throws IOException { if ( src == this.netOutBuffer ) { //we can get here through a recursive call //by using the NioBlockingSelector int written = sc.write(src); return written; } else { //make sure we can handle expand, and that we only use on buffer if ( (!this.isSendFile()) && (src != bufHandler.getWriteBuffer()) ) throw new IllegalArgumentException("You can only write using the application write buffer provided by the handler."); //are we closing or closed? if ( closing || closed) throw new IOException("Channel is in closing state."); //the number of bytes written int written = 0; if (!flush(netOutBuffer)) { //we haven't emptied out the buffer yet return written; } /* * The data buffer is empty, we can reuse the entire buffer. */ netOutBuffer.clear(); SSLEngineResult result = sslEngine.wrap(src, netOutBuffer); written = result.bytesConsumed(); netOutBuffer.flip(); if (result.getStatus() == Status.OK) { if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) tasks(); } else { throw new IOException("Unable to wrap data, invalid engine state: " +result.getStatus()); } //force a flush flush(netOutBuffer); return written; } }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public boolean flushOutbound() throws IOException { int remaining = netOutBuffer.remaining(); flush(netOutBuffer); int remaining2= netOutBuffer.remaining(); return remaining2 < remaining; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int write(ByteBuffer buf, NioChannel socket, long writeTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int written = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) && buf.hasRemaining()) { if (keycount > 0) { //only write if we were registered for a write int cnt = socket.write(buf); //write the data if (cnt == -1) throw new EOFException(); written += cnt; if (cnt > 0) { time = System.currentTimeMillis(); //reset our timeout timer continue; //we successfully wrote, try again without a selector } } try { if ( att.getWriteLatch()==null || att.getWriteLatch().getCount()==0) att.startWriteLatch(1); poller.add(att,SelectionKey.OP_WRITE,reference); if (writeTimeout < 0) { att.awaitWriteLatch(Long.MAX_VALUE,TimeUnit.MILLISECONDS); } else { att.awaitWriteLatch(writeTimeout,TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getWriteLatch()!=null && att.getWriteLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetWriteLatch(); } if (writeTimeout > 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= writeTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_WRITE); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return written; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int read(ByteBuffer buf, NioChannel socket, long readTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int read = 0; boolean timedout = false; int keycount = 1; //assume we can read long time = System.currentTimeMillis(); //start the timeout timer try { while(!timedout) { if (keycount > 0) { //only read if we were registered for a read read = socket.read(buf); if (read == -1) throw new EOFException(); if (read > 0) break; } try { if ( att.getReadLatch()==null || att.getReadLatch().getCount()==0) att.startReadLatch(1); poller.add(att,SelectionKey.OP_READ, reference); if (readTimeout < 0) { att.awaitReadLatch(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } else { att.awaitReadLatch(readTimeout, TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getReadLatch()!=null && att.getReadLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetReadLatch(); } if (readTimeout >= 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= readTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_READ); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return read; }
// in java/org/apache/tomcat/util/net/DefaultServerSocketFactory.java
Override public ServerSocket createSocket (int port) throws IOException { return new ServerSocket (port); }
// in java/org/apache/tomcat/util/net/DefaultServerSocketFactory.java
Override public ServerSocket createSocket (int port, int backlog) throws IOException { return new ServerSocket (port, backlog); }
// in java/org/apache/tomcat/util/net/DefaultServerSocketFactory.java
Override public ServerSocket createSocket (int port, int backlog, InetAddress ifAddress) throws IOException { return new ServerSocket (port, backlog, ifAddress); }
// in java/org/apache/tomcat/util/net/DefaultServerSocketFactory.java
Override public Socket acceptSocket(ServerSocket socket) throws IOException { return socket.accept(); }
// in java/org/apache/tomcat/util/net/DefaultServerSocketFactory.java
Override public void handshake(Socket sock) throws IOException { // NOOP }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
Override public String getCipherSuite() throws IOException { // Look up the current SSLSession if (session == null) return null; return session.getCipherSuite(); }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
Override public Object[] getPeerCertificateChain() throws IOException { return getPeerCertificateChain(false); }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
Override public Object[] getPeerCertificateChain(boolean force) throws IOException { // Look up the current SSLSession if (session == null) return null; // Convert JSSE's certificate format to the ones we need X509Certificate [] jsseCerts = null; try { jsseCerts = session.getPeerCertificateChain(); } catch(Exception bex) { // ignore. } if (jsseCerts == null) jsseCerts = new X509Certificate[0]; if(jsseCerts.length <= 0 && force && ssl != null) { session.invalidate(); handShake(); session = ssl.getSession(); } return getX509Certificates(session); }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
protected void handShake() throws IOException { if( ssl.getWantClientAuth() ) { log.debug(sm.getString("jsseSupport.noCertWant")); } else { ssl.setNeedClientAuth(true); } if (ssl.getEnabledCipherSuites().length == 0) { // Handshake is never going to be successful. // Assume this is because handshakes are disabled log.warn(sm.getString("jsseSupport.serverRenegDisabled")); session.invalidate(); ssl.close(); return; } InputStream in = ssl.getInputStream(); int oldTimeout = ssl.getSoTimeout(); ssl.setSoTimeout(1000); byte[] b = new byte[1]; listener.reset(); ssl.startHandshake(); int maxTries = 60; // 60 * 1000 = example 1 minute time out for (int i = 0; i < maxTries; i++) { if (log.isTraceEnabled()) log.trace("Reading for try #" + i); try { int read = in.read(b); if (read > 0) { // Shouldn't happen as all input should have been swallowed // before trying to do the handshake. If it does, something // went wrong so lets bomb out now. throw new SSLException( sm.getString("jsseSupport.unexpectedData")); } } catch(SSLException sslex) { log.info(sm.getString("jsseSupport.clientCertError"), sslex); throw sslex; } catch (IOException e) { // ignore - presumably the timeout } if (listener.completed) { break; } } ssl.setSoTimeout(oldTimeout); if (listener.completed == false) { throw new SocketException("SSL Cert handshake timeout"); } }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
Override public Integer getKeySize() throws IOException { // Look up the current SSLSession SSLSupport.CipherData c_aux[]=ciphers; if (session == null) return null; Integer keySize = null; synchronized(keySizeCache) { keySize = keySizeCache.get(session); } if (keySize == null) { int size = 0; String cipherSuite = session.getCipherSuite(); for (int i = 0; i < c_aux.length; i++) { if (cipherSuite.indexOf(c_aux[i].phrase) >= 0) { size = c_aux[i].keySize; break; } } keySize = Integer.valueOf(size); synchronized(keySizeCache) { keySizeCache.put(session, keySize); } } return keySize; }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
Override public String getSessionId() throws IOException { // Look up the current SSLSession if (session == null) return null; // Expose ssl_session (getId) byte [] ssl_session = session.getId(); if ( ssl_session == null) return null; StringBuilder buf=new StringBuilder(); for(int x=0; x<ssl_session.length; x++) { String digit=Integer.toHexString(ssl_session[x]); if (digit.length()<2) buf.append('0'); if (digit.length()>2) digit=digit.substring(digit.length()-2); buf.append(digit); } return buf.toString(); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public ServerSocket createSocket (int port) throws IOException { init(); ServerSocket socket = sslProxy.createServerSocket(port); initServerSocket(socket); return socket; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public ServerSocket createSocket (int port, int backlog) throws IOException { init(); ServerSocket socket = sslProxy.createServerSocket(port, backlog); initServerSocket(socket); return socket; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public ServerSocket createSocket (int port, int backlog, InetAddress ifAddress) throws IOException { init(); ServerSocket socket = sslProxy.createServerSocket(port, backlog, ifAddress); initServerSocket(socket); return socket; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public Socket acceptSocket(ServerSocket socket) throws IOException { SSLSocket asock = null; try { asock = (SSLSocket)socket.accept(); } catch (SSLException e){ throw new SocketException("SSL handshake error" + e.toString()); } return asock; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public void handshake(Socket sock) throws IOException { // We do getSession instead of startHandshake() so we can call this multiple times SSLSession session = ((SSLSocket)sock).getSession(); if (session.getCipherSuite().equals("SSL_NULL_WITH_NULL_NULL")) throw new IOException("SSL handshake failed. Ciper suite in SSL Session is SSL_NULL_WITH_NULL_NULL"); if (!allowUnsafeLegacyRenegotiation && !RFC_5746_SUPPORTED) { // Prevent further handshakes by removing all cipher suites ((SSLSocket) sock).setEnabledCipherSuites(new String[0]); } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected KeyStore getKeystore(String type, String provider, String pass) throws IOException { String keystoreFile = endpoint.getKeystoreFile(); if (keystoreFile == null) keystoreFile = defaultKeystoreFile; return getStore(type, provider, keystoreFile, pass); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected KeyStore getTrustStore(String keystoreType, String keystoreProvider) throws IOException { KeyStore trustStore = null; String truststoreFile = endpoint.getTruststoreFile(); if(truststoreFile == null) { truststoreFile = System.getProperty("javax.net.ssl.trustStore"); } if(log.isDebugEnabled()) { log.debug("Truststore = " + truststoreFile); } String truststorePassword = endpoint.getTruststorePass(); if( truststorePassword == null) { truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword"); } if(log.isDebugEnabled()) { log.debug("TrustPass = " + truststorePassword); } String truststoreType = endpoint.getTruststoreType(); if( truststoreType == null) { truststoreType = System.getProperty("javax.net.ssl.trustStoreType"); } if(truststoreType == null) { truststoreType = keystoreType; } if(log.isDebugEnabled()) { log.debug("trustType = " + truststoreType); } String truststoreProvider = endpoint.getTruststoreProvider(); if( truststoreProvider == null) { truststoreProvider = System.getProperty("javax.net.ssl.trustStoreProvider"); } if (truststoreProvider == null) { truststoreProvider = keystoreProvider; } if(log.isDebugEnabled()) { log.debug("trustProvider = " + truststoreProvider); } if (truststoreFile != null){ try { trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, truststorePassword); } catch (IOException ioe) { Throwable cause = ioe.getCause(); if (cause instanceof UnrecoverableKeyException) { // Log a warning we had a password issue log.warn(sm.getString("jsse.invalid_truststore_password"), cause); // Re-try trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, null); } else { // Something else went wrong - re-throw throw ioe; } } } return trustStore; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
private KeyStore getStore(String type, String provider, String path, String pass) throws IOException { KeyStore ks = null; InputStream istream = null; try { if (provider == null) { ks = KeyStore.getInstance(type); } else { ks = KeyStore.getInstance(type, provider); } if(!("PKCS11".equalsIgnoreCase(type) || "".equalsIgnoreCase(path))) { File keyStoreFile = new File(path); if (!keyStoreFile.isAbsolute()) { keyStoreFile = new File(System.getProperty( Constants.CATALINA_BASE_PROP), path); } istream = new FileInputStream(keyStoreFile); } char[] storePass = null; if (pass != null && !"".equals(pass)) { storePass = pass.toCharArray(); } ks.load(istream, storePass); } catch (FileNotFoundException fnfe) { log.error(sm.getString("jsse.keystore_load_failed", type, path, fnfe.getMessage()), fnfe); throw fnfe; } catch (IOException ioe) { // May be expected when working with a trust store // Re-throw. Caller will catch and log as required throw ioe; } catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); } finally { if (istream != null) { try { istream.close(); } catch (IOException ioe) { // Do nothing } } } return ks; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
void init() throws IOException { try { String clientAuthStr = endpoint.getClientAuth(); if("true".equalsIgnoreCase(clientAuthStr) || "yes".equalsIgnoreCase(clientAuthStr)) { requireClientAuth = true; } else if("want".equalsIgnoreCase(clientAuthStr)) { wantClientAuth = true; } SSLContext context = createSSLContext(); context.init(getKeyManagers(), getTrustManagers(), null); // Configure SSL session cache SSLSessionContext sessionContext = context.getServerSessionContext(); if (sessionContext != null) { configureSessionContext(sessionContext); } // create proxy sslProxy = context.getServerSocketFactory(); // Determine which cipher suites to enable String requestedCiphers = endpoint.getCiphers(); enabledCiphers = getEnabledCiphers(requestedCiphers, sslProxy.getSupportedCipherSuites()); allowUnsafeLegacyRenegotiation = "true".equals( endpoint.getAllowUnsafeLegacyRenegotiation()); // Check the SSL config is OK checkConfig(); } catch(Exception e) { if( e instanceof IOException ) throw (IOException)e; throw new IOException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected Collection<? extends CRL> getCRLs(String crlf) throws IOException, CRLException, CertificateException { File crlFile = new File(crlf); if( !crlFile.isAbsolute() ) { crlFile = new File( System.getProperty(Constants.CATALINA_BASE_PROP), crlf); } Collection<? extends CRL> crls = null; InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlFile); crls = cf.generateCRLs(is); } catch(IOException iex) { throw iex; } catch(CRLException crle) { throw crle; } catch(CertificateException ce) { throw ce; } finally { if(is != null) { try{ is.close(); } catch(Exception ex) { // Ignore } } } return crls; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
private void checkConfig() throws IOException { // Create an unbound server socket ServerSocket socket = sslProxy.createServerSocket(); initServerSocket(socket); try { // Set the timeout to 1ms as all we care about is if it throws an // SSLException on accept. socket.setSoTimeout(1); socket.accept(); // Will never get here - no client can connect to an unbound port } catch (SSLException ssle) { // SSL configuration is invalid. Possibly cert doesn't match ciphers IOException ioe = new IOException(sm.getString( "jsse.invalid_ssl_conf", ssle.getMessage())); ioe.initCause(ssle); throw ioe; } catch (Exception e) { /* * Possible ways of getting here * socket.accept() throws a SecurityException * socket.setSoTimeout() throws a SocketException * socket.accept() throws some other exception (after a JDK change) * In these cases the test won't work so carry on - essentially * the behaviour before this patch * socket.accept() throws a SocketTimeoutException * In this case all is well so carry on */ } finally { // Should be open here but just in case if (!socket.isClosed()) { socket.close(); } } }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
protected Selector getSharedSelector() throws IOException { if (SHARED && SHARED_SELECTOR == null) { synchronized ( NioSelectorPool.class ) { if ( SHARED_SELECTOR == null ) { synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 SHARED_SELECTOR = Selector.open(); } log.info("Using a shared selector for servlet write/read"); } }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public Selector get() throws IOException{ if ( SHARED ) { return getSharedSelector(); } if ( (!enabled) || active.incrementAndGet() >= maxSelectors ) { if ( enabled ) active.decrementAndGet(); return null; } Selector s = null; try { s = selectors.size()>0?selectors.poll():null; if (s == null) { synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 s = Selector.open(); } } else spare.decrementAndGet(); }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public void put(Selector s) throws IOException { if ( SHARED ) return; if ( enabled ) active.decrementAndGet(); if ( enabled && (maxSpareSelectors==-1 || spare.get() < Math.min(maxSpareSelectors,maxSelectors)) ) { spare.incrementAndGet(); selectors.offer(s); } else s.close(); }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public void close() throws IOException { enabled = false; Selector s; while ( (s = selectors.poll()) != null ) s.close(); spare.set(0); active.set(0); if (blockingSelector!=null) { blockingSelector.close(); } if ( SHARED && getSharedSelector()!=null ) { getSharedSelector().close(); SHARED_SELECTOR = null; } }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public void open() throws IOException { enabled = true; getSharedSelector(); if (SHARED) { blockingSelector = new NioBlockingSelector(); blockingSelector.open(getSharedSelector()); } }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int write(ByteBuffer buf, NioChannel socket, Selector selector, long writeTimeout) throws IOException { return write(buf,socket,selector,writeTimeout,true); }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int write(ByteBuffer buf, NioChannel socket, Selector selector, long writeTimeout, boolean block) throws IOException { if ( SHARED && block ) { return blockingSelector.write(buf,socket,writeTimeout); } SelectionKey key = null; int written = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) && buf.hasRemaining() ) { int cnt = 0; if ( keycount > 0 ) { //only write if we were registered for a write cnt = socket.write(buf); //write the data if (cnt == -1) throw new EOFException(); written += cnt; if (cnt > 0) { time = System.currentTimeMillis(); //reset our timeout timer continue; //we successfully wrote, try again without a selector } if (cnt==0 && (!block)) break; //don't block } if ( selector != null ) { //register OP_WRITE to the selector if (key==null) key = socket.getIOChannel().register(selector, SelectionKey.OP_WRITE); else key.interestOps(SelectionKey.OP_WRITE); keycount = selector.select(writeTimeout); } if (writeTimeout > 0 && (selector == null || keycount == 0) ) timedout = (System.currentTimeMillis()-time)>=writeTimeout; }//while if ( timedout ) throw new SocketTimeoutException(); } finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } } return written; }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int read(ByteBuffer buf, NioChannel socket, Selector selector, long readTimeout) throws IOException { return read(buf,socket,selector,readTimeout,true); }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int read(ByteBuffer buf, NioChannel socket, Selector selector, long readTimeout, boolean block) throws IOException { if ( SHARED && block ) { return blockingSelector.read(buf,socket,readTimeout); } SelectionKey key = null; int read = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) ) { int cnt = 0; if ( keycount > 0 ) { //only read if we were registered for a read cnt = socket.read(buf); if (cnt == -1) throw new EOFException(); read += cnt; if (cnt > 0) continue; //read some more if (cnt==0 && (read>0 || (!block) ) ) break; //we are done reading } if ( selector != null ) {//perform a blocking read //register OP_WRITE to the selector if (key==null) key = socket.getIOChannel().register(selector, SelectionKey.OP_READ); else key.interestOps(SelectionKey.OP_READ); keycount = selector.select(readTimeout); } if (readTimeout > 0 && (selector == null || keycount == 0) ) timedout = (System.currentTimeMillis()-time)>=readTimeout; }//while if ( timedout ) throw new SocketTimeoutException(); } finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } } return read; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
public char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); tokenBegin = bufpos; return c; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
public char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; return buffer[bufpos]; } if (++bufpos >= maxNextCharInd) FillBuff(); char c = buffer[bufpos]; UpdateLineColumn(c); return c; }
// in java/org/apache/tomcat/util/http/Parameters.java
private void urlDecode(ByteChunk bc) throws IOException { if( urlDec==null ) { urlDec=new UDecoder(); } urlDec.convert(bc, true); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public byte readByte() throws IOException { // Buffer depleted ? if (head == tail) { head = 0; // Refill. tail = input.read(buffer, head, bufSize); if (tail == -1) { // No more data available. throw new IOException("No more data is available"); } if (notifier != null) { notifier.noteBytesRead(tail); } } return buffer[head++]; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public int readBodyData(OutputStream output) throws MalformedStreamException, IOException { final InputStream istream = newInputStream(); return (int) Streams.copy(istream, output, false); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public int discardBodyData() throws MalformedStreamException, IOException { return readBodyData(null); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public boolean skipPreamble() throws IOException { // First delimiter may be not preceeded with a CRLF. System.arraycopy(boundary, 2, boundary, 0, boundary.length - 2); boundaryLength = boundary.length - 2; try { // Discard all data up to the delimiter. discardBodyData(); // Read boundary - if succeeded, the stream contains an // encapsulation. return readBoundary(); } catch (MalformedStreamException e) { return false; } finally { // Restore delimiter. System.arraycopy(boundary, 0, boundary, 2, boundary.length - 2); boundaryLength = boundary.length; boundary[0] = CR; boundary[1] = LF; } }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public int available() throws IOException { if (pos == -1) { return tail - head - pad; } return pos - head; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public int read() throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (available() == 0) { if (makeAvailable() == 0) { return -1; } } ++total; int b = buffer[head++]; if (b >= 0) { return b; } return b + BYTE_POSITIVE_OFFSET; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public int read(byte[] b, int off, int len) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (len == 0) { return 0; } int res = available(); if (res == 0) { res = makeAvailable(); if (res == 0) { return -1; } } res = Math.min(res, len); System.arraycopy(buffer, head, b, off, res); head += res; total += res; return res; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public void close() throws IOException { close(false); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public void close(boolean pCloseUnderlying) throws IOException { if (closed) { return; } if (pCloseUnderlying) { closed = true; input.close(); } else { for (;;) { int av = available(); if (av == 0) { av = makeAvailable(); if (av == 0) { break; } } skip(av); } } closed = true; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public long skip(long bytes) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } int av = available(); if (av == 0) { av = makeAvailable(); if (av == 0) { return 0; } } long res = Math.min(av, bytes); head += res; return res; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
private int makeAvailable() throws IOException { if (pos != -1) { return 0; } // Move the data to the beginning of the buffer. total += tail - head - pad; System.arraycopy(buffer, tail - pad, buffer, 0, pad); // Refill buffer with new data. head = 0; tail = pad; for (;;) { int bytesRead = input.read(buffer, tail, bufSize - tail); if (bytesRead == -1) { // The last pad amount is left in the buffer. // Boundary can't be in there so signal an error // condition. final String msg = "Stream ended unexpectedly"; throw new MalformedStreamException(msg); } if (notifier != null) { notifier.noteBytesRead(bytesRead); } tail += bytesRead; findSeparator(); int av = available(); if (av > 0 || pos != -1) { return av; } } }
// in java/org/apache/tomcat/util/http/fileupload/IOUtils.java
public static int copy(InputStream input, OutputStream output) throws IOException { long count = copyLarge(input, output); if (count > Integer.MAX_VALUE) { return -1; } return (int) count; }
// in java/org/apache/tomcat/util/http/fileupload/IOUtils.java
public static long copyLarge(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; long count = 0; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
Override public InputStream getInputStream() throws IOException { if (!isInMemory()) { return new FileInputStream(dfos.getFile()); } if (cachedContent == null) { cachedContent = dfos.getData(); } return new ByteArrayInputStream(cachedContent); }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
Override public OutputStream getOutputStream() throws IOException { if (dfos == null) { File outputFile = getTempFile(); dfos = new DeferredFileOutputStream(sizeThreshold, outputFile); } return dfos; }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
private void writeObject(ObjectOutputStream out) throws IOException { // Read the data if (dfos.isInMemory()) { cachedContent = get(); } else { cachedContent = null; dfosFile = dfos.getFile(); } // write out values out.defaultWriteObject(); }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // read values in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; }
// in java/org/apache/tomcat/util/http/fileupload/servlet/ServletRequestContext.java
Override public InputStream getInputStream() throws IOException { return request.getInputStream(); }
// in java/org/apache/tomcat/util/http/fileupload/servlet/ServletFileUpload.java
public FileItemIterator getItemIterator(HttpServletRequest request) throws FileUploadException, IOException { return super.getItemIterator(new ServletRequestContext(request)); }
// in java/org/apache/tomcat/util/http/fileupload/DeferredFileOutputStream.java
Override protected OutputStream getStream() throws IOException { return currentOutputStream; }
// in java/org/apache/tomcat/util/http/fileupload/DeferredFileOutputStream.java
Override protected void thresholdReached() throws IOException { if (prefix != null) { outputFile = File.createTempFile(prefix, suffix, directory); } FileOutputStream fos = new FileOutputStream(outputFile); memoryOutputStream.writeTo(fos); currentOutputStream = fos; memoryOutputStream = null; }
// in java/org/apache/tomcat/util/http/fileupload/DeferredFileOutputStream.java
Override public void close() throws IOException { super.close(); closed = true; }
// in java/org/apache/tomcat/util/http/fileupload/DeferredFileOutputStream.java
public void writeTo(OutputStream out) throws IOException { // we may only need to check if this is closed if we are working with a file // but we should force the habit of closing wether we are working with // a file or memory. if (!closed) { throw new IOException("Stream not closed"); } if(isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
public FileItemIterator getItemIterator(RequestContext ctx) throws FileUploadException, IOException { return new FileItemIteratorImpl(ctx); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override protected void raiseError(long pSizeMax, long pCount) throws IOException { itemStream.close(true); FileSizeLimitExceededException e = new FileSizeLimitExceededException( "The field " + fieldName + " exceeds its maximum permitted " + " size of " + pSizeMax + " bytes.", pCount, pSizeMax); e.setFieldName(fieldName); e.setFileName(name); throw new FileUploadIOException(e); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public InputStream openStream() throws IOException { if (opened) { throw new IllegalStateException( "The stream was already opened."); } if (((Closeable) stream).isClosed()) { throw new FileItemStream.ItemSkippedException(); } return stream; }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
void close() throws IOException { stream.close(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override protected void raiseError(long pSizeMax, long pCount) throws IOException { FileUploadException ex = new SizeLimitExceededException( "the request was rejected because" + " its size (" + pCount + ") exceeds the configured maximum" + " (" + pSizeMax + ")", pCount, pSizeMax); throw new FileUploadIOException(ex); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
private boolean findNextItem() throws IOException { if (eof) { return false; } if (currentItem != null) { currentItem.close(); currentItem = null; } for (;;) { boolean nextPart; if (skipPreamble) { nextPart = multi.skipPreamble(); } else { nextPart = multi.readBoundary(); } if (!nextPart) { if (currentFieldName == null) { // Outer multipart terminated -> No more data eof = true; return false; } // Inner multipart terminated -> Return to parsing the outer multi.setBoundary(boundary); currentFieldName = null; continue; } FileItemHeaders headers = getParsedHeaders(multi.readHeaders()); if (currentFieldName == null) { // We're parsing the outer multipart String fieldName = getFieldName(headers); if (fieldName != null) { String subContentType = headers.getHeader(CONTENT_TYPE); if (subContentType != null && subContentType.toLowerCase(Locale.ENGLISH) .startsWith(MULTIPART_MIXED)) { currentFieldName = fieldName; // Multiple files associated with this field name byte[] subBoundary = getBoundary(subContentType); multi.setBoundary(subBoundary); skipPreamble = true; continue; } String fileName = getFileName(headers); currentItem = new FileItemStreamImpl(fileName, fieldName, headers.getHeader(CONTENT_TYPE), fileName == null, getContentLength(headers)); currentItem.setHeaders(headers); notifier.noteItem(); itemValid = true; return true; } } else { String fileName = getFileName(headers); if (fileName != null) { currentItem = new FileItemStreamImpl(fileName, currentFieldName, headers.getHeader(CONTENT_TYPE), false, getContentLength(headers)); currentItem.setHeaders(headers); notifier.noteItem(); itemValid = true; return true; } } multi.discardBodyData(); } }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public boolean hasNext() throws FileUploadException, IOException { if (eof) { return false; } if (itemValid) { return true; } return findNextItem(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public FileItemStream next() throws FileUploadException, IOException { if (eof || (!itemValid && !hasNext())) { throw new NoSuchElementException(); } itemValid = false; return currentItem; }
// in java/org/apache/tomcat/util/http/fileupload/FileDeleteStrategy.java
public void delete(File fileToDelete) throws IOException { if (fileToDelete.exists() && doDelete(fileToDelete) == false) { throw new IOException("Deletion failed: " + fileToDelete); } }
// in java/org/apache/tomcat/util/http/fileupload/FileDeleteStrategy.java
protected boolean doDelete(File fileToDelete) throws IOException { return fileToDelete.delete(); }
// in java/org/apache/tomcat/util/http/fileupload/FileDeleteStrategy.java
Override protected boolean doDelete(File fileToDelete) throws IOException { FileUtils.forceDelete(fileToDelete); return true; }
// in java/org/apache/tomcat/util/http/fileupload/ByteArrayOutputStream.java
public synchronized int write(InputStream in) throws IOException { int readCount = 0; int inBufferPos = count - filledBufferSum; int n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos); while (n != -1) { readCount += n; inBufferPos += n; count += n; if (inBufferPos == currentBuffer.length) { needNewBuffer(currentBuffer.length); inBufferPos = 0; } n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos); } return readCount; }
// in java/org/apache/tomcat/util/http/fileupload/ByteArrayOutputStream.java
Override public void close() throws IOException { //nop }
// in java/org/apache/tomcat/util/http/fileupload/ByteArrayOutputStream.java
public synchronized void writeTo(OutputStream out) throws IOException { int remaining = count; for (int i = 0; i < buffers.size(); i++) { byte[] buf = getBuffer(i); int c = Math.min(buf.length, remaining); out.write(buf, 0, c); remaining -= c; if (remaining == 0) { break; } } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void deleteDirectory(File directory) throws IOException { if (!directory.exists()) { return; } cleanDirectory(directory); if (!directory.delete()) { String message = "Unable to delete directory " + directory + "."; throw new IOException(message); } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void cleanDirectory(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (int i = 0; i < files.length; i++) { File file = files[i]; try { forceDelete(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void forceDelete(File file) throws IOException { if (file.isDirectory()) { deleteDirectory(file); } else { boolean filePresent = file.exists(); if (!file.delete()) { if (!filePresent){ throw new FileNotFoundException("File does not exist: " + file); } String message = "Unable to delete file: " + file; throw new IOException(message); } } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void forceDeleteOnExit(File file) throws IOException { if (file.isDirectory()) { deleteDirectoryOnExit(file); } else { file.deleteOnExit(); } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
private static void deleteDirectoryOnExit(File directory) throws IOException { if (!directory.exists()) { return; } cleanDirectoryOnExit(directory); directory.deleteOnExit(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
private static void cleanDirectoryOnExit(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (int i = 0; i < files.length; i++) { File file = files[i]; try { forceDeleteOnExit(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } }
// in java/org/apache/tomcat/util/http/fileupload/util/Streams.java
public static long copy(InputStream pInputStream, OutputStream pOutputStream, boolean pClose) throws IOException { return copy(pInputStream, pOutputStream, pClose, new byte[DEFAULT_BUFFER_SIZE]); }
// in java/org/apache/tomcat/util/http/fileupload/util/Streams.java
public static long copy(InputStream pIn, OutputStream pOut, boolean pClose, byte[] pBuffer) throws IOException { OutputStream out = pOut; InputStream in = pIn; try { long total = 0; for (;;) { int res = in.read(pBuffer); if (res == -1) { break; } if (res > 0) { total += res; if (out != null) { out.write(pBuffer, 0, res); } } } if (out != null) { if (pClose) { out.close(); } else { out.flush(); } out = null; } in.close(); in = null; return total; } finally { if (in != null) { try { in.close(); } catch (IOException ioe) { /* Ignore me */ } } if (pClose && out != null) { try { out.close(); } catch (IOException ioe) { /* Ignore me */ } } } }
// in java/org/apache/tomcat/util/http/fileupload/util/Streams.java
public static String asString(InputStream pStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); copy(pStream, baos, true); return baos.toString(); }
// in java/org/apache/tomcat/util/http/fileupload/util/Streams.java
public static String asString(InputStream pStream, String pEncoding) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); copy(pStream, baos, true); return baos.toString(pEncoding); }
// in java/org/apache/tomcat/util/http/fileupload/util/LimitedInputStream.java
private void checkLimit() throws IOException { if (count > sizeMax) { raiseError(sizeMax, count); } }
// in java/org/apache/tomcat/util/http/fileupload/util/LimitedInputStream.java
Override public int read() throws IOException { int res = super.read(); if (res != -1) { count++; checkLimit(); } return res; }
// in java/org/apache/tomcat/util/http/fileupload/util/LimitedInputStream.java
Override public int read(byte[] b, int off, int len) throws IOException { int res = super.read(b, off, len); if (res > 0) { count += res; checkLimit(); } return res; }
// in java/org/apache/tomcat/util/http/fileupload/util/LimitedInputStream.java
Override public boolean isClosed() throws IOException { return closed; }
// in java/org/apache/tomcat/util/http/fileupload/util/LimitedInputStream.java
Override public void close() throws IOException { closed = true; super.close(); }
// in java/org/apache/tomcat/util/http/fileupload/ThresholdingOutputStream.java
Override public void write(int b) throws IOException { checkThreshold(1); getStream().write(b); written++; }
// in java/org/apache/tomcat/util/http/fileupload/ThresholdingOutputStream.java
Override public void write(byte b[]) throws IOException { checkThreshold(b.length); getStream().write(b); written += b.length; }
// in java/org/apache/tomcat/util/http/fileupload/ThresholdingOutputStream.java
Override public void write(byte b[], int off, int len) throws IOException { checkThreshold(len); getStream().write(b, off, len); written += len; }
// in java/org/apache/tomcat/util/http/fileupload/ThresholdingOutputStream.java
Override public void flush() throws IOException { getStream().flush(); }
// in java/org/apache/tomcat/util/http/fileupload/ThresholdingOutputStream.java
Override public void close() throws IOException { try { flush(); } catch (IOException ignored) { // ignore } getStream().close(); }
// in java/org/apache/tomcat/util/http/fileupload/ThresholdingOutputStream.java
protected void checkThreshold(int count) throws IOException { if (!thresholdExceeded && (written + count > threshold)) { thresholdExceeded = true; thresholdReached(); } }
// in java/org/apache/tomcat/util/buf/MessageBytes.java
public void duplicate( MessageBytes src ) throws IOException { switch( src.getType() ) { case MessageBytes.T_BYTES: type=T_BYTES; ByteChunk bc=src.getByteChunk(); byteC.allocate( 2 * bc.getLength(), -1 ); byteC.append( bc ); break; case MessageBytes.T_CHARS: type=T_CHARS; CharChunk cc=src.getCharChunk(); charC.allocate( 2 * cc.getLength(), -1 ); charC.append( cc ); break; case MessageBytes.T_STR: type=T_STR; String sc=src.getString(); this.setString( sc ); break; } }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
public void convert( ByteChunk bb, CharChunk cb, int limit) throws IOException { iis.setByteChunk( bb ); try { // read from the reader int bbLengthBeforeRead = 0; while( limit > 0 ) { int size = limit < BUFFER_SIZE ? limit : BUFFER_SIZE; bbLengthBeforeRead = bb.getLength(); int cnt=conv.read( result, 0, size ); if( cnt <= 0 ) { // End of stream ! - we may be in a bad state if(log.isDebugEnabled()) { log.debug("B2CConverter: EOF"); } return; } if(log.isDebugEnabled()) { log.debug("B2CConverter: Converted: " + new String(result, 0, cnt)); } cb.append( result, 0, cnt ); limit = limit - (bbLengthBeforeRead - bb.getLength()); } } catch( IOException ex) { if(log.isDebugEnabled()) { log.debug("B2CConverter: Reseting the converter " + ex.toString()); } reset(); throw ex; } }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
public void reset() throws IOException { // destroy the reader/iis iis=new IntermediateInputStream(); conv = new ReadConvertor(iis, getCharset(encoding)); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
Override public final void close() throws IOException { // NOTHING // Calling super.close() would reset out and cb. }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
Override public final int read(char cbuf[], int off, int len) throws IOException { // will do the conversion and call write on the output stream return super.read( cbuf, off, len ); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
Override public final void close() throws IOException { // shouldn't be called - we filter it out in writer throw new IOException("close() called - shouldn't happen "); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
Override public final int read(byte cbuf[], int off, int len) throws IOException { return bc.substract(cbuf, off, len); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
Override public final int read() throws IOException { return bc.substract(); }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public void append( char b ) throws IOException { makeSpace( 1 ); // couldn't make space if( limit >0 && end >= limit ) { flushBuffer(); } buff[end++]=b; }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public void append( CharChunk src ) throws IOException { append( src.getBuffer(), src.getOffset(), src.getLength()); }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public void append( char src[], int off, int len ) throws IOException { // will grow, up to limit makeSpace( len ); // if we don't have limit: makeSpace can grow as it wants if( limit < 0 ) { // assert: makeSpace made enough space System.arraycopy( src, off, buff, end, len ); end+=len; return; } // Optimize on a common case. // If the source is going to fill up all the space in buffer, may // as well write it directly to the output, and avoid an extra copy if ( optimizedWrite && len == limit && end == start && out != null ) { out.realWriteChars( src, off, len ); return; } // if we have limit and we're below if( len <= limit - end ) { // makeSpace will grow the buffer to the limit, // so we have space System.arraycopy( src, off, buff, end, len ); end+=len; return; } // need more space than we can afford, need to flush // buffer // the buffer is already at ( or bigger than ) limit // Optimization: // If len-avail < length ( i.e. after we fill the buffer with // what we can, the remaining will fit in the buffer ) we'll just // copy the first part, flush, then copy the second part - 1 write // and still have some space for more. We'll still have 2 writes, but // we write more on the first. if( len + end < 2 * limit ) { /* If the request length exceeds the size of the output buffer, flush the output buffer and then write the data directly. We can't avoid 2 writes, but we can write more on the second */ int avail=limit-end; System.arraycopy(src, off, buff, end, avail); end += avail; flushBuffer(); System.arraycopy(src, off+avail, buff, end, len - avail); end+= len - avail; } else { // len > buf.length + avail // long write - flush the buffer and write the rest // directly from source flushBuffer(); out.realWriteChars( src, off, len ); } }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public void append(String s) throws IOException { append(s, 0, s.length()); }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public void append(String s, int off, int len) throws IOException { if (s==null) { return; } // will grow, up to limit makeSpace( len ); // if we don't have limit: makeSpace can grow as it wants if( limit < 0 ) { // assert: makeSpace made enough space s.getChars(off, off+len, buff, end ); end+=len; return; } int sOff = off; int sEnd = off + len; while (sOff < sEnd) { int d = min(limit - end, sEnd - sOff); s.getChars( sOff, sOff+d, buff, end); sOff += d; end += d; if (end >= limit) { flushBuffer(); } } }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public int substract() throws IOException { if ((end - start) == 0) { if (in == null) { return -1; } int n = in.realReadChars(buff, end, buff.length - end); if (n < 0) { return -1; } } return (buff[start++]); }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public int substract( char src[], int off, int len ) throws IOException { if ((end - start) == 0) { if (in == null) { return -1; } int n = in.realReadChars( buff, end, buff.length - end); if (n < 0) { return -1; } } int n = len; if (len > getLength()) { n = getLength(); } System.arraycopy(buff, start, src, off, n); start += n; return n; }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public void flushBuffer() throws IOException { //assert out!=null if( out==null ) { throw new IOException( "Buffer overflow, no sink " + limit + " " + buff.length ); } out.realWriteChars( buff, start, end - start ); end=start; }
// in java/org/apache/tomcat/util/buf/UDecoder.java
public void convert( ByteChunk mb, boolean query ) throws IOException { int start=mb.getOffset(); byte buff[]=mb.getBytes(); int end=mb.getEnd(); int idx= ByteChunk.findByte( buff, start, end, (byte) '%' ); int idx2=-1; if( query ) { idx2= ByteChunk.findByte( buff, start, (idx >= 0 ? idx : end), (byte) '+' ); } if( idx<0 && idx2<0 ) { return; } // idx will be the smallest positive index ( first % or + ) if( (idx2 >= 0 && idx2 < idx) || idx < 0 ) { idx=idx2; } final boolean noSlash = !(ALLOW_ENCODED_SLASH || query); for( int j=idx; j<end; j++, idx++ ) { if( buff[ j ] == '+' && query) { buff[idx]= (byte)' ' ; } else if( buff[ j ] != '%' ) { buff[idx]= buff[j]; } else { // read next 2 digits if( j+2 >= end ) { throw EXCEPTION_EOF; } byte b1= buff[j+1]; byte b2=buff[j+2]; if( !isHexDigit( b1 ) || ! isHexDigit(b2 )) { throw EXCEPTION_NOT_HEX_DIGIT; } j+=2; int res=x2c( b1, b2 ); if (noSlash && (res == '/')) { throw EXCEPTION_SLASH; } buff[idx]=(byte)res; } } mb.setEnd( idx ); return; }
// in java/org/apache/tomcat/util/buf/UDecoder.java
public void convert( CharChunk mb, boolean query ) throws IOException { // log( "Converting a char chunk "); int start=mb.getOffset(); char buff[]=mb.getBuffer(); int cend=mb.getEnd(); int idx= CharChunk.indexOf( buff, start, cend, '%' ); int idx2=-1; if( query ) { idx2= CharChunk.indexOf( buff, start, (idx >= 0 ? idx : cend), '+' ); } if( idx<0 && idx2<0 ) { return; } // idx will be the smallest positive index ( first % or + ) if( (idx2 >= 0 && idx2 < idx) || idx < 0 ) { idx=idx2; } final boolean noSlash = !(ALLOW_ENCODED_SLASH || query); for( int j=idx; j<cend; j++, idx++ ) { if( buff[ j ] == '+' && query ) { buff[idx]=( ' ' ); } else if( buff[ j ] != '%' ) { buff[idx]=buff[j]; } else { // read next 2 digits if( j+2 >= cend ) { // invalid throw EXCEPTION_EOF; } char b1= buff[j+1]; char b2=buff[j+2]; if( !isHexDigit( b1 ) || ! isHexDigit(b2 )) { throw EXCEPTION_NOT_HEX_DIGIT; } j+=2; int res=x2c( b1, b2 ); if (noSlash && (res == '/')) { throw EXCEPTION_SLASH; } buff[idx]=(char)res; } } mb.setEnd( idx ); }
// in java/org/apache/tomcat/util/buf/UDecoder.java
public void convert(MessageBytes mb, boolean query) throws IOException { switch (mb.getType()) { case MessageBytes.T_STR: String strValue=mb.toString(); if( strValue==null ) { return; } try { mb.setString( convert( strValue, query )); } catch (RuntimeException ex) { throw new DecodeException(ex.getMessage()); } break; case MessageBytes.T_CHARS: CharChunk charC=mb.getCharChunk(); convert( charC, query ); break; case MessageBytes.T_BYTES: ByteChunk bytesC=mb.getByteChunk(); convert( bytesC, query ); break; } }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
private void init() throws IOException { ios = new IntermediateOutputStream(bb); conv = new WriteConvertor(ios, B2CConverter.getCharset(encoding)); writer = new BufferedWriter(conv); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
public final void convert(char c[], int off, int len) throws IOException { writer.write(c, off, len); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
public final void convert(String s, int off, int len) throws IOException { writer.write(s, off, len); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
public final void convert(String s) throws IOException { writer.write(s); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
public final void convert(char c) throws IOException { writer.write(c); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
public final void flushBuffer() throws IOException { writer.flush(); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void close() throws IOException { // NOTHING // Calling super.close() would reset out and cb. }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void flush() throws IOException { // Will flushBuffer and out() // flushBuffer put any remaining chars in the byte[] super.flush(); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void write(char cbuf[], int off, int len) throws IOException { // Will do the conversion and call write on the output stream super.write( cbuf, off, len ); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void close() throws IOException { // shouldn't be called - we filter it out in writer throw new IOException("close() called - shouldn't happen "); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void flush() throws IOException { // nothing - write will go directly to the buffer, // we don't keep any state }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void write(byte cbuf[], int off, int len) throws IOException { // will do the conversion and call write on the output stream if( enabled ) { tbuff.append( cbuf, off, len ); } }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void write(int i) throws IOException { throw new IOException("write( int ) called - shouldn't happen "); }
// in java/org/apache/tomcat/util/buf/UEncoder.java
public void urlEncode( Writer buf, String s ) throws IOException { if( c2b==null ) { bb=new ByteChunk(16); // small enough. c2b=new C2BConverter( bb, ENCODING ); } for (int i = 0; i < s.length(); i++) { int c = s.charAt(i); if( safeChars.get( c ) ) { if(log.isDebugEnabled()) { log.debug("Encoder: Safe: " + (char)c); } buf.write((char)c); } else { if(log.isDebugEnabled()) { log.debug("Encoder: Unsafe: " + (char)c); } c2b.convert( (char)c ); // "surrogate" - UTF is _not_ 16 bit, but 21 !!!! // ( while UCS is 31 ). Amazing... if (c >= 0xD800 && c <= 0xDBFF) { if ( (i+1) < s.length()) { int d = s.charAt(i+1); if (d >= 0xDC00 && d <= 0xDFFF) { if(log.isDebugEnabled()) { log.debug("Encoder: Unsafe: " + c); } c2b.convert( (char)d); i++; } } } c2b.flushBuffer(); urlEncode( buf, bb.getBuffer(), bb.getOffset(), bb.getLength() ); bb.recycle(); } } }
// in java/org/apache/tomcat/util/buf/UEncoder.java
public void urlEncode( Writer buf, byte bytes[], int off, int len) throws IOException { for( int j=off; j< len; j++ ) { buf.write( '%' ); char ch = Character.forDigit((bytes[j] >> 4) & 0xF, 16); if(log.isDebugEnabled()) { log.debug("Encoder: Encode: " + ch); } buf.write(ch); ch = Character.forDigit(bytes[j] & 0xF, 16); if(log.isDebugEnabled()) { log.debug("Encoder: Encode: " + ch); } buf.write(ch); } }
// in java/org/apache/tomcat/util/buf/ByteChunk.java
public void append( byte b ) throws IOException { makeSpace( 1 ); // couldn't make space if( limit >0 && end >= limit ) { flushBuffer(); } buff[end++]=b; }
// in java/org/apache/tomcat/util/buf/ByteChunk.java
public void append( ByteChunk src ) throws IOException { append( src.getBytes(), src.getStart(), src.getLength()); }
// in java/org/apache/tomcat/util/buf/ByteChunk.java
public void append( byte src[], int off, int len ) throws IOException { // will grow, up to limit makeSpace( len ); // if we don't have limit: makeSpace can grow as it wants if( limit < 0 ) { // assert: makeSpace made enough space System.arraycopy( src, off, buff, end, len ); end+=len; return; } // Optimize on a common case. // If the buffer is empty and the source is going to fill up all the // space in buffer, may as well write it directly to the output, // and avoid an extra copy if ( len == limit && end == start && out != null ) { out.realWriteBytes( src, off, len ); return; } // if we have limit and we're below if( len <= limit - end ) { // makeSpace will grow the buffer to the limit, // so we have space System.arraycopy( src, off, buff, end, len ); end+=len; return; } // need more space than we can afford, need to flush // buffer // the buffer is already at ( or bigger than ) limit // We chunk the data into slices fitting in the buffer limit, although // if the data is written directly if it doesn't fit int avail=limit-end; System.arraycopy(src, off, buff, end, avail); end += avail; flushBuffer(); int remain = len - avail; while (remain > (limit - end)) { out.realWriteBytes( src, (off + len) - remain, limit - end ); remain = remain - (limit - end); } System.arraycopy(src, (off + len) - remain, buff, end, remain); end += remain; }
// in java/org/apache/tomcat/util/buf/ByteChunk.java
public int substract() throws IOException { if ((end - start) == 0) { if (in == null) { return -1; } int n = in.realReadBytes( buff, 0, buff.length ); if (n < 0) { return -1; } } return (buff[start++] & 0xFF); }
// in java/org/apache/tomcat/util/buf/ByteChunk.java
public int substract( byte src[], int off, int len ) throws IOException { if ((end - start) == 0) { if (in == null) { return -1; } int n = in.realReadBytes( buff, 0, buff.length ); if (n < 0) { return -1; } } int n = len; if (len > getLength()) { n = getLength(); } System.arraycopy(buff, start, src, off, n); start += n; return n; }
// in java/org/apache/tomcat/util/buf/ByteChunk.java
public void flushBuffer() throws IOException { //assert out!=null if( out==null ) { throw new IOException( "Buffer overflow, no sink " + limit + " " + buff.length ); } out.realWriteBytes( buff, start, end-start ); end=start; }
// in java/org/apache/tomcat/util/scan/NonClosingJarInputStream.java
Override public void close() throws IOException { // Make this a NO-OP so that further entries can be read from the stream }
// in java/org/apache/tomcat/util/scan/NonClosingJarInputStream.java
public void reallyClose() throws IOException { super.close(); }
// in java/org/apache/tomcat/util/scan/JarFactory.java
public static Jar newInstance(URL url) throws IOException { String jarUrl = url.toString(); if (jarUrl.startsWith("jar:file:")) { return new FileUrlJar(url); } else { return new UrlJar(url); } }
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
private void process(JarScannerCallback callback, URL url) throws IOException { if (log.isTraceEnabled()) { log.trace(sm.getString("jarScan.jarUrlStart", url)); } URLConnection conn = url.openConnection(); if (conn instanceof JarURLConnection) { callback.scan((JarURLConnection) conn); } else { String urlStr = url.toString(); if (urlStr.startsWith("file:") || urlStr.startsWith("jndi:")) { if (urlStr.endsWith(Constants.JAR_EXT)) { URL jarURL = new URL("jar:" + urlStr + "!/"); callback.scan((JarURLConnection) jarURL.openConnection()); } else { File f; try { f = new File(url.toURI()); if (f.isFile() && scanAllFiles) { // Treat this file as a JAR URL jarURL = new URL("jar:" + urlStr + "!/"); callback.scan((JarURLConnection) jarURL.openConnection()); } else if (f.isDirectory() && scanAllDirectories) { File metainf = new File(f.getAbsoluteFile() + File.separator + "META-INF"); if (metainf.isDirectory()) { callback.scan(f); } } } catch (URISyntaxException e) { // Wrap the exception and re-throw IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } } } } }
// in java/org/apache/tomcat/util/scan/UrlJar.java
Override public boolean entryExists(String name) throws IOException { JarEntry entry = jarInputStream.getNextJarEntry(); while (entry != null) { if (name.equals(entry.getName())) { break; } entry = jarInputStream.getNextJarEntry(); } return entry != null; }
// in java/org/apache/tomcat/util/scan/UrlJar.java
Override public InputStream getInputStream(String name) throws IOException { JarEntry entry = jarInputStream.getNextJarEntry(); while (entry != null) { if (name.equals(entry.getName())) { break; } entry = jarInputStream.getNextJarEntry(); } if (entry == null) { return null; } else { return jarInputStream; } }
// in java/org/apache/tomcat/util/scan/UrlJar.java
private NonClosingJarInputStream createJarInputStream() throws IOException { JarURLConnection jarConn = (JarURLConnection) url.openConnection(); URL resourceURL = jarConn.getJarFileURL(); URLConnection resourceConn = resourceURL.openConnection(); resourceConn.setUseCaches(false); return new NonClosingJarInputStream(resourceConn.getInputStream()); }
// in java/org/apache/tomcat/util/scan/UrlJar.java
Override public InputStream getEntryInputStream() throws IOException { return jarInputStream; }
// in java/org/apache/tomcat/util/scan/UrlJar.java
Override public void reset() throws IOException { close(); jarInputStream = createJarInputStream(); }
// in java/org/apache/tomcat/util/scan/FileUrlJar.java
Override public InputStream getInputStream(String name) throws IOException { ZipEntry entry = jarFile.getEntry(name); if (entry == null) { return null; } else { return jarFile.getInputStream(entry); } }
// in java/org/apache/tomcat/util/scan/FileUrlJar.java
Override public InputStream getEntryInputStream() throws IOException { if (entry == null) { return null; } else { return jarFile.getInputStream(entry); } }
// in java/org/apache/tomcat/util/scan/FileUrlJar.java
Override public void reset() throws IOException { entries = null; entry = null; }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(File file) throws IOException, SAXException { configure(); InputSource input = new InputSource(new FileInputStream(file)); input.setSystemId("file://" + file.getAbsolutePath()); getXMLReader().parse(input); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(InputSource input) throws IOException, SAXException { configure(); getXMLReader().parse(input); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(InputStream input) throws IOException, SAXException { configure(); InputSource is = new InputSource(input); getXMLReader().parse(is); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(Reader reader) throws IOException, SAXException { configure(); InputSource is = new InputSource(reader); getXMLReader().parse(is); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(String uri) throws IOException, SAXException { configure(); InputSource is = new InputSource(uri); getXMLReader().parse(is); return (root); }
// in java/org/apache/tomcat/util/log/SystemLogHandler.java
Override public void write(byte[] b) throws IOException { findStream().write(b); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassElementValue.java
Override public void dump(DataOutputStream dos) throws IOException { dos.writeByte(type); // u1 kind of value dos.writeShort(idx); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantFloat.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeFloat(bytes); }
// in java/org/apache/tomcat/util/bcel/classfile/RuntimeInvisibleAnnotations.java
Override public final void dump(DataOutputStream dos) throws IOException { super.dump(dos); writeAnnotations(dos); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantNameAndType.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeShort(name_index); file.writeShort(signature_index); }
// in java/org/apache/tomcat/util/bcel/classfile/Synthetic.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); if (length > 0) { file.write(bytes, 0, length); } }
// in java/org/apache/tomcat/util/bcel/classfile/ExceptionTable.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(number_of_exceptions); for (int i = 0; i < number_of_exceptions; i++) { file.writeShort(exception_index_table[i]); } }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
public static final String codeToString( ByteSequence bytes, ConstantPool constant_pool, boolean verbose ) throws IOException { short opcode = (short) bytes.readUnsignedByte(); int default_offset = 0, low, high, npairs; int index, vindex, constant; int[] match, jump_table; int no_pad_bytes = 0, offset; StringBuilder buf = new StringBuilder(Constants.OPCODE_NAMES[opcode]); /* Special case: Skip (0-3) padding bytes, i.e., the * following bytes are 4-byte-aligned */ if ((opcode == Constants.TABLESWITCH) || (opcode == Constants.LOOKUPSWITCH)) { int remainder = bytes.getIndex() % 4; no_pad_bytes = (remainder == 0) ? 0 : 4 - remainder; for (int i = 0; i < no_pad_bytes; i++) { byte b; if ((b = bytes.readByte()) != 0) { System.err.println("Warning: Padding byte != 0 in " + Constants.OPCODE_NAMES[opcode] + ":" + b); } } // Both cases have a field default_offset in common default_offset = bytes.readInt(); } switch (opcode) { /* Table switch has variable length arguments. */ case Constants.TABLESWITCH: low = bytes.readInt(); high = bytes.readInt(); offset = bytes.getIndex() - 12 - no_pad_bytes - 1; default_offset += offset; buf.append("\tdefault = ").append(default_offset).append(", low = ").append(low) .append(", high = ").append(high).append("("); jump_table = new int[high - low + 1]; for (int i = 0; i < jump_table.length; i++) { jump_table[i] = offset + bytes.readInt(); buf.append(jump_table[i]); if (i < jump_table.length - 1) { buf.append(", "); } } buf.append(")"); break; /* Lookup switch has variable length arguments. */ case Constants.LOOKUPSWITCH: { npairs = bytes.readInt(); offset = bytes.getIndex() - 8 - no_pad_bytes - 1; match = new int[npairs]; jump_table = new int[npairs]; default_offset += offset; buf.append("\tdefault = ").append(default_offset).append(", npairs = ").append( npairs).append(" ("); for (int i = 0; i < npairs; i++) { match[i] = bytes.readInt(); jump_table[i] = offset + bytes.readInt(); buf.append("(").append(match[i]).append(", ").append(jump_table[i]).append(")"); if (i < npairs - 1) { buf.append(", "); } } buf.append(")"); } break; /* Two address bytes + offset from start of byte stream form the * jump target */ case Constants.GOTO: case Constants.IFEQ: case Constants.IFGE: case Constants.IFGT: case Constants.IFLE: case Constants.IFLT: case Constants.JSR: case Constants.IFNE: case Constants.IFNONNULL: case Constants.IFNULL: case Constants.IF_ACMPEQ: case Constants.IF_ACMPNE: case Constants.IF_ICMPEQ: case Constants.IF_ICMPGE: case Constants.IF_ICMPGT: case Constants.IF_ICMPLE: case Constants.IF_ICMPLT: case Constants.IF_ICMPNE: buf.append("\t\t#").append((bytes.getIndex() - 1) + bytes.readShort()); break; /* 32-bit wide jumps */ case Constants.GOTO_W: case Constants.JSR_W: buf.append("\t\t#").append(((bytes.getIndex() - 1) + bytes.readInt())); break; /* Index byte references local variable (register) */ case Constants.ALOAD: case Constants.ASTORE: case Constants.DLOAD: case Constants.DSTORE: case Constants.FLOAD: case Constants.FSTORE: case Constants.ILOAD: case Constants.ISTORE: case Constants.LLOAD: case Constants.LSTORE: case Constants.RET: if (wide) { vindex = bytes.readUnsignedShort(); wide = false; // Clear flag } else { vindex = bytes.readUnsignedByte(); } buf.append("\t\t%").append(vindex); break; /* * Remember wide byte which is used to form a 16-bit address in the * following instruction. Relies on that the method is called again with * the following opcode. */ case Constants.WIDE: wide = true; buf.append("\t(wide)"); break; /* Array of basic type. */ case Constants.NEWARRAY: buf.append("\t\t<").append(Constants.TYPE_NAMES[bytes.readByte()]).append(">"); break; /* Access object/class fields. */ case Constants.GETFIELD: case Constants.GETSTATIC: case Constants.PUTFIELD: case Constants.PUTSTATIC: index = bytes.readUnsignedShort(); buf.append("\t\t").append( constant_pool.constantToString(index, Constants.CONSTANT_Fieldref)).append( (verbose ? " (" + index + ")" : "")); break; /* Operands are references to classes in constant pool */ case Constants.NEW: case Constants.CHECKCAST: buf.append("\t"); //$FALL-THROUGH$ case Constants.INSTANCEOF: index = bytes.readUnsignedShort(); buf.append("\t<").append( constant_pool.constantToString(index, Constants.CONSTANT_Class)) .append(">").append((verbose ? " (" + index + ")" : "")); break; /* Operands are references to methods in constant pool */ case Constants.INVOKESPECIAL: case Constants.INVOKESTATIC: case Constants.INVOKEVIRTUAL: index = bytes.readUnsignedShort(); buf.append("\t").append( constant_pool.constantToString(index, Constants.CONSTANT_Methodref)) .append((verbose ? " (" + index + ")" : "")); break; case Constants.INVOKEINTERFACE: index = bytes.readUnsignedShort(); int nargs = bytes.readUnsignedByte(); // historical, redundant buf.append("\t").append( constant_pool .constantToString(index, Constants.CONSTANT_InterfaceMethodref)) .append(verbose ? " (" + index + ")\t" : "").append(nargs).append("\t") .append(bytes.readUnsignedByte()); // Last byte is a reserved space break; /* Operands are references to items in constant pool */ case Constants.LDC_W: case Constants.LDC2_W: index = bytes.readUnsignedShort(); buf.append("\t\t").append( constant_pool.constantToString(index, constant_pool.getConstant(index) .getTag())).append((verbose ? " (" + index + ")" : "")); break; case Constants.LDC: index = bytes.readUnsignedByte(); buf.append("\t\t").append( constant_pool.constantToString(index, constant_pool.getConstant(index) .getTag())).append((verbose ? " (" + index + ")" : "")); break; /* Array of references. */ case Constants.ANEWARRAY: index = bytes.readUnsignedShort(); buf.append("\t\t<").append( compactClassName(constant_pool.getConstantString(index, Constants.CONSTANT_Class), false)).append(">").append( (verbose ? " (" + index + ")" : "")); break; /* Multidimensional array of references. */ case Constants.MULTIANEWARRAY: { index = bytes.readUnsignedShort(); int dimensions = bytes.readUnsignedByte(); buf.append("\t<").append( compactClassName(constant_pool.getConstantString(index, Constants.CONSTANT_Class), false)).append(">\t").append(dimensions) .append((verbose ? " (" + index + ")" : "")); } break; /* Increment local variable. */ case Constants.IINC: if (wide) { vindex = bytes.readUnsignedShort(); constant = bytes.readShort(); wide = false; } else { vindex = bytes.readUnsignedByte(); constant = bytes.readByte(); } buf.append("\t\t%").append(vindex).append("\t").append(constant); break; default: if (Constants.NO_OF_OPERANDS[opcode] > 0) { for (int i = 0; i < Constants.TYPE_OF_OPERANDS[opcode].length; i++) { buf.append("\t\t"); switch (Constants.TYPE_OF_OPERANDS[opcode][i]) { case Constants.T_BYTE: buf.append(bytes.readByte()); break; case Constants.T_SHORT: buf.append(bytes.readShort()); break; case Constants.T_INT: buf.append(bytes.readInt()); break; default: // Never reached System.err.println("Unreachable default case reached!"); System.exit(-1); } } } } return buf.toString(); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantInteger.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeInt(bytes); }
// in java/org/apache/tomcat/util/bcel/classfile/Deprecated.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); if (length > 0) { file.write(bytes, 0, length); } }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantValue.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(constantvalue_index); }
// in java/org/apache/tomcat/util/bcel/classfile/InnerClasses.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(number_of_classes); for (int i = 0; i < number_of_classes; i++) { inner_classes[i].dump(file); } }
// in java/org/apache/tomcat/util/bcel/classfile/ElementValue.java
public static ElementValue readElementValue(DataInputStream dis, ConstantPool cpool) throws IOException { byte type = dis.readByte(); switch (type) { case 'B': // byte return new SimpleElementValue(PRIMITIVE_BYTE, dis .readUnsignedShort(), cpool); case 'C': // char return new SimpleElementValue(PRIMITIVE_CHAR, dis .readUnsignedShort(), cpool); case 'D': // double return new SimpleElementValue(PRIMITIVE_DOUBLE, dis .readUnsignedShort(), cpool); case 'F': // float return new SimpleElementValue(PRIMITIVE_FLOAT, dis .readUnsignedShort(), cpool); case 'I': // int return new SimpleElementValue(PRIMITIVE_INT, dis .readUnsignedShort(), cpool); case 'J': // long return new SimpleElementValue(PRIMITIVE_LONG, dis .readUnsignedShort(), cpool); case 'S': // short return new SimpleElementValue(PRIMITIVE_SHORT, dis .readUnsignedShort(), cpool); case 'Z': // boolean return new SimpleElementValue(PRIMITIVE_BOOLEAN, dis .readUnsignedShort(), cpool); case 's': // String return new SimpleElementValue(STRING, dis.readUnsignedShort(), cpool); case 'e': // Enum constant return new EnumElementValue(ENUM_CONSTANT, dis.readUnsignedShort(), dis.readUnsignedShort(), cpool); case 'c': // Class return new ClassElementValue(CLASS, dis.readUnsignedShort(), cpool); case '@': // Annotation // TODO isRuntimeVisible return new AnnotationElementValue(ANNOTATION, AnnotationEntry.read( dis, cpool), cpool); case '[': // Array int numArrayVals = dis.readUnsignedShort(); ElementValue[] evalues = new ElementValue[numArrayVals]; for (int j = 0; j < numArrayVals; j++) { evalues[j] = ElementValue.readElementValue(dis, cpool); } return new ArrayElementValue(ARRAY, evalues, cpool); default: throw new RuntimeException( "Unexpected element value kind in annotation: " + type); } }
// in java/org/apache/tomcat/util/bcel/classfile/StackMap.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(map_length); for (int i = 0; i < map_length; i++) { map[i].dump(file); } }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantString.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeShort(string_index); }
// in java/org/apache/tomcat/util/bcel/classfile/SourceFile.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(sourcefile_index); }
// in java/org/apache/tomcat/util/bcel/classfile/Constant.java
static final Constant readConstant( DataInputStream file ) throws IOException, ClassFormatException { byte b = file.readByte(); // Read tag byte switch (b) { case Constants.CONSTANT_Class: return new ConstantClass(file); case Constants.CONSTANT_Fieldref: return new ConstantFieldref(file); case Constants.CONSTANT_Methodref: return new ConstantMethodref(file); case Constants.CONSTANT_InterfaceMethodref: return new ConstantInterfaceMethodref(file); case Constants.CONSTANT_String: return new ConstantString(file); case Constants.CONSTANT_Integer: return new ConstantInteger(file); case Constants.CONSTANT_Float: return new ConstantFloat(file); case Constants.CONSTANT_Long: return new ConstantLong(file); case Constants.CONSTANT_Double: return new ConstantDouble(file); case Constants.CONSTANT_NameAndType: return new ConstantNameAndType(file); case Constants.CONSTANT_Utf8: return new ConstantUtf8(file); default: throw new ClassFormatException("Invalid byte tag in constant pool: " + b); } }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantLong.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeLong(bytes); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantDouble.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeDouble(bytes); }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapEntry.java
public final void dump( DataOutputStream file ) throws IOException { file.writeShort(byte_code_offset); file.writeShort(number_of_locals); for (int i = 0; i < number_of_locals; i++) { types_of_locals[i].dump(file); } file.writeShort(number_of_stack_items); for (int i = 0; i < number_of_stack_items; i++) { types_of_stack_items[i].dump(file); } }
// in java/org/apache/tomcat/util/bcel/classfile/Annotations.java
protected void writeAnnotations(DataOutputStream dos) throws IOException { if (annotation_table == null) { return; } dos.writeShort(annotation_table.length); for (int i = 0; i < annotation_table.length; i++) { annotation_table[i].dump(dos); } }
// in java/org/apache/tomcat/util/bcel/classfile/LocalVariableTable.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(local_variable_table_length); for (int i = 0; i < local_variable_table_length; i++) { local_variable_table[i].dump(file); } }
// in java/org/apache/tomcat/util/bcel/classfile/EnumElementValue.java
Override public void dump(DataOutputStream dos) throws IOException { dos.writeByte(type); // u1 type of value (ENUM_CONSTANT == 'e') dos.writeShort(typeIdx); // u2 dos.writeShort(valueIdx); // u2 }
// in java/org/apache/tomcat/util/bcel/classfile/Unknown.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); if (length > 0) { file.write(bytes, 0, length); } }
// in java/org/apache/tomcat/util/bcel/classfile/Attribute.java
public void dump(DataOutputStream file) throws IOException { file.writeShort(name_index); file.writeInt(length); }
// in java/org/apache/tomcat/util/bcel/classfile/Attribute.java
public static final Attribute readAttribute(DataInputStream file, ConstantPool constant_pool) throws IOException, ClassFormatException { ConstantUtf8 c; String name; int name_index; int length; byte tag = Constants.ATTR_UNKNOWN; // Unknown attribute // Get class name from constant pool via `name_index' indirection name_index = file.readUnsignedShort(); c = (ConstantUtf8) constant_pool.getConstant(name_index, Constants.CONSTANT_Utf8); name = c.getBytes(); // Length of data in bytes length = file.readInt(); // Compare strings to find known attribute // System.out.println(name); for (byte i = 0; i < Constants.KNOWN_ATTRIBUTES; i++) { if (name.equals(Constants.ATTRIBUTE_NAMES[i])) { tag = i; // found! break; } } // Call proper constructor, depending on `tag' switch (tag) { case Constants.ATTR_UNKNOWN: AttributeReader r = readers.get(name); if (r != null) { return r.createAttribute(name_index, length, file, constant_pool); } return new Unknown(name_index, length, file, constant_pool); case Constants.ATTR_CONSTANT_VALUE: return new ConstantValue(name_index, length, file, constant_pool); case Constants.ATTR_SOURCE_FILE: return new SourceFile(name_index, length, file, constant_pool); case Constants.ATTR_CODE: return new Code(name_index, length, file, constant_pool); case Constants.ATTR_EXCEPTIONS: return new ExceptionTable(name_index, length, file, constant_pool); case Constants.ATTR_LINE_NUMBER_TABLE: return new LineNumberTable(name_index, length, file, constant_pool); case Constants.ATTR_LOCAL_VARIABLE_TABLE: return new LocalVariableTable(name_index, length, file, constant_pool); case Constants.ATTR_INNER_CLASSES: return new InnerClasses(name_index, length, file, constant_pool); case Constants.ATTR_SYNTHETIC: return new Synthetic(name_index, length, file, constant_pool); case Constants.ATTR_DEPRECATED: return new Deprecated(name_index, length, file, constant_pool); case Constants.ATTR_PMG: return new PMGClass(name_index, length, file, constant_pool); case Constants.ATTR_SIGNATURE: return new Signature(name_index, length, file, constant_pool); case Constants.ATTR_STACK_MAP: return new StackMap(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIME_VISIBLE_ANNOTATIONS: return new RuntimeVisibleAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIMEIN_VISIBLE_ANNOTATIONS: return new RuntimeInvisibleAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS: return new RuntimeVisibleParameterAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIMEIN_VISIBLE_PARAMETER_ANNOTATIONS: return new RuntimeInvisibleParameterAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_ANNOTATION_DEFAULT: return new AnnotationDefault(name_index, length, file, constant_pool); case Constants.ATTR_LOCAL_VARIABLE_TYPE_TABLE: return new LocalVariableTypeTable(name_index, length, file, constant_pool); case Constants.ATTR_ENCLOSING_METHOD: return new EnclosingMethod(name_index, length, file, constant_pool); case Constants.ATTR_STACK_MAP_TABLE: return new StackMapTable(name_index, length, file, constant_pool); default: // Never reached throw new IllegalStateException("Unrecognized attribute type tag parsed: " + tag); } }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantUtf8.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeUTF(bytes); }
// in java/org/apache/tomcat/util/bcel/classfile/LocalVariable.java
public final void dump( DataOutputStream file ) throws IOException { file.writeShort(start_pc); file.writeShort(length); file.writeShort(name_index); file.writeShort(signature_index); file.writeShort(index); }
// in java/org/apache/tomcat/util/bcel/classfile/AnnotationDefault.java
Override public final void dump(DataOutputStream dos) throws IOException { super.dump(dos); default_value.dump(dos); }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapTable.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(map_length); for (int i = 0; i < map_length; i++) { map[i].dump(file); } }
// in java/org/apache/tomcat/util/bcel/classfile/AnnotationElementValue.java
Override public void dump(DataOutputStream dos) throws IOException { dos.writeByte(type); // u1 type of value (ANNOTATION == '@') annotationEntry.dump(dos); }
// in java/org/apache/tomcat/util/bcel/classfile/Signature.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(signature_index); }
// in java/org/apache/tomcat/util/bcel/classfile/EnclosingMethod.java
Override public final void dump(DataOutputStream file) throws IOException { super.dump(file); file.writeShort(classIndex); file.writeShort(methodIndex); }
// in java/org/apache/tomcat/util/bcel/classfile/InnerClass.java
public final void dump( DataOutputStream file ) throws IOException { file.writeShort(inner_class_index); file.writeShort(outer_class_index); file.writeShort(inner_name_index); file.writeShort(inner_access_flags); }
// in java/org/apache/tomcat/util/bcel/classfile/ArrayElementValue.java
Override public void dump(DataOutputStream dos) throws IOException { dos.writeByte(type); // u1 type of value (ARRAY == '[') dos.writeShort(evalues.length); for (int i = 0; i < evalues.length; i++) { evalues[i].dump(dos); } }
// in java/org/apache/tomcat/util/bcel/classfile/PMGClass.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(pmg_index); file.writeShort(pmg_class_index); }
// in java/org/apache/tomcat/util/bcel/classfile/AnnotationEntry.java
public static AnnotationEntry read(DataInputStream file, ConstantPool constant_pool) throws IOException { final AnnotationEntry annotationEntry = new AnnotationEntry(file.readUnsignedShort(), constant_pool); final int num_element_value_pairs = (file.readUnsignedShort()); annotationEntry.element_value_pairs = new ArrayList<ElementValuePair>(); for (int i = 0; i < num_element_value_pairs; i++) { annotationEntry.element_value_pairs.add(new ElementValuePair(file.readUnsignedShort(), ElementValue.readElementValue(file, constant_pool), constant_pool)); } return annotationEntry; }
// in java/org/apache/tomcat/util/bcel/classfile/AnnotationEntry.java
public void dump(DataOutputStream dos) throws IOException { dos.writeShort(type_index); // u2 index of type name in cpool dos.writeShort(element_value_pairs.size()); // u2 element_value pair // count for (int i = 0; i < element_value_pairs.size(); i++) { final ElementValuePair envp = element_value_pairs.get(i); envp.dump(dos); } }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapTableEntry.java
public final void dump( DataOutputStream file ) throws IOException { file.write(frame_type); if (frame_type >= Constants.SAME_FRAME && frame_type <= Constants.SAME_FRAME_MAX) { // nothing to be done } else if (frame_type >= Constants.SAME_LOCALS_1_STACK_ITEM_FRAME && frame_type <= Constants.SAME_LOCALS_1_STACK_ITEM_FRAME_MAX) { types_of_stack_items[0].dump(file); } else if (frame_type == Constants.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { file.writeShort(byte_code_offset_delta); types_of_stack_items[0].dump(file); } else if (frame_type >= Constants.CHOP_FRAME && frame_type <= Constants.CHOP_FRAME_MAX) { file.writeShort(byte_code_offset_delta); } else if (frame_type == Constants.SAME_FRAME_EXTENDED) { file.writeShort(byte_code_offset_delta); } else if (frame_type >= Constants.APPEND_FRAME && frame_type <= Constants.APPEND_FRAME_MAX) { file.writeShort(byte_code_offset_delta); for (int i = 0; i < number_of_locals; i++) { types_of_locals[i].dump(file); } } else if (frame_type == Constants.FULL_FRAME) { file.writeShort(byte_code_offset_delta); file.writeShort(number_of_locals); for (int i = 0; i < number_of_locals; i++) { types_of_locals[i].dump(file); } file.writeShort(number_of_stack_items); for (int i = 0; i < number_of_stack_items; i++) { types_of_stack_items[i].dump(file); } } else { /* Can't happen */ throw new ClassFormatException ("Invalid Stack map table tag: " + frame_type); } }
// in java/org/apache/tomcat/util/bcel/classfile/LineNumberTable.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(line_number_table_length); for (int i = 0; i < line_number_table_length; i++) { line_number_table[i].dump(file); } }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapType.java
public final void dump( DataOutputStream file ) throws IOException { file.writeByte(type); if (hasIndex()) { file.writeShort(getIndex()); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
public JavaClass parse() throws IOException, ClassFormatException { /****************** Read headers ********************************/ // Check magic tag of class file readID(); // Get compiler version readVersion(); /****************** Read constant pool and related **************/ // Read constant pool entries readConstantPool(); // Get class information readClassInfo(); // Get interface information, i.e., implemented interfaces readInterfaces(); /****************** Read class fields and methods ***************/ // Read class fields, i.e., the variables of the class readFields(); // Read class methods, i.e., the functions in the class readMethods(); // Read class attributes readAttributes(); // Check for unknown variables //Unknown[] u = Unknown.getUnknownAttributes(); //for(int i=0; i < u.length; i++) // System.err.println("WARNING: " + u[i]); // Everything should have been read now // if(file.available() > 0) { // int bytes = file.available(); // byte[] buf = new byte[bytes]; // file.read(buf); // if(!(is_zip && (buf.length == 1))) { // System.err.println("WARNING: Trailing garbage at end of " + file_name); // System.err.println(bytes + " extra bytes: " + Utility.toHexString(buf)); // } // } // Return the information we have gathered in a new object return new JavaClass(class_name_index, superclass_name_index, file_name, major, minor, access_flags, constant_pool, interfaces, fields, methods, attributes); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readAttributes() throws IOException, ClassFormatException { int attributes_count; attributes_count = file.readUnsignedShort(); attributes = new Attribute[attributes_count]; for (int i = 0; i < attributes_count; i++) { attributes[i] = Attribute.readAttribute(file, constant_pool); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readClassInfo() throws IOException, ClassFormatException { access_flags = file.readUnsignedShort(); /* Interfaces are implicitely abstract, the flag should be set * according to the JVM specification. */ if ((access_flags & Constants.ACC_INTERFACE) != 0) { access_flags |= Constants.ACC_ABSTRACT; } if (((access_flags & Constants.ACC_ABSTRACT) != 0) && ((access_flags & Constants.ACC_FINAL) != 0)) { throw new ClassFormatException("Class " + file_name + " can't be both final and abstract"); } class_name_index = file.readUnsignedShort(); superclass_name_index = file.readUnsignedShort(); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readConstantPool() throws IOException, ClassFormatException { constant_pool = new ConstantPool(file); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readFields() throws IOException, ClassFormatException { int fields_count; fields_count = file.readUnsignedShort(); fields = new Field[fields_count]; for (int i = 0; i < fields_count; i++) { fields[i] = new Field(file, constant_pool); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readID() throws IOException, ClassFormatException { int magic = 0xCAFEBABE; if (file.readInt() != magic) { throw new ClassFormatException(file_name + " is not a Java .class file"); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readInterfaces() throws IOException, ClassFormatException { int interfaces_count; interfaces_count = file.readUnsignedShort(); interfaces = new int[interfaces_count]; for (int i = 0; i < interfaces_count; i++) { interfaces[i] = file.readUnsignedShort(); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readMethods() throws IOException, ClassFormatException { int methods_count; methods_count = file.readUnsignedShort(); methods = new Method[methods_count]; for (int i = 0; i < methods_count; i++) { methods[i] = new Method(file, constant_pool); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readVersion() throws IOException, ClassFormatException { minor = file.readUnsignedShort(); major = file.readUnsignedShort(); }
// in java/org/apache/tomcat/util/bcel/classfile/LocalVariableTypeTable.java
Override public final void dump(DataOutputStream file) throws IOException { super.dump(file); file.writeShort(local_variable_type_table_length); for(int i=0; i < local_variable_type_table_length; i++) local_variable_type_table[i].dump(file); }
// in java/org/apache/tomcat/util/bcel/classfile/SimpleElementValue.java
Override public void dump(DataOutputStream dos) throws IOException { dos.writeByte(type); // u1 kind of value switch (type) { case PRIMITIVE_INT: case PRIMITIVE_BYTE: case PRIMITIVE_CHAR: case PRIMITIVE_FLOAT: case PRIMITIVE_LONG: case PRIMITIVE_BOOLEAN: case PRIMITIVE_SHORT: case PRIMITIVE_DOUBLE: case STRING: dos.writeShort(getIndex()); break; default: throw new RuntimeException( "SimpleElementValue doesnt know how to write out type " + type); } }
// in java/org/apache/tomcat/util/bcel/classfile/CodeException.java
public final void dump( DataOutputStream file ) throws IOException { file.writeShort(start_pc); file.writeShort(end_pc); file.writeShort(handler_pc); file.writeShort(catch_type); }
// in java/org/apache/tomcat/util/bcel/classfile/RuntimeVisibleAnnotations.java
Override public final void dump(DataOutputStream dos) throws IOException { super.dump(dos); writeAnnotations(dos); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantClass.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeShort(name_index); }
// in java/org/apache/tomcat/util/bcel/classfile/Code.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(max_stack); file.writeShort(max_locals); file.writeInt(code_length); file.write(code, 0, code_length); file.writeShort(exception_table_length); for (int i = 0; i < exception_table_length; i++) { exception_table[i].dump(file); } file.writeShort(attributes_count); for (int i = 0; i < attributes_count; i++) { attributes[i].dump(file); } }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantCP.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeShort(class_index); file.writeShort(name_and_type_index); }
// in java/org/apache/tomcat/util/bcel/classfile/ElementValuePair.java
protected void dump(DataOutputStream dos) throws IOException { dos.writeShort(elementNameIndex); // u2 name of the element elementValue.dump(dos); }
// in java/org/apache/tomcat/util/bcel/classfile/LineNumber.java
public final void dump( DataOutputStream file ) throws IOException { file.writeShort(start_pc); file.writeShort(line_number); }
// in java/org/apache/el/lang/FunctionMapperImpl.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(this.functions); }
// in java/org/apache/el/lang/FunctionMapperImpl.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF((this.prefix != null) ? this.prefix : ""); out.writeUTF(this.localName); // make sure m isn't null getMethod(); out.writeUTF((this.owner != null) ? this.owner : this.m.getDeclaringClass().getName()); out.writeUTF((this.name != null) ? this.name : this.m.getName()); out.writeObject((this.types != null) ? this.types : ReflectionUtil.toTypeNameArray(this.m.getParameterTypes())); }
// in java/org/apache/el/lang/FunctionMapperImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.prefix = in.readUTF(); if ("".equals(this.prefix)) this.prefix = null; this.localName = in.readUTF(); this.owner = in.readUTF(); this.name = in.readUTF(); this.types = (String[]) in.readObject(); }
// in java/org/apache/el/MethodExpressionImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.expr = in.readUTF(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } this.paramTypes = ReflectionUtil.toTypeArray(((String[]) in .readObject())); this.fnMapper = (FunctionMapper) in.readObject(); this.varMapper = (VariableMapper) in.readObject(); }
// in java/org/apache/el/MethodExpressionImpl.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(this.expr); out.writeUTF((this.expectedType != null) ? this.expectedType.getName() : ""); out.writeObject(ReflectionUtil.toTypeNameArray(this.paramTypes)); out.writeObject(this.fnMapper); out.writeObject(this.varMapper); }
// in java/org/apache/el/MethodExpressionLiteral.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.expr = in.readUTF(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } this.paramTypes = ReflectionUtil.toTypeArray(((String[]) in .readObject())); }
// in java/org/apache/el/MethodExpressionLiteral.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(this.expr); out.writeUTF((this.expectedType != null) ? this.expectedType.getName() : ""); out.writeObject(ReflectionUtil.toTypeNameArray(this.paramTypes)); }
// in java/org/apache/el/parser/SimpleCharStream.java
protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
// in java/org/apache/el/parser/SimpleCharStream.java
public char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); tokenBegin = bufpos; return c; }
// in java/org/apache/el/parser/SimpleCharStream.java
public char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; return buffer[bufpos]; } if (++bufpos >= maxNextCharInd) FillBuff(); char c = buffer[bufpos]; UpdateLineColumn(c); return c; }
// in java/org/apache/el/ValueExpressionLiteral.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(this.value); out.writeUTF((this.expectedType != null) ? this.expectedType.getName() : ""); }
// in java/org/apache/el/ValueExpressionLiteral.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.value = in.readObject(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } }
// in java/org/apache/el/ValueExpressionImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.expr = in.readUTF(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } this.fnMapper = (FunctionMapper) in.readObject(); this.varMapper = (VariableMapper) in.readObject(); }
// in java/org/apache/el/ValueExpressionImpl.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(this.expr); out.writeUTF((this.expectedType != null) ? this.expectedType.getName() : ""); out.writeObject(this.fnMapper); out.writeObject(this.varMapper); }
// in java/org/apache/catalina/startup/ContextConfig.java
protected void fixDocBase() throws IOException { Host host = (Host) context.getParent(); File appBase = host.getAppBaseFile(); String docBase = context.getDocBase(); if (docBase == null) { // Trying to guess the docBase according to the path String path = context.getPath(); if (path == null) { return; } ContextName cn = new ContextName(path, context.getWebappVersion()); docBase = cn.getBaseName(); } File file = new File(docBase); if (!file.isAbsolute()) { docBase = (new File(appBase, docBase)).getPath(); } else { docBase = file.getCanonicalPath(); } file = new File(docBase); String origDocBase = docBase; ContextName cn = new ContextName(context.getPath(), context.getWebappVersion()); String pathName = cn.getBaseName(); boolean unpackWARs = true; if (host instanceof StandardHost && context instanceof StandardContext) { unpackWARs = ((StandardHost) host).isUnpackWARs() && ((StandardContext) context).getUnpackWAR() && (docBase.startsWith(host.getAppBaseFile().getPath())); } if (docBase.toLowerCase(Locale.ENGLISH).endsWith(".war") && !file.isDirectory() && unpackWARs) { URL war = new URL("jar:" + (new File(docBase)).toURI().toURL() + "!/"); docBase = ExpandWar.expand(host, war, pathName); file = new File(docBase); docBase = file.getCanonicalPath(); if (context instanceof StandardContext) { ((StandardContext) context).setOriginalDocBase(origDocBase); } } else if (docBase.toLowerCase(Locale.ENGLISH).endsWith(".war") && !file.isDirectory() && !unpackWARs) { URL war = new URL("jar:" + (new File (docBase)).toURI().toURL() + "!/"); ExpandWar.validate(host, war, pathName); } else { File docDir = new File(docBase); if (!docDir.exists()) { File warFile = new File(docBase + ".war"); if (warFile.exists()) { URL war = new URL("jar:" + warFile.toURI().toURL() + "!/"); if (unpackWARs) { docBase = ExpandWar.expand(host, war, pathName); file = new File(docBase); docBase = file.getCanonicalPath(); } else { docBase = warFile.getCanonicalPath(); ExpandWar.validate(host, war, pathName); } } if (context instanceof StandardContext) { ((StandardContext) context).setOriginalDocBase(origDocBase); } } } if (docBase.startsWith(appBase.getPath() + File.separatorChar)) { docBase = docBase.substring(appBase.getPath().length()); docBase = docBase.replace(File.separatorChar, '/'); if (docBase.startsWith("/")) { docBase = docBase.substring(1); } } else { docBase = docBase.replace(File.separatorChar, '/'); } context.setDocBase(docBase); }
// in java/org/apache/catalina/startup/ContextConfig.java
protected ServletContainerInitializer getServletContainerInitializer( InputStream is) throws IOException { String className = null; if (is != null) { String line = null; try { BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); line = br.readLine(); if (line != null && line.trim().length() > 0) { className = line.trim(); } } catch (UnsupportedEncodingException e) { // Should never happen with UTF-8 // If it does - ignore & return null } } ServletContainerInitializer sci = null; try { Class<?> clazz = Class.forName(className,true, context.getLoader().getClassLoader()); sci = (ServletContainerInitializer) clazz.newInstance(); } catch (ClassNotFoundException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); } catch (InstantiationException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); } catch (IllegalAccessException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); } return sci; }
// in java/org/apache/catalina/startup/ContextConfig.java
protected void processAnnotationsStream(InputStream is, WebXml fragment) throws ClassFormatException, IOException { ClassParser parser = new ClassParser(is, null); JavaClass clazz = parser.parse(); checkHandlesTypes(clazz); String className = clazz.getClassName(); AnnotationEntry[] annotationsEntries = clazz.getAnnotationEntries(); for (AnnotationEntry ae : annotationsEntries) { String type = ae.getAnnotationType(); if ("Ljavax/servlet/annotation/WebServlet;".equals(type)) { processAnnotationWebServlet(className, ae, fragment); }else if ("Ljavax/servlet/annotation/WebFilter;".equals(type)) { processAnnotationWebFilter(className, ae, fragment); }else if ("Ljavax/servlet/annotation/WebListener;".equals(type)) { fragment.addListener(className); } else { // Unknown annotation - ignore } } }
// in java/org/apache/catalina/startup/ContextConfig.java
Override public void scan(JarURLConnection jarConn) throws IOException { URL url = jarConn.getURL(); URL resourceURL = jarConn.getJarFileURL(); Jar jar = null; InputStream is = null; WebXml fragment = new WebXml(); try { jar = JarFactory.newInstance(url); is = jar.getInputStream(FRAGMENT_LOCATION); if (is == null) { // If there is no web.xml, normal JAR no impact on // distributable fragment.setDistributable(true); } else { InputSource source = new InputSource( resourceURL.toString() + "!/" + FRAGMENT_LOCATION); source.setByteStream(is); parseWebXml(source, fragment, true); } } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } if (jar != null) { jar.close(); } fragment.setURL(url); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); } }
// in java/org/apache/catalina/startup/ContextConfig.java
Override public void scan(File file) throws IOException { InputStream stream = null; WebXml fragment = new WebXml(); try { File fragmentFile = new File(file, FRAGMENT_LOCATION); if (fragmentFile.isFile()) { stream = new FileInputStream(fragmentFile); InputSource source = new InputSource(fragmentFile.toURI().toURL().toString()); source.setByteStream(stream); parseWebXml(source, fragment, true); } } finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } fragment.setURL(file.toURI().toURL()); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); } }
// in java/org/apache/catalina/startup/TldConfig.java
Override public void scan(JarURLConnection urlConn) throws IOException { tldScanJar(urlConn); }
// in java/org/apache/catalina/startup/TldConfig.java
private XmlErrorHandler tldScanStream(InputStream resourceStream) throws IOException { InputSource source = new InputSource(resourceStream); XmlErrorHandler result = new XmlErrorHandler(); synchronized (tldDigester) { try { tldDigester.setErrorHandler(result); tldDigester.push(this); tldDigester.parse(source); } catch (SAXException s) { // Hack - makes exception handling simpler throw new IOException(s); } finally { tldDigester.reset(); } return result; } }
// in java/org/apache/catalina/startup/ClassLoaderFactory.java
private static boolean validateFile(File file, RepositoryType type) throws IOException { if (RepositoryType.DIR == type || RepositoryType.GLOB == type) { if (!file.exists() || !file.isDirectory() || !file.canRead()) { String msg = "Problem with directory [" + file + "], exists: [" + file.exists() + "], isDirectory: [" + file.isDirectory() + "], canRead: [" + file.canRead() + "]"; File home = new File (Bootstrap.getCatalinaHome()); home = home.getCanonicalFile(); File base = new File (Bootstrap.getCatalinaBase()); base = base.getCanonicalFile(); File defaultValue = new File(base, "lib"); // Existence of ${catalina.base}/lib directory is optional. // Hide the warning if Tomcat runs with separate catalina.home // and catalina.base and that directory is absent. if (!home.getPath().equals(base.getPath()) && file.getPath().equals(defaultValue.getPath()) && !file.exists()) { log.debug(msg); } else { log.warn(msg); } return false; } } else if (RepositoryType.JAR == type) { if (!file.exists() || !file.canRead()) { log.warn("Problem with JAR file [" + file + "], exists: [" + file.exists() + "], canRead: [" + file.canRead() + "]"); return false; } } return true; }
// in java/org/apache/catalina/startup/ExpandWar.java
public static String expand(Host host, URL war, String pathname) throws IOException { // Make sure that there is no such directory already existing File docBase = new File(host.getAppBaseFile(), pathname); if (docBase.exists()) { // War file is already installed return (docBase.getAbsolutePath()); } // Create the new document base directory docBase.mkdir(); // Expand the WAR into the new document base directory String canonicalDocBasePrefix = docBase.getCanonicalPath(); if (!canonicalDocBasePrefix.endsWith(File.separator)) { canonicalDocBasePrefix += File.separator; } JarURLConnection juc = (JarURLConnection) war.openConnection(); juc.setUseCaches(false); JarFile jarFile = null; InputStream input = null; boolean success = false; try { jarFile = juc.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String name = jarEntry.getName(); File expandedFile = new File(docBase, name); if (!expandedFile.getCanonicalPath().startsWith( canonicalDocBasePrefix)) { // Trying to expand outside the docBase // Throw an exception to stop the deployment throw new IllegalArgumentException( sm.getString("expandWar.illegalPath",war, name, expandedFile.getCanonicalPath(), canonicalDocBasePrefix)); } int last = name.lastIndexOf('/'); if (last >= 0) { File parent = new File(docBase, name.substring(0, last)); if (!parent.mkdirs() && !parent.isDirectory()) { throw new IOException( sm.getString("expandWar.createFailed", parent)); } } if (name.endsWith("/")) { continue; } input = jarFile.getInputStream(jarEntry); if(null == input) throw new ZipException(sm.getString("expandWar.missingJarEntry", jarEntry.getName())); // Bugzilla 33636 expand(input, expandedFile); long lastModified = jarEntry.getTime(); if ((lastModified != -1) && (lastModified != 0)) { expandedFile.setLastModified(lastModified); } input.close(); input = null; } success = true; } catch (IOException e) { throw e; } finally { if (!success) { // If something went wrong, delete expanded dir to keep things // clean deleteDir(docBase); } if (input != null) { try { input.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } input = null; } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } } // Return the absolute path to our new document base directory return (docBase.getAbsolutePath()); }
// in java/org/apache/catalina/startup/ExpandWar.java
public static void validate(Host host, URL war, String pathname) throws IOException { File docBase = new File(host.getAppBaseFile(), pathname); // Calculate the document base directory String canonicalDocBasePrefix = docBase.getCanonicalPath(); if (!canonicalDocBasePrefix.endsWith(File.separator)) { canonicalDocBasePrefix += File.separator; } JarURLConnection juc = (JarURLConnection) war.openConnection(); juc.setUseCaches(false); JarFile jarFile = null; try { jarFile = juc.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String name = jarEntry.getName(); File expandedFile = new File(docBase, name); if (!expandedFile.getCanonicalPath().startsWith( canonicalDocBasePrefix)) { // Entry located outside the docBase // Throw an exception to stop the deployment throw new IllegalArgumentException( sm.getString("expandWar.illegalPath",war, name, expandedFile.getCanonicalPath(), canonicalDocBasePrefix)); } } } catch (IOException e) { throw e; } finally { if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } } }
// in java/org/apache/catalina/startup/ExpandWar.java
private static void expand(InputStream input, File file) throws IOException { BufferedOutputStream output = null; try { output = new BufferedOutputStream(new FileOutputStream(file)); byte buffer[] = new byte[2048]; while (true) { int n = input.read(buffer); if (n <= 0) break; output.write(buffer, 0, n); } } finally { if (output != null) { try { output.close(); } catch (IOException e) { // Ignore } } } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
synchronized void addJar(String jar, JarFile jarFile, File file) throws IOException { if (jar == null) return; if (jarFile == null) return; if (file == null) return; if (log.isDebugEnabled()) log.debug("addJar(" + jar + ")"); int i; if ((jarPath != null) && (jar.startsWith(jarPath))) { String jarName = jar.substring(jarPath.length()); while (jarName.startsWith("/")) jarName = jarName.substring(1); String[] result = new String[jarNames.length + 1]; for (i = 0; i < jarNames.length; i++) { result[i] = jarNames[i]; } result[jarNames.length] = jarName; jarNames = result; } try { // Register the JAR for tracking long lastModified = ((ResourceAttributes) resources.getAttributes(jar)) .getLastModified(); String[] result = new String[paths.length + 1]; for (i = 0; i < paths.length; i++) { result[i] = paths[i]; } result[paths.length] = jar; paths = result; long[] result3 = new long[lastModifiedDates.length + 1]; for (i = 0; i < lastModifiedDates.length; i++) { result3[i] = lastModifiedDates[i]; } result3[lastModifiedDates.length] = lastModified; lastModifiedDates = result3; } catch (NamingException e) { // Ignore } // If the JAR currently contains invalid classes, don't actually use it // for classloading if (!validateJarFile(file)) return; JarFile[] result2 = new JarFile[jarFiles.length + 1]; for (i = 0; i < jarFiles.length; i++) { result2[i] = jarFiles[i]; } result2[jarFiles.length] = jarFile; jarFiles = result2; // Add the file to the list File[] result4 = new File[jarRealFiles.length + 1]; for (i = 0; i < jarRealFiles.length; i++) { result4[i] = jarRealFiles[i]; } result4[jarRealFiles.length] = file; jarRealFiles = result4; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public Enumeration<URL> findResources(String name) throws IOException { if (log.isDebugEnabled()) log.debug(" findResources(" + name + ")"); //we use a LinkedHashSet instead of a Vector to avoid duplicates with virtualmappings LinkedHashSet<URL> result = new LinkedHashSet<URL>(); int jarFilesLength = jarFiles.length; int repositoriesLength = repositories.length; int i; // Adding the results of a call to the superclass if (hasExternalRepositories && searchExternalFirst) { Enumeration<URL> otherResourcePaths = super.findResources(name); while (otherResourcePaths.hasMoreElements()) { result.add(otherResourcePaths.nextElement()); } } // Looking at the repositories for (i = 0; i < repositoriesLength; i++) { try { String fullPath = repositories[i] + name; resources.lookup(fullPath); // Note : Not getting an exception here means the resource was // found try { result.add(getURI(new File(files[i], name))); } catch (MalformedURLException e) { // Ignore } } catch (NamingException e) { // Ignore } } // Looking at the JAR files synchronized (jarFiles) { if (openJARs()) { for (i = 0; i < jarFilesLength; i++) { JarEntry jarEntry = jarFiles[i].getJarEntry(name); if (jarEntry != null) { try { String jarFakeUrl = getURI(jarRealFiles[i]).toString(); jarFakeUrl = "jar:" + jarFakeUrl + "!/" + name; result.add(new URL(jarFakeUrl)); } catch (MalformedURLException e) { // Ignore } } } } } // Adding the results of a call to the superclass if (hasExternalRepositories && !searchExternalFirst) { Enumeration<URL> otherResourcePaths = super.findResources(name); while (otherResourcePaths.hasMoreElements()) { result.add(otherResourcePaths.nextElement()); } } final Iterator<URL> iterator = result.iterator(); return new Enumeration<URL>() { @Override public boolean hasMoreElements() { return iterator.hasNext(); } @Override public URL nextElement() { return iterator.next(); } }; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
protected boolean validateJarFile(File file) throws IOException { if (triggers == null) return (true); JarFile jarFile = null; try { jarFile = new JarFile(file); for (int i = 0; i < triggers.length; i++) { Class<?> clazz = null; try { if (parent != null) { clazz = parent.loadClass(triggers[i]); } else { clazz = Class.forName(triggers[i]); } } catch (Exception e) { clazz = null; } if (clazz == null) continue; String name = triggers[i].replace('.', '/') + ".class"; if (log.isDebugEnabled()) log.debug(" Checking for " + name); JarEntry jarEntry = jarFile.getJarEntry(name); if (jarEntry != null) { log.info("validateJarFile(" + file + ") - jar not loaded. See Servlet Spec 2.3, " + "section 9.7.2. Offending class: " + name); return false; } } return true; } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException ioe) { // Ignore } } } }
// in java/org/apache/catalina/loader/WebappLoader.java
private void setRepositories() throws IOException { if (!(container instanceof Context)) return; ServletContext servletContext = ((Context) container).getServletContext(); if (servletContext == null) return; loaderRepositories=new ArrayList<String>(); // Loading the work directory File workDir = (File) servletContext.getAttribute(ServletContext.TEMPDIR); if (workDir == null) { log.info("No work dir for " + servletContext); } if( log.isDebugEnabled() && workDir != null) log.debug(sm.getString("webappLoader.deploy", workDir.getAbsolutePath())); classLoader.setWorkDir(workDir); DirContext resources = container.getResources(); // Setting up the class repository (/WEB-INF/classes), if it exists String classesPath = "/WEB-INF/classes"; DirContext classes = null; try { Object object = resources.lookup(classesPath); if (object instanceof DirContext) { classes = (DirContext) object; } } catch(NamingException e) { // Silent catch: it's valid that no /WEB-INF/classes collection // exists } if (classes != null) { File classRepository = null; String absoluteClassesPath = servletContext.getRealPath(classesPath); if (absoluteClassesPath != null) { classRepository = new File(absoluteClassesPath); } else { classRepository = new File(workDir, classesPath); if (!classRepository.mkdirs() && !classRepository.isDirectory()) { throw new IOException( sm.getString("webappLoader.mkdirFailure")); } if (!copyDir(classes, classRepository)) { throw new IOException( sm.getString("webappLoader.copyFailure")); } } if(log.isDebugEnabled()) log.debug(sm.getString("webappLoader.classDeploy", classesPath, classRepository.getAbsolutePath())); // Adding the repository to the class loader classLoader.addRepository(classesPath + "/", classRepository); loaderRepositories.add(classesPath + "/" ); } // Setting up the JAR repository (/WEB-INF/lib), if it exists String libPath = "/WEB-INF/lib"; classLoader.setJarPath(libPath); DirContext libDir = null; // Looking up directory /WEB-INF/lib in the context try { Object object = resources.lookup(libPath); if (object instanceof DirContext) libDir = (DirContext) object; } catch(NamingException e) { // Silent catch: it's valid that no /WEB-INF/lib collection // exists } if (libDir != null) { boolean copyJars = false; String absoluteLibPath = servletContext.getRealPath(libPath); File destDir = null; if (absoluteLibPath != null) { destDir = new File(absoluteLibPath); } else { copyJars = true; destDir = new File(workDir, libPath); if (!destDir.mkdirs() && !destDir.isDirectory()) { throw new IOException( sm.getString("webappLoader.mkdirFailure")); } } // Looking up directory /WEB-INF/lib in the context NamingEnumeration<NameClassPair> enumeration = null; try { enumeration = libDir.list(""); } catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", libPath)); ioe.initCause(e); throw ioe; } while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String filename = libPath + "/" + ncPair.getName(); if (!filename.endsWith(".jar")) continue; // Copy JAR in the work directory, always (the JAR file // would get locked otherwise, which would make it // impossible to update it or remove it at runtime) File destFile = new File(destDir, ncPair.getName()); if( log.isDebugEnabled()) log.debug(sm.getString("webappLoader.jarDeploy", filename, destFile.getAbsolutePath())); // Bug 45403 - Explicitly call lookup() on the name to check // that the resource is readable. We cannot use resources // returned by listBindings(), because that lists all of them, // but does not perform the necessary checks on each. Object obj = null; try { obj = libDir.lookup(ncPair.getName()); } catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", filename)); ioe.initCause(e); throw ioe; } if (!(obj instanceof Resource)) continue; Resource jarResource = (Resource) obj; if (copyJars) { if (!copy(jarResource.streamContent(), new FileOutputStream(destFile))) { throw new IOException( sm.getString("webappLoader.copyFailure")); } } try { JarFile jarFile = new JarFile(destFile); classLoader.addJar(filename, jarFile, destFile); } catch (Exception ex) { // Catch the exception if there is an empty jar file // Should ignore and continue loading other jar files // in the dir } loaderRepositories.add( filename ); } } }
// in java/org/apache/catalina/realm/RealmBase.java
Override public boolean hasResourcePermission(Request request, Response response, SecurityConstraint []constraints, Context context) throws IOException { if (constraints == null || constraints.length == 0) return (true); // Specifically allow access to the form login and form error pages // and the "j_security_check" action LoginConfig config = context.getLoginConfig(); if ((config != null) && (Constants.FORM_METHOD.equals(config.getAuthMethod()))) { String requestURI = request.getRequestPathMB().toString(); String loginPage = config.getLoginPage(); if (loginPage.equals(requestURI)) { if (log.isDebugEnabled()) log.debug(" Allow access to login page " + loginPage); return (true); } String errorPage = config.getErrorPage(); if (errorPage.equals(requestURI)) { if (log.isDebugEnabled()) log.debug(" Allow access to error page " + errorPage); return (true); } if (requestURI.endsWith(Constants.FORM_ACTION)) { if (log.isDebugEnabled()) log.debug(" Allow access to username/password submission"); return (true); } } // Which user principal have we already authenticated? Principal principal = request.getPrincipal(); boolean status = false; boolean denyfromall = false; for(int i=0; i < constraints.length; i++) { SecurityConstraint constraint = constraints[i]; String roles[]; if (constraint.getAllRoles()) { // * means all roles defined in web.xml roles = request.getContext().findSecurityRoles(); } else { roles = constraint.findAuthRoles(); } if (roles == null) roles = new String[0]; if (log.isDebugEnabled()) log.debug(" Checking roles " + principal); if (roles.length == 0 && !constraint.getAllRoles()) { if(constraint.getAuthConstraint()) { if( log.isDebugEnabled() ) log.debug("No roles"); status = false; // No listed roles means no access at all denyfromall = true; break; } if(log.isDebugEnabled()) log.debug("Passing all access"); status = true; } else if (principal == null) { if (log.isDebugEnabled()) log.debug(" No user authenticated, cannot grant access"); } else { for (int j = 0; j < roles.length; j++) { if (hasRole(null, principal, roles[j])) { status = true; if( log.isDebugEnabled() ) log.debug( "Role found: " + roles[j]); } else if( log.isDebugEnabled() ) log.debug( "No role found: " + roles[j]); } } } if (!denyfromall && allRolesMode != AllRolesMode.STRICT_MODE && !status && principal != null) { if (log.isDebugEnabled()) { log.debug("Checking for all roles mode: " + allRolesMode); } // Check for an all roles(role-name="*") for (int i = 0; i < constraints.length; i++) { SecurityConstraint constraint = constraints[i]; String roles[]; // If the all roles mode exists, sets if (constraint.getAllRoles()) { if (allRolesMode == AllRolesMode.AUTH_ONLY_MODE) { if (log.isDebugEnabled()) { log.debug("Granting access for role-name=*, auth-only"); } status = true; break; } // For AllRolesMode.STRICT_AUTH_ONLY_MODE there must be zero roles roles = request.getContext().findSecurityRoles(); if (roles.length == 0 && allRolesMode == AllRolesMode.STRICT_AUTH_ONLY_MODE) { if (log.isDebugEnabled()) { log.debug("Granting access for role-name=*, strict auth-only"); } status = true; break; } } } } // Return a "Forbidden" message denying access to this resource if(!status) { response.sendError (HttpServletResponse.SC_FORBIDDEN, sm.getString("realmBase.forbidden")); } return status; }
// in java/org/apache/catalina/realm/RealmBase.java
Override public boolean hasUserDataPermission(Request request, Response response, SecurityConstraint []constraints) throws IOException { // Is there a relevant user data constraint? if (constraints == null || constraints.length == 0) { if (log.isDebugEnabled()) log.debug(" No applicable security constraint defined"); return (true); } for(int i=0; i < constraints.length; i++) { SecurityConstraint constraint = constraints[i]; String userConstraint = constraint.getUserConstraint(); if (userConstraint == null) { if (log.isDebugEnabled()) log.debug(" No applicable user data constraint defined"); return (true); } if (userConstraint.equals(Constants.NONE_TRANSPORT)) { if (log.isDebugEnabled()) log.debug(" User data constraint has no restrictions"); return (true); } } // Validate the request against the user data constraint if (request.getRequest().isSecure()) { if (log.isDebugEnabled()) log.debug(" User data constraint already satisfied"); return (true); } // Initialize variables we need to determine the appropriate action int redirectPort = request.getConnector().getRedirectPort(); // Is redirecting disabled? if (redirectPort <= 0) { if (log.isDebugEnabled()) log.debug(" SSL redirect is disabled"); response.sendError (HttpServletResponse.SC_FORBIDDEN, request.getRequestURI()); return (false); } // Redirect to the corresponding SSL port StringBuilder file = new StringBuilder(); String protocol = "https"; String host = request.getServerName(); // Protocol file.append(protocol).append("://").append(host); // Host with port if(redirectPort != 443) { file.append(":").append(redirectPort); } // URI file.append(request.getRequestURI()); String requestedSessionId = request.getRequestedSessionId(); if ((requestedSessionId != null) && request.isRequestedSessionIdFromURL()) { file.append(";"); file.append(SessionConfig.getSessionUriParamName( request.getContext())); file.append("="); file.append(requestedSessionId); } String queryString = request.getQueryString(); if (queryString != null) { file.append('?'); file.append(queryString); } if (log.isDebugEnabled()) log.debug(" Redirecting to " + file.toString()); response.sendRedirect(file.toString()); return (false); }
// in java/org/apache/catalina/realm/JAASCallbackHandler.java
Override public void handle(Callback callbacks[]) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof NameCallback) { if (realm.getContainer().getLogger().isTraceEnabled()) realm.getContainer().getLogger().trace(sm.getString("jaasCallback.username", username)); ((NameCallback) callbacks[i]).setName(username); } else if (callbacks[i] instanceof PasswordCallback) { final char[] passwordcontents; if (password != null) { passwordcontents = password.toCharArray(); } else { passwordcontents = new char[0]; } ((PasswordCallback) callbacks[i]).setPassword (passwordcontents); } else if (callbacks[i] instanceof TextInputCallback) { TextInputCallback cb = ((TextInputCallback) callbacks[i]); if (cb.getPrompt().equals("nonce")) { cb.setText(nonce); } else if (cb.getPrompt().equals("nc")) { cb.setText(nc); } else if (cb.getPrompt().equals("cnonce")) { cb.setText(cnonce); } else if (cb.getPrompt().equals("qop")) { cb.setText(qop); } else if (cb.getPrompt().equals("realmName")) { cb.setText(realmName); } else if (cb.getPrompt().equals("md5a2")) { cb.setText(md5a2); } else if (cb.getPrompt().equals("authMethod")) { cb.setText(authMethod); } else { throw new UnsupportedCallbackException(callbacks[i]); } } else { throw new UnsupportedCallbackException(callbacks[i]); } } }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
Override public Socket createSocket(String host, int port) throws IOException { if (factory == null) { return new Socket(FORCED_HOST, port); } else { return factory.createSocket(FORCED_HOST, port); } }
// in java/org/apache/catalina/filters/SetCharacterEncodingFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Conditionally select and set the character encoding to be used if (ignore || (request.getCharacterEncoding() == null)) { String characterEncoding = selectEncoding(request); if (characterEncoding != null) { request.setCharacterEncoding(characterEncoding); } } // Pass control on to the next filter chain.doFilter(request, response); }
// in java/org/apache/catalina/filters/RequestDumperFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest hRequest = null; HttpServletResponse hResponse = null; if (request instanceof HttpServletRequest) { hRequest = (HttpServletRequest) request; } if (response instanceof HttpServletResponse) { hResponse = (HttpServletResponse) response; } // Log pre-service information doLog("START TIME ", getTimestamp()); if (hRequest == null) { doLog(" requestURI", NON_HTTP_REQ_MSG); doLog(" authType", NON_HTTP_REQ_MSG); } else { doLog(" requestURI", hRequest.getRequestURI()); doLog(" authType", hRequest.getAuthType()); } doLog(" characterEncoding", request.getCharacterEncoding()); doLog(" contentLength", Integer.valueOf(request.getContentLength()).toString()); doLog(" contentType", request.getContentType()); if (hRequest == null) { doLog(" contextPath", NON_HTTP_REQ_MSG); doLog(" cookie", NON_HTTP_REQ_MSG); doLog(" header", NON_HTTP_REQ_MSG); } else { doLog(" contextPath", hRequest.getContextPath()); Cookie cookies[] = hRequest.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { doLog(" cookie", cookies[i].getName() + "=" + cookies[i].getValue()); } } Enumeration<String> hnames = hRequest.getHeaderNames(); while (hnames.hasMoreElements()) { String hname = hnames.nextElement(); Enumeration<String> hvalues = hRequest.getHeaders(hname); while (hvalues.hasMoreElements()) { String hvalue = hvalues.nextElement(); doLog(" header", hname + "=" + hvalue); } } } doLog(" locale", request.getLocale().toString()); if (hRequest == null) { doLog(" method", NON_HTTP_REQ_MSG); } else { doLog(" method", hRequest.getMethod()); } Enumeration<String> pnames = request.getParameterNames(); while (pnames.hasMoreElements()) { String pname = pnames.nextElement(); String pvalues[] = request.getParameterValues(pname); StringBuilder result = new StringBuilder(pname); result.append('='); for (int i = 0; i < pvalues.length; i++) { if (i > 0) { result.append(", "); } result.append(pvalues[i]); } doLog(" parameter", result.toString()); } if (hRequest == null) { doLog(" pathInfo", NON_HTTP_REQ_MSG); } else { doLog(" pathInfo", hRequest.getPathInfo()); } doLog(" protocol", request.getProtocol()); if (hRequest == null) { doLog(" queryString", NON_HTTP_REQ_MSG); } else { doLog(" queryString", hRequest.getQueryString()); } doLog(" remoteAddr", request.getRemoteAddr()); doLog(" remoteHost", request.getRemoteHost()); if (hRequest == null) { doLog(" remoteUser", NON_HTTP_REQ_MSG); doLog("requestedSessionId", NON_HTTP_REQ_MSG); } else { doLog(" remoteUser", hRequest.getRemoteUser()); doLog("requestedSessionId", hRequest.getRequestedSessionId()); } doLog(" scheme", request.getScheme()); doLog(" serverName", request.getServerName()); doLog(" serverPort", Integer.valueOf(request.getServerPort()).toString()); if (hRequest == null) { doLog(" servletPath", NON_HTTP_REQ_MSG); } else { doLog(" servletPath", hRequest.getServletPath()); } doLog(" isSecure", Boolean.valueOf(request.isSecure()).toString()); doLog("------------------", "--------------------------------------------"); // Perform the request chain.doFilter(request, response); // Log post-service information doLog("------------------", "--------------------------------------------"); if (hRequest == null) { doLog(" authType", NON_HTTP_REQ_MSG); } else { doLog(" authType", hRequest.getAuthType()); } doLog(" contentType", response.getContentType()); if (hResponse == null) { doLog(" header", NON_HTTP_RES_MSG); } else { Iterable<String> rhnames = hResponse.getHeaderNames(); for (String rhname : rhnames) { Iterable<String> rhvalues = hResponse.getHeaders(rhname); for (String rhvalue : rhvalues) { doLog(" header", rhname + "=" + rhvalue); } } } if (hRequest == null) { doLog(" remoteUser", NON_HTTP_REQ_MSG); } else { doLog(" remoteUser", hRequest.getRemoteUser()); } if (hResponse == null) { doLog(" remoteUser", NON_HTTP_RES_MSG); } else { doLog(" status", Integer.valueOf(hResponse.getStatus()).toString()); } doLog("END TIME ", getTimestamp()); doLog("==================", "============================================"); }
// in java/org/apache/catalina/filters/RequestFilter.java
protected void process(String property, ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (isAllowed(property)) { chain.doFilter(request, response); } else { if (response instanceof HttpServletResponse) { ((HttpServletResponse) response).sendError(denyStatus); } else { sendErrorWhenNotHttp(response); } } }
// in java/org/apache/catalina/filters/RequestFilter.java
protected void processCometEvent(String property, CometEvent event, CometFilterChain chain) throws IOException, ServletException { HttpServletResponse response = event.getHttpServletResponse(); if (isAllowed(property)) { chain.doFilterEvent(event); } else { response.sendError(denyStatus); event.close(); } }
// in java/org/apache/catalina/filters/RequestFilter.java
private void sendErrorWhenNotHttp(ServletResponse response) throws IOException { response.setContentType(PLAIN_TEXT_MIME_TYPE); response.getWriter().write(sm.getString("http.403")); response.getWriter().flush(); }
// in java/org/apache/catalina/filters/AddDefaultCharsetFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Wrap the response if (response instanceof HttpServletResponse) { ResponseWrapper wrapped = new ResponseWrapper((HttpServletResponse)response, encoding); chain.doFilter(request, wrapped); } else { chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/RemoteHostFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { process(request.getRemoteHost(), request, response, chain); }
// in java/org/apache/catalina/filters/RemoteHostFilter.java
Override public void doFilterEvent(CometEvent event, CometFilterChain chain) throws IOException, ServletException { processCometEvent(event.getHttpServletRequest().getRemoteHost(), event, chain); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public ServletOutputStream getOutputStream() throws IOException { if (servletOutputStream == null) { servletOutputStream = new XServletOutputStream( super.getOutputStream(), request, this); } return servletOutputStream; }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public PrintWriter getWriter() throws IOException { if (printWriter == null) { printWriter = new XPrintWriter(super.getWriter(), request, this); } return printWriter; }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void close() throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.close(); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void flush() throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.flush(); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void print(boolean b) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.print(b); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void print(char c) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.print(c); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void print(double d) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.print(d); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void print(float f) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.print(f); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void print(int i) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.print(i); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void print(long l) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.print(l); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void print(String s) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.print(s); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println() throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println(boolean b) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(b); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println(char c) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(c); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println(double d) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(d); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println(float f) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(f); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println(int i) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(i); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println(long l) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(l); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println(String s) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(s); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void write(byte[] b) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.write(b); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void write(byte[] b, int off, int len) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.write(b, off, len); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void write(int b) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.write(b); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (response.isCommitted()) { if (log.isDebugEnabled()) { log.debug(sm.getString( "expiresFilter.responseAlreadyCommited", httpRequest.getRequestURL())); } chain.doFilter(request, response); } else { XHttpServletResponse xResponse = new XHttpServletResponse( httpRequest, httpResponse); chain.doFilter(request, xResponse); if (!xResponse.isWriteResponseBodyStarted()) { // Empty response, manually trigger // onBeforeWriteResponseBody() onBeforeWriteResponseBody(httpRequest, xResponse); } } } else { chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (internalProxies != null && internalProxies.matcher(request.getRemoteAddr()).matches()) { String remoteIp = null; // In java 6, proxiesHeaderValue should be declared as a java.util.Deque LinkedList<String> proxiesHeaderValue = new LinkedList<String>(); StringBuilder concatRemoteIpHeaderValue = new StringBuilder(); for (Enumeration<String> e = request.getHeaders(remoteIpHeader); e.hasMoreElements();) { if (concatRemoteIpHeaderValue.length() > 0) { concatRemoteIpHeaderValue.append(", "); } concatRemoteIpHeaderValue.append(e.nextElement()); } String[] remoteIpHeaderValue = commaDelimitedListToStringArray(concatRemoteIpHeaderValue.toString()); int idx; // loop on remoteIpHeaderValue to find the first trusted remote ip and to build the proxies chain for (idx = remoteIpHeaderValue.length - 1; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; remoteIp = currentRemoteIp; if (internalProxies.matcher(currentRemoteIp).matches()) { // do nothing, internalProxies IPs are not appended to the } else if (trustedProxies != null && trustedProxies.matcher(currentRemoteIp).matches()) { proxiesHeaderValue.addFirst(currentRemoteIp); } else { idx--; // decrement idx because break statement doesn't do it break; } } // continue to loop on remoteIpHeaderValue to build the new value of the remoteIpHeader LinkedList<String> newRemoteIpHeaderValue = new LinkedList<String>(); for (; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; newRemoteIpHeaderValue.addFirst(currentRemoteIp); } XForwardedRequest xRequest = new XForwardedRequest(request); if (remoteIp != null) { xRequest.setRemoteAddr(remoteIp); xRequest.setRemoteHost(remoteIp); if (proxiesHeaderValue.size() == 0) { xRequest.removeHeader(proxiesHeader); } else { String commaDelimitedListOfProxies = listToCommaDelimitedString(proxiesHeaderValue); xRequest.setHeader(proxiesHeader, commaDelimitedListOfProxies); } if (newRemoteIpHeaderValue.size() == 0) { xRequest.removeHeader(remoteIpHeader); } else { String commaDelimitedRemoteIpHeaderValue = listToCommaDelimitedString(newRemoteIpHeaderValue); xRequest.setHeader(remoteIpHeader, commaDelimitedRemoteIpHeaderValue); } } if (protocolHeader != null) { String protocolHeaderValue = request.getHeader(protocolHeader); if (protocolHeaderValue == null) { // don't modify the secure,scheme and serverPort attributes of the request } else if (protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue)) { xRequest.setSecure(true); xRequest.setScheme("https"); setPorts(xRequest, httpsServerPort); } else { xRequest.setSecure(false); xRequest.setScheme("http"); setPorts(xRequest, httpServerPort); } } if (log.isDebugEnabled()) { log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "', originalRemoteHost='" + request.getRemoteHost() + "', originalSecure='" + request.isSecure() + "', originalScheme='" + request.getScheme() + "', original[" + remoteIpHeader + "]='" + concatRemoteIpHeaderValue + "', original[" + protocolHeader + "]='" + (protocolHeader == null ? null : request.getHeader(protocolHeader)) + "' will be seen as newRemoteAddr='" + xRequest.getRemoteAddr() + "', newRemoteHost='" + xRequest.getRemoteHost() + "', newScheme='" + xRequest.getScheme() + "', newSecure='" + xRequest.isSecure() + "', new[" + remoteIpHeader + "]='" + xRequest.getHeader(remoteIpHeader) + "', new[" + proxiesHeader + "]='" + xRequest.getHeader(proxiesHeader) + "'"); } if (requestAttributesEnabled) { request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE, request.getRemoteAddr()); request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE, request.getRemoteHost()); request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE, request.getProtocol()); request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE, Integer.valueOf(request.getServerPort())); } chain.doFilter(xRequest, response); } else { if (log.isDebugEnabled()) { log.debug("Skip RemoteIpFilter for request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "'"); } chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { doFilter((HttpServletRequest)request, (HttpServletResponse)response, chain); } else { chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/WebdavFixFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { chain.doFilter(request, response); return; } HttpServletRequest httpRequest = ((HttpServletRequest) request); HttpServletResponse httpResponse = ((HttpServletResponse) response); String ua = httpRequest.getHeader("User-Agent"); if (ua == null || ua.length() == 0 || !ua.startsWith(UA_MINIDIR_START)) { // No UA or starts with non MS value // Hope everything just works... chain.doFilter(request, response); } else if (ua.startsWith(UA_MINIDIR_5_1_2600)) { // XP 32-bit SP3 - needs redirect with explicit port httpResponse.sendRedirect(buildRedirect(httpRequest)); } else if (ua.startsWith(UA_MINIDIR_5_2_3790)) { // XP 64-bit SP2 if (!"".equals(httpRequest.getContextPath())) { log(request, "XP-x64-SP2 clients only work with the root context"); } // Namespace issue maybe // see http://greenbytes.de/tech/webdav/webdav-redirector-list.html log(request, "XP-x64-SP2 is known not to work with WebDAV Servlet"); chain.doFilter(request, response); } else { // Don't know which MS client it is - try the redirect with an // explicit port in the hope that it moves the client to a different // WebDAV implementation that works httpResponse.sendRedirect(buildRedirect(httpRequest)); } }
// in java/org/apache/catalina/filters/RemoteAddrFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { process(request.getRemoteAddr(), request, response, chain); }
// in java/org/apache/catalina/filters/RemoteAddrFilter.java
Override public void doFilterEvent(CometEvent event, CometFilterChain chain) throws IOException, ServletException { processCometEvent(event.getHttpServletRequest().getRemoteAddr(), event, chain); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ServletResponse wResponse = null; if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; boolean skipNonceCheck = false; if (Constants.METHOD_GET.equals(req.getMethod())) { String path = req.getServletPath(); if (req.getPathInfo() != null) { path = path + req.getPathInfo(); } if (entryPoints.contains(path)) { skipNonceCheck = true; } } @SuppressWarnings("unchecked") LruCache<String> nonceCache = (LruCache<String>) req.getSession(true).getAttribute( Constants.CSRF_NONCE_SESSION_ATTR_NAME); if (!skipNonceCheck) { String previousNonce = req.getParameter(Constants.CSRF_NONCE_REQUEST_PARAM); if (nonceCache != null && !nonceCache.contains(previousNonce)) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } if (nonceCache == null) { nonceCache = new LruCache<String>(nonceCacheSize); req.getSession().setAttribute( Constants.CSRF_NONCE_SESSION_ATTR_NAME, nonceCache); } String newNonce = generateNonce(); nonceCache.add(newNonce); wResponse = new CsrfResponseWrapper(res, newNonce); } else { wResponse = response; } chain.doFilter(request, wResponse); }
// in java/org/apache/catalina/filters/FailedRequestFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!isGoodRequest(request)) { ((HttpServletResponse) response) .sendError(HttpServletResponse.SC_BAD_REQUEST); return; } chain.doFilter(request, response); }
// in java/org/apache/catalina/filters/FailedRequestFilter.java
Override public void doFilterEvent(CometEvent event, CometFilterChain chain) throws IOException, ServletException { if (event.getEventType() == CometEvent.EventType.BEGIN && !isGoodRequest(event.getHttpServletRequest())) { event.getHttpServletResponse().sendError( HttpServletResponse.SC_BAD_REQUEST); event.close(); return; } chain.doFilterEvent(event); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
public static MBeanServerConnection createJMXConnection(String url, String host, String port, String username, String password) throws MalformedURLException, IOException { String urlForJMX; if (url != null) urlForJMX = url; else urlForJMX = JMX_SERVICE_PREFIX + host + ":" + port + JMX_SERVICE_SUFFIX; Map<String, String[]> environment = null; if (username != null && password != null) { String[] credentials = new String[2]; credentials[0] = username; credentials[1] = password; environment = new HashMap<String, String[]>(); environment.put(JMXConnector.CREDENTIALS, credentials); } return JMXConnectorFactory.connect(new JMXServiceURL(urlForJMX), environment).getMBeanServerConnection(); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
protected MBeanServerConnection getJMXConnection() throws MalformedURLException, IOException { MBeanServerConnection jmxServerConnection = null; if (isUseRef()) { Object pref = null ; if(getProject() != null) { pref = getProject().getReference(getRef()); if (pref != null) { try { jmxServerConnection = (MBeanServerConnection) pref; } catch (ClassCastException cce) { getProject().log( "Wrong object reference " + getRef() + " - " + pref.getClass()); return null; } } } if (jmxServerConnection == null) { jmxServerConnection = accessJMXConnection(getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), getRef()); } } else { jmxServerConnection = accessJMXConnection(getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), null); } return jmxServerConnection; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorEqualsCondition.java
protected MBeanServerConnection getJMXConnection() throws MalformedURLException, IOException { return JMXAccessorTask.accessJMXConnection( getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), ref); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorCondition.java
protected MBeanServerConnection getJMXConnection() throws MalformedURLException, IOException { return JMXAccessorTask.accessJMXConnection( getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), ref); }
// in java/org/apache/catalina/websocket/WebSocketServlet.java
Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Information required to send the server handshake message String key; String subProtocol = null; List<String> extensions = Collections.emptyList(); if (!headerContainsToken(req, "upgrade", "websocket")) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (!headerContainsToken(req, "connection", "upgrade")) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (!headerContainsToken(req, "sec-websocket-version", "13")) { resp.setStatus(426); resp.setHeader("Sec-WebSocket-Version", "13"); return; } key = req.getHeader("Sec-WebSocket-Key"); if (key == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } String origin = req.getHeader("Origin"); if (!verifyOrigin(origin)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } List<String> subProtocols = getTokensFromHeader(req, "Sec-WebSocket-Protocol-Client"); if (!subProtocols.isEmpty()) { subProtocol = selectSubProtocol(subProtocols); } // TODO Read client handshake - Sec-WebSocket-Extensions // TODO Extensions require the ability to specify something (API TBD) // that can be passed to the Tomcat internals and process extension // data present when the frame is fragmented. // If we got this far, all is good. Accept the connection. resp.setHeader("Upgrade", "websocket"); resp.setHeader("Connection", "upgrade"); resp.setHeader("Sec-WebSocket-Accept", getWebSocketAccept(key)); if (subProtocol != null) { resp.setHeader("Sec-WebSocket-Protocol", subProtocol); } if (!extensions.isEmpty()) { // TODO } // Small hack until the Servlet API provides a way to do this. StreamInbound inbound = createWebSocketInbound(subProtocol); ((RequestFacade) req).doUpgrade(inbound); }
// in java/org/apache/catalina/websocket/MessageInbound.java
Override protected final void onBinaryData(InputStream is) throws IOException { int read = 0; while (read > -1) { bb.position(bb.position() + read); if (bb.remaining() == 0) { resizeByteBuffer(); } read = is.read(bb.array(), bb.position(), bb.remaining()); } bb.flip(); onBinaryMessage(bb); bb.clear(); }
// in java/org/apache/catalina/websocket/MessageInbound.java
Override protected final void onTextData(Reader r) throws IOException { int read = 0; while (read > -1) { cb.position(cb.position() + read); if (cb.remaining() == 0) { resizeCharBuffer(); } read = r.read(cb.array(), cb.position(), cb.remaining()); } cb.flip(); onTextMessage(cb); cb.clear(); }
// in java/org/apache/catalina/websocket/MessageInbound.java
private void resizeByteBuffer() throws IOException { int maxSize = getByteBufferMaxSize(); if (bb.limit() >= maxSize) { throw new IOException(sm.getString("message.bufferTooSmall")); } long newSize = bb.limit() * 2; if (newSize > maxSize) { newSize = maxSize; } // Cast is safe. newSize < maxSize and maxSize is an int ByteBuffer newBuffer = ByteBuffer.allocate((int) newSize); bb.rewind(); newBuffer.put(bb); bb = newBuffer; }
// in java/org/apache/catalina/websocket/MessageInbound.java
private void resizeCharBuffer() throws IOException { int maxSize = getCharBufferMaxSize(); if (cb.limit() >= maxSize) { throw new IOException(sm.getString("message.bufferTooSmall")); } long newSize = cb.limit() * 2; if (newSize > maxSize) { newSize = maxSize; } // Cast is safe. newSize < maxSize and maxSize is an int CharBuffer newBuffer = CharBuffer.allocate((int) newSize); cb.rewind(); newBuffer.put(cb); cb = newBuffer; }
// in java/org/apache/catalina/websocket/StreamInbound.java
Override public final SocketState onData() throws IOException { // Must be start the start of a message (which may consist of multiple // frames) WsInputStream wsIs = new WsInputStream(processor, getWsOutbound()); try { WsFrame frame = wsIs.nextFrame(true); while (frame != null) { // TODO User defined extensions may define values for rsv if (frame.getRsv() > 0) { closeOutboundConnection( Constants.STATUS_PROTOCOL_ERROR, null); return SocketState.CLOSED; } byte opCode = frame.getOpCode(); if (opCode == Constants.OPCODE_BINARY) { onBinaryData(wsIs); } else if (opCode == Constants.OPCODE_TEXT) { InputStreamReader r = new InputStreamReader(wsIs, new Utf8Decoder()); onTextData(r); } else if (opCode == Constants.OPCODE_CLOSE){ closeOutboundConnection(frame); return SocketState.CLOSED; } else if (opCode == Constants.OPCODE_PING) { getWsOutbound().pong(frame.getPayLoad()); } else if (opCode == Constants.OPCODE_PONG) { // NO-OP } else { // Unknown OpCode closeOutboundConnection( Constants.STATUS_PROTOCOL_ERROR, null); return SocketState.CLOSED; } frame = wsIs.nextFrame(false); } } catch (MalformedInputException mie) { // Invalid UTF-8 closeOutboundConnection(Constants.STATUS_BAD_DATA, null); return SocketState.CLOSED; } catch (UnmappableCharacterException uce) { // Invalid UTF-8 closeOutboundConnection(Constants.STATUS_BAD_DATA, null); return SocketState.CLOSED; } catch (IOException ioe) { // Given something must have gone to reach this point, this // might not work but try it anyway. closeOutboundConnection(Constants.STATUS_PROTOCOL_ERROR, null); return SocketState.CLOSED; } return SocketState.UPGRADED; }
// in java/org/apache/catalina/websocket/StreamInbound.java
private void closeOutboundConnection(int status, ByteBuffer data) throws IOException { try { getWsOutbound().close(status, data); } finally { onClose(status); } }
// in java/org/apache/catalina/websocket/StreamInbound.java
private void closeOutboundConnection(WsFrame frame) throws IOException { try { getWsOutbound().close(frame); } finally { onClose(Constants.OPCODE_CLOSE); } }
// in java/org/apache/catalina/websocket/WsInputStream.java
public WsFrame nextFrame(boolean block) throws IOException { frame = WsFrame.nextFrame(processor, block); if (frame != null) { readThisFragment = 0; remaining = frame.getPayLoadLength(); } return frame; }
// in java/org/apache/catalina/websocket/WsInputStream.java
Override public int read() throws IOException { makePayloadDataAvailable(); if (remaining == 0) { return -1; } remaining--; readThisFragment++; int masked = processor.read(); if(masked == -1) { return -1; } return masked ^ (frame.getMask()[(int) ((readThisFragment - 1) % 4)] & 0xFF); }
// in java/org/apache/catalina/websocket/WsInputStream.java
Override public int read(byte b[], int off, int len) throws IOException { makePayloadDataAvailable(); if (remaining == 0) { return -1; } if (len > remaining) { len = (int) remaining; } int result = processor.read(true, b, off, len); if(result == -1) { return -1; } for (int i = off; i < off + result; i++) { b[i] = (byte) (b[i] ^ frame.getMask()[(int) ((readThisFragment + i - off) % 4)]); } remaining -= result; readThisFragment += result; return result; }
// in java/org/apache/catalina/websocket/WsInputStream.java
private void makePayloadDataAvailable() throws IOException { if (error != null) { throw new IOException(error); } while (remaining == 0 && !frame.getFin()) { // Need more data - process next frame nextFrame(true); while (frame.isControl()) { if (frame.getOpCode() == Constants.OPCODE_PING) { outbound.pong(frame.getPayLoad()); } else if (frame.getOpCode() == Constants.OPCODE_PONG) { // NO-OP. Swallow it. } else if (frame.getOpCode() == Constants.OPCODE_CLOSE) { outbound.close(frame); } else{ throw new IOException(sm.getString("is.unknownOpCode", Byte.valueOf(frame.getOpCode()))); } nextFrame(true); } if (frame.getOpCode() != Constants.OPCODE_CONTINUATION) { error = sm.getString("is.notContinuation", Byte.valueOf(frame.getOpCode())); throw new IOException(error); } } }
// in java/org/apache/catalina/websocket/WsFrame.java
private int blockingRead(UpgradeProcessor<?> processor) throws IOException { int result = processor.read(); if (result == -1) { throw new IOException(sm.getString("frame.eos")); } return result; }
// in java/org/apache/catalina/websocket/WsFrame.java
private void blockingRead(UpgradeProcessor<?> processor, byte[] bytes) throws IOException { int read = 0; int last = 0; while (read < bytes.length) { last = processor.read(true, bytes, read, bytes.length - read); if (last == -1) { throw new IOException(sm.getString("frame.eos")); } read += last; } }
// in java/org/apache/catalina/websocket/WsFrame.java
private void blockingRead(UpgradeProcessor<?> processor, ByteBuffer bb) throws IOException { int last = 0; while (bb.hasRemaining()) { last = processor.read(); if (last == -1) { throw new IOException(sm.getString("frame.eos")); } bb.put((byte) (last ^ mask[bb.position() % 4])); } bb.flip(); }
// in java/org/apache/catalina/websocket/WsFrame.java
public static WsFrame nextFrame(UpgradeProcessor<?> processor, boolean block) throws IOException { byte[] first = new byte[1]; int read = processor.read(block, first, 0, 1); if (read == 1) { return new WsFrame(first[0], processor); } else if (read == 0) { return null; } else if (read == -1) { throw new EOFException(sm.getString("frame.readEos")); } else { throw new IOException( sm.getString("frame.readFailed", Integer.valueOf(read))); } }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeBinaryData(int b) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (bb.position() == bb.capacity()) { doFlush(false); } if (text == null) { text = Boolean.FALSE; } else if (text == Boolean.TRUE) { // Flush the character data flush(); text = Boolean.FALSE; } bb.put((byte) (b & 0xFF)); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeTextData(char c) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (cb.position() == cb.capacity()) { doFlush(false); } if (text == null) { text = Boolean.TRUE; } else if (text == Boolean.FALSE) { // Flush the binary data flush(); text = Boolean.TRUE; } cb.append(c); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeBinaryMessage(ByteBuffer msgBb) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (text != null) { // Empty the buffer flush(); } text = Boolean.FALSE; doWriteBytes(msgBb, true); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeTextMessage(CharBuffer msgCb) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (text != null) { // Empty the buffer flush(); } text = Boolean.TRUE; doWriteText(msgCb, true); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void flush() throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } doFlush(true); }
// in java/org/apache/catalina/websocket/WsOutbound.java
private void doFlush(boolean finalFragment) throws IOException { if (text == null) { // No data return; } if (text.booleanValue()) { cb.flip(); doWriteText(cb, finalFragment); } else { bb.flip(); doWriteBytes(bb, finalFragment); } }
// in java/org/apache/catalina/websocket/WsOutbound.java
protected void close(WsFrame frame) throws IOException { if (frame.getPayLoadLength() > 0) { // Must be status (2 bytes) plus optional message if (frame.getPayLoadLength() == 1) { throw new IOException(); } int status = (frame.getPayLoad().get() & 0xFF) << 8; status += frame.getPayLoad().get() & 0xFF; if (validateCloseStatus(status)) { // Echo the status back to the client close(status, frame.getPayLoad()); } else { // Invalid close code close(Constants.STATUS_PROTOCOL_ERROR, null); } } else { // No status close(0, null); } }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void close(int status, ByteBuffer data) throws IOException { if (closed) { return; } closed = true; upgradeOutbound.write(0x88); if (status == 0) { upgradeOutbound.write(0); } else if (data == null || data.position() == data.limit()) { upgradeOutbound.write(2); upgradeOutbound.write(status >>> 8); upgradeOutbound.write(status); } else { upgradeOutbound.write(2 + data.limit() - data.position()); upgradeOutbound.write(status >>> 8); upgradeOutbound.write(status); upgradeOutbound.write(data.array(), data.position(), data.limit() - data.position()); } upgradeOutbound.flush(); bb = null; cb = null; upgradeOutbound = null; }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void pong(ByteBuffer data) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } doFlush(true); upgradeOutbound.write(0x8A); if (data == null) { upgradeOutbound.write(0); } else { upgradeOutbound.write(data.limit() - data.position()); upgradeOutbound.write(data.array(), data.position(), data.limit() - data.position()); } upgradeOutbound.flush(); }
// in java/org/apache/catalina/websocket/WsOutbound.java
private void doWriteBytes(ByteBuffer buffer, boolean finalFragment) throws IOException { // Work out the first byte int first = 0x00; if (finalFragment) { first = first + 0x80; } if (firstFrame) { if (text.booleanValue()) { first = first + 0x1; } else { first = first + 0x2; } } // Continuation frame is OpCode 0 upgradeOutbound.write(first); if (buffer.limit() < 126) { upgradeOutbound.write(buffer.limit()); } else if (buffer.limit() < 65536) { upgradeOutbound.write(126); upgradeOutbound.write(buffer.limit() >>> 8); upgradeOutbound.write(buffer.limit() & 0xFF); } else { // Will never be more than 2^31-1 upgradeOutbound.write(127); upgradeOutbound.write(0); upgradeOutbound.write(0); upgradeOutbound.write(0); upgradeOutbound.write(0); upgradeOutbound.write(buffer.limit() >>> 24); upgradeOutbound.write(buffer.limit() >>> 16); upgradeOutbound.write(buffer.limit() >>> 8); upgradeOutbound.write(buffer.limit() & 0xFF); } // Write the content upgradeOutbound.write(buffer.array(), 0, buffer.limit()); upgradeOutbound.flush(); // Reset if (finalFragment) { text = null; firstFrame = true; } else { firstFrame = false; } bb.clear(); }
// in java/org/apache/catalina/websocket/WsOutbound.java
private void doWriteText(CharBuffer buffer, boolean finalFragment) throws IOException { CharsetEncoder encoder = B2CConverter.UTF_8.newEncoder(); do { CoderResult cr = encoder.encode(buffer, bb, true); if (cr.isError()) { cr.throwException(); } bb.flip(); if (buffer.hasRemaining()) { doWriteBytes(bb, false); } else { doWriteBytes(bb, finalFragment); } } while (buffer.hasRemaining()); // Reset - bb will be cleared in doWriteBytes() cb.clear(); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need // By obtaining the command from the pathInfo, per-command security can // be configured in web.xml String command = request.getPathInfo(); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Process the requested command if (command == null || command.equals("/")) { // No command == list } else if (command.equals("/list")) { // List always displayed - nothing to do here } else if (command.equals("/sessions")) { try { doSessions(cn, request, response, smClient); return; } catch (Exception e) { log("HTMLManagerServlet.sessions[" + cn + "]", e); message = smClient.getString("managerServlet.exception", e.toString()); } } else if (command.equals("/upload") || command.equals("/deploy") || command.equals("/reload") || command.equals("/undeploy") || command.equals("/expire") || command.equals("/start") || command.equals("/stop")) { message = smClient.getString("managerServlet.postCommand", command); } else { message = smClient.getString("managerServlet.unknownCommand", command); } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need // By obtaining the command from the pathInfo, per-command security can // be configured in web.xml String command = request.getPathInfo(); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } String deployPath = request.getParameter("deployPath"); ContextName deployCn = null; if (deployPath != null) { deployCn = new ContextName(deployPath, request.getParameter("deployVersion")); } String deployConfig = request.getParameter("deployConfig"); String deployWar = request.getParameter("deployWar"); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; if (command == null || command.length() == 0) { // No command == list // List always displayed -> do nothing } else if (command.equals("/upload")) { message = upload(request, smClient); } else if (command.equals("/deploy")) { message = deployInternal(deployConfig, deployCn, deployWar, smClient); } else if (command.equals("/reload")) { message = reload(cn, smClient); } else if (command.equals("/undeploy")) { message = undeploy(cn, smClient); } else if (command.equals("/expire")) { message = expireSessions(cn, request, smClient); } else if (command.equals("/start")) { message = start(cn, smClient); } else if (command.equals("/stop")) { message = stop(cn, smClient); } else if (command.equals("/findleaks")) { message = findleaks(smClient); } else { // Try GET doGet(request,response); return; } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected String upload(HttpServletRequest request, StringManager smClient) throws IOException, ServletException { String message = ""; Part warPart = null; String filename = null; Collection<Part> parts = request.getParts(); Iterator<Part> iter = parts.iterator(); try { while (iter.hasNext()) { Part part = iter.next(); if (part.getName().equals("deployWar") && warPart == null) { warPart = part; } else { part.delete(); } } while (true) { if (warPart == null) { message = smClient.getString( "htmlManagerServlet.deployUploadNoFile"); break; } filename = extractFilename(warPart.getHeader("Content-Disposition")); if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) { message = smClient.getString( "htmlManagerServlet.deployUploadNotWar", filename); break; } // Get the filename if uploaded name includes a path if (filename.lastIndexOf('\\') >= 0) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (filename.lastIndexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } // Identify the appBase of the owning Host of this Context // (if any) File file = new File(host.getAppBaseFile(), filename); if (file.exists()) { message = smClient.getString( "htmlManagerServlet.deployUploadWarExists", filename); break; } ContextName cn = new ContextName(filename); String name = cn.getName(); if ((host.findChild(name) != null) && !isDeployed(name)) { message = smClient.getString( "htmlManagerServlet.deployUploadInServerXml", filename); break; } if (!isServiced(name)) { addServiced(name); try { warPart.write(file.getAbsolutePath()); // Perform new deployment check(name); } finally { removeServiced(name); } } break; } } catch(Exception e) { message = smClient.getString ("htmlManagerServlet.deployUploadFail", e.getMessage()); log(message, e); } finally { if (warPart != null) { warPart.delete(); } warPart = null; } return message; }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected void list(HttpServletRequest request, HttpServletResponse response, String message, StringManager smClient) throws IOException { if (debug >= 1) log("list: Listing contexts for virtual host '" + host.getName() + "'"); PrintWriter writer = response.getWriter(); // HTML Header Section writer.print(Constants.HTML_HEADER_SECTION); // Body Header Section Object[] args = new Object[2]; args[0] = request.getContextPath(); args[1] = smClient.getString("htmlManagerServlet.title"); writer.print(MessageFormat.format (Constants.BODY_HEADER_SECTION, args)); // Message Section args = new Object[3]; args[0] = smClient.getString("htmlManagerServlet.messageLabel"); if (message == null || message.length() == 0) { args[1] = "OK"; } else { args[1] = RequestUtil.filter(message); } writer.print(MessageFormat.format(Constants.MESSAGE_SECTION, args)); // Manager Section args = new Object[9]; args[0] = smClient.getString("htmlManagerServlet.manager"); args[1] = response.encodeURL(request.getContextPath() + "/html/list"); args[2] = smClient.getString("htmlManagerServlet.list"); args[3] = response.encodeURL (request.getContextPath() + "/" + smClient.getString("htmlManagerServlet.helpHtmlManagerFile")); args[4] = smClient.getString("htmlManagerServlet.helpHtmlManager"); args[5] = response.encodeURL (request.getContextPath() + "/" + smClient.getString("htmlManagerServlet.helpManagerFile")); args[6] = smClient.getString("htmlManagerServlet.helpManager"); args[7] = response.encodeURL (request.getContextPath() + "/status"); args[8] = smClient.getString("statusServlet.title"); writer.print(MessageFormat.format(Constants.MANAGER_SECTION, args)); // Apps Header Section args = new Object[7]; args[0] = smClient.getString("htmlManagerServlet.appsTitle"); args[1] = smClient.getString("htmlManagerServlet.appsPath"); args[2] = smClient.getString("htmlManagerServlet.appsVersion"); args[3] = smClient.getString("htmlManagerServlet.appsName"); args[4] = smClient.getString("htmlManagerServlet.appsAvailable"); args[5] = smClient.getString("htmlManagerServlet.appsSessions"); args[6] = smClient.getString("htmlManagerServlet.appsTasks"); writer.print(MessageFormat.format(APPS_HEADER_SECTION, args)); // Apps Row Section // Create sorted map of deployed applications by context name. Container children[] = host.findChildren(); String contextNames[] = new String[children.length]; for (int i = 0; i < children.length; i++) contextNames[i] = children[i].getName(); Arrays.sort(contextNames); String appsStart = smClient.getString("htmlManagerServlet.appsStart"); String appsStop = smClient.getString("htmlManagerServlet.appsStop"); String appsReload = smClient.getString("htmlManagerServlet.appsReload"); String appsUndeploy = smClient.getString("htmlManagerServlet.appsUndeploy"); String appsExpire = smClient.getString("htmlManagerServlet.appsExpire"); String noVersion = "<i>" + smClient.getString("htmlManagerServlet.noVersion") + "</i>"; boolean isHighlighted = true; boolean isDeployed = true; String highlightColor = null; for (String contextName : contextNames) { Context ctxt = (Context) host.findChild(contextName); if (ctxt != null) { // Bugzilla 34818, alternating row colors isHighlighted = !isHighlighted; if(isHighlighted) { highlightColor = "#C3F3C3"; } else { highlightColor = "#FFFFFF"; } String contextPath = ctxt.getPath(); String displayPath = contextPath; if (displayPath.equals("")) { displayPath = "/"; } StringBuilder tmp = new StringBuilder(); tmp.append("path="); tmp.append(URL_ENCODER.encode(displayPath)); if (ctxt.getWebappVersion().length() > 0) { tmp.append("&version="); tmp.append(URL_ENCODER.encode(ctxt.getWebappVersion())); } String pathVersion = tmp.toString(); try { isDeployed = isDeployed(contextName); } catch (Exception e) { // Assume false on failure for safety isDeployed = false; } args = new Object[7]; args[0] = "<a href=\"" + URL_ENCODER.encode(displayPath) + "\">" + RequestUtil.filter(displayPath) + "</a>"; if ("".equals(ctxt.getWebappVersion())) { args[1] = noVersion; } else { args[1] = RequestUtil.filter(ctxt.getWebappVersion()); } if (ctxt.getDisplayName() == null) { args[2] = "&nbsp;"; } else { args[2] = RequestUtil.filter(ctxt.getDisplayName()); } args[3] = Boolean.valueOf(ctxt.getAvailable()); args[4] = RequestUtil.filter(response.encodeURL(request.getContextPath() + "/html/sessions?" + pathVersion)); Manager manager = ctxt.getManager(); if (manager instanceof DistributedManager && showProxySessions) { args[5] = Integer.valueOf( ((DistributedManager)manager).getActiveSessionsFull()); } else if (ctxt.getManager() != null){ args[5] = Integer.valueOf(manager.getActiveSessions()); } else { args[5] = Integer.valueOf(0); } args[6] = highlightColor; writer.print (MessageFormat.format(APPS_ROW_DETAILS_SECTION, args)); args = new Object[14]; args[0] = RequestUtil.filter(response.encodeURL(request .getContextPath() + "/html/start?" + pathVersion)); args[1] = appsStart; args[2] = RequestUtil.filter(response.encodeURL(request .getContextPath() + "/html/stop?" + pathVersion)); args[3] = appsStop; args[4] = RequestUtil.filter(response.encodeURL(request .getContextPath() + "/html/reload?" + pathVersion)); args[5] = appsReload; args[6] = RequestUtil.filter(response.encodeURL(request .getContextPath() + "/html/undeploy?" + pathVersion)); args[7] = appsUndeploy; args[8] = RequestUtil.filter(response.encodeURL(request .getContextPath() + "/html/expire?" + pathVersion)); args[9] = appsExpire; args[10] = smClient.getString( "htmlManagerServlet.expire.explain"); if (manager == null) { args[11] = smClient.getString( "htmlManagerServlet.noManager"); } else { args[11] = Integer.valueOf( ctxt.getManager().getMaxInactiveInterval()/60); } args[12] = smClient.getString("htmlManagerServlet.expire.unit"); args[13] = highlightColor; if (ctxt.getName().equals(this.context.getName())) { writer.print(MessageFormat.format( MANAGER_APP_ROW_BUTTON_SECTION, args)); } else if (ctxt.getAvailable() && isDeployed) { writer.print(MessageFormat.format( STARTED_DEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } else if (ctxt.getAvailable() && !isDeployed) { writer.print(MessageFormat.format( STARTED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } else if (!ctxt.getAvailable() && isDeployed) { writer.print(MessageFormat.format( STOPPED_DEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } else { writer.print(MessageFormat.format( STOPPED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } } } // Deploy Section args = new Object[7]; args[0] = smClient.getString("htmlManagerServlet.deployTitle"); args[1] = smClient.getString("htmlManagerServlet.deployServer"); args[2] = response.encodeURL(request.getContextPath() + "/html/deploy"); args[3] = smClient.getString("htmlManagerServlet.deployPath"); args[4] = smClient.getString("htmlManagerServlet.deployConfig"); args[5] = smClient.getString("htmlManagerServlet.deployWar"); args[6] = smClient.getString("htmlManagerServlet.deployButton"); writer.print(MessageFormat.format(DEPLOY_SECTION, args)); args = new Object[4]; args[0] = smClient.getString("htmlManagerServlet.deployUpload"); args[1] = response.encodeURL(request.getContextPath() + "/html/upload"); args[2] = smClient.getString("htmlManagerServlet.deployUploadFile"); args[3] = smClient.getString("htmlManagerServlet.deployButton"); writer.print(MessageFormat.format(UPLOAD_SECTION, args)); // Diagnostics section args = new Object[5]; args[0] = smClient.getString("htmlManagerServlet.diagnosticsTitle"); args[1] = smClient.getString("htmlManagerServlet.diagnosticsLeak"); args[2] = response.encodeURL( request.getContextPath() + "/html/findleaks"); args[3] = smClient.getString("htmlManagerServlet.diagnosticsLeakWarning"); args[4] = smClient.getString("htmlManagerServlet.diagnosticsLeakButton"); writer.print(MessageFormat.format(DIAGNOSTICS_SECTION, args)); // Server Header Section args = new Object[9]; args[0] = smClient.getString("htmlManagerServlet.serverTitle"); args[1] = smClient.getString("htmlManagerServlet.serverVersion"); args[2] = smClient.getString("htmlManagerServlet.serverJVMVersion"); args[3] = smClient.getString("htmlManagerServlet.serverJVMVendor"); args[4] = smClient.getString("htmlManagerServlet.serverOSName"); args[5] = smClient.getString("htmlManagerServlet.serverOSVersion"); args[6] = smClient.getString("htmlManagerServlet.serverOSArch"); args[7] = sm.getString("htmlManagerServlet.serverHostname"); args[8] = sm.getString("htmlManagerServlet.serverIPAddress"); writer.print(MessageFormat.format (Constants.SERVER_HEADER_SECTION, args)); // Server Row Section args = new Object[8]; args[0] = ServerInfo.getServerInfo(); args[1] = System.getProperty("java.runtime.version"); args[2] = System.getProperty("java.vm.vendor"); args[3] = System.getProperty("os.name"); args[4] = System.getProperty("os.version"); args[5] = System.getProperty("os.arch"); try { InetAddress address = InetAddress.getLocalHost(); args[6] = address.getHostName(); args[7] = address.getHostAddress(); } catch (UnknownHostException e) { args[6] = "-"; args[7] = "-"; } writer.print(MessageFormat.format(Constants.SERVER_ROW_SECTION, args)); // HTML Tail Section writer.print(Constants.HTML_TAIL_SECTION); // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected void doSessions(ContextName cn, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { req.setAttribute("path", cn.getPath()); req.setAttribute("version", cn.getVersion()); String action = req.getParameter("action"); if (debug >= 1) { log("sessions: Session action '" + action + "' for web application '" + cn.getDisplayName() + "'"); } if ("sessionDetail".equals(action)) { String sessionId = req.getParameter("sessionId"); displaySessionDetailPage(req, resp, cn, sessionId, smClient); return; } else if ("invalidateSessions".equals(action)) { String[] sessionIds = req.getParameterValues("sessionIds"); int i = invalidateSessions(cn, sessionIds, smClient); req.setAttribute(APPLICATION_MESSAGE, "" + i + " sessions invalidated."); } else if ("removeSessionAttribute".equals(action)) { String sessionId = req.getParameter("sessionId"); String name = req.getParameter("attributeName"); boolean removed = removeSessionAttribute(cn, sessionId, name, smClient); String outMessage = removed ? "Session attribute '" + name + "' removed." : "Session did not contain any attribute named '" + name + "'"; req.setAttribute(APPLICATION_MESSAGE, outMessage); displaySessionDetailPage(req, resp, cn, sessionId, smClient); return; } // else displaySessionsListPage(cn, req, resp, smClient); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected void displaySessionsListPage(ContextName cn, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { List<Session> sessions = getSessionsForName(cn, smClient); String sortBy = req.getParameter("sort"); String orderBy = null; if (null != sortBy && !"".equals(sortBy.trim())) { Comparator<Session> comparator = getComparator(sortBy); if (comparator != null) { orderBy = req.getParameter("order"); if ("DESC".equalsIgnoreCase(orderBy)) { comparator = new ReverseComparator(comparator); orderBy = "ASC"; } else { orderBy = "DESC"; } try { Collections.sort(sessions, comparator); } catch (IllegalStateException ise) { // at least 1 of the sessions is invalidated req.setAttribute(APPLICATION_ERROR, "Can't sort session list: one session is invalidated"); } } else { log("WARNING: unknown sort order: " + sortBy); } } // keep sort order req.setAttribute("sort", sortBy); req.setAttribute("order", orderBy); req.setAttribute("activeSessions", sessions); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now getServletContext().getRequestDispatcher(sessionsListJspPath).include(req, resp); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected void displaySessionDetailPage(HttpServletRequest req, HttpServletResponse resp, ContextName cn, String sessionId, StringManager smClient) throws ServletException, IOException { Session session = getSessionForNameAndId(cn, sessionId, smClient); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now req.setAttribute("currentSession", session); getServletContext().getRequestDispatcher(resp.encodeURL(sessionDetailJspPath)).include(req, resp); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected int invalidateSessions(ContextName cn, String[] sessionIds, StringManager smClient) throws IOException { if (null == sessionIds) { return 0; } int nbAffectedSessions = 0; for (int i = 0; i < sessionIds.length; ++i) { String sessionId = sessionIds[i]; HttpSession session = getSessionForNameAndId(cn, sessionId, smClient).getSession(); if (null == session) { // Shouldn't happen, but let's play nice... if (debug >= 1) { log("WARNING: can't invalidate null session " + sessionId); } continue; } try { session.invalidate(); ++nbAffectedSessions; if (debug >= 1) { log("Invalidating session id " + sessionId); } } catch (IllegalStateException ise) { if (debug >= 1) { log("Can't invalidate already invalidated session id " + sessionId); } } } return nbAffectedSessions; }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected boolean removeSessionAttribute(ContextName cn, String sessionId, String attributeName, StringManager smClient) throws IOException { HttpSession session = getSessionForNameAndId(cn, sessionId, smClient).getSession(); if (null == session) { // Shouldn't happen, but let's play nice... if (debug >= 1) { log("WARNING: can't remove attribute '" + attributeName + "' for null session " + sessionId); } return false; } boolean wasPresent = (null != session.getAttribute(attributeName)); try { session.removeAttribute(attributeName); } catch (IllegalStateException ise) { if (debug >= 1) { log("Can't remote attribute '" + attributeName + "' for invalidated session id " + sessionId); } } return wasPresent; }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); PrintWriter writer = response.getWriter(); if( mBeanServer==null ) { writer.println("Error - No mbean server"); return; } String qry=request.getParameter("set"); if( qry!= null ) { String name=request.getParameter("att"); String val=request.getParameter("val"); setAttribute( writer, qry, name, val ); return; } qry=request.getParameter("get"); if( qry!= null ) { String name=request.getParameter("att"); getAttribute( writer, qry, name, request.getParameter("key") ); return; } qry = request.getParameter("invoke"); if(qry != null) { String opName=request.getParameter("op"); String ps = request.getParameter("ps"); String[] valuesStr; if (ps == null) { valuesStr = new String[0]; } else { valuesStr = ps.split(","); } invokeOperation( writer, qry, opName,valuesStr ); return; } qry=request.getParameter("qry"); if( qry == null ) { qry = "*:*"; } listBeans( writer, qry ); }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null) command = request.getServletPath(); String name = request.getParameter("name"); // Prepare our output writer to generate the response message response.setContentType("text/plain; charset=" + Constants.CHARSET); PrintWriter writer = response.getWriter(); // Process the requested command if (command == null) { writer.println(sm.getString("hostManagerServlet.noCommand")); } else if (command.equals("/add")) { add(request, writer, name, false, smClient); } else if (command.equals("/remove")) { remove(writer, name, smClient); } else if (command.equals("/list")) { list(writer, smClient); } else if (command.equals("/start")) { start(writer, name, smClient); } else if (command.equals("/stop")) { stop(writer, name, smClient); } else { writer.println(sm.getString("hostManagerServlet.unknownCommand", command)); } // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/host/HTMLHostManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Process the requested command if (command == null) { // No command == list } else if (command.equals("/list")) { // Nothing to do - always generate list } else if (command.equals("/add") || command.equals("/remove") || command.equals("/start") || command.equals("/stop")) { message = smClient.getString( "hostManagerServlet.postCommand", command); } else { message = smClient.getString( "hostManagerServlet.unknownCommand", command); } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/host/HTMLHostManagerServlet.java
Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); String name = request.getParameter("name"); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Process the requested command if (command == null) { // No command == list } else if (command.equals("/add")) { message = add(request, name, smClient); } else if (command.equals("/remove")) { message = remove(name, smClient); } else if (command.equals("/start")) { message = start(name, smClient); } else if (command.equals("/stop")) { message = stop(name, smClient); } else { //Try GET doGet(request, response); } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/host/HTMLHostManagerServlet.java
public void list(HttpServletRequest request, HttpServletResponse response, String message, StringManager smClient) throws IOException { if (debug >= 1) { log(sm.getString("hostManagerServlet.list", engine.getName())); } PrintWriter writer = response.getWriter(); // HTML Header Section writer.print(org.apache.catalina.manager.Constants.HTML_HEADER_SECTION); // Body Header Section Object[] args = new Object[2]; args[0] = request.getContextPath(); args[1] = smClient.getString("htmlHostManagerServlet.title"); writer.print(MessageFormat.format (Constants.BODY_HEADER_SECTION, args)); // Message Section args = new Object[3]; args[0] = smClient.getString("htmlHostManagerServlet.messageLabel"); if (message == null || message.length() == 0) { args[1] = "OK"; } else { args[1] = RequestUtil.filter(message); } writer.print(MessageFormat.format(Constants.MESSAGE_SECTION, args)); // Manager Section args = new Object[9]; args[0] = smClient.getString("htmlHostManagerServlet.manager"); args[1] = response.encodeURL(request.getContextPath() + "/html/list"); args[2] = smClient.getString("htmlHostManagerServlet.list"); args[3] = response.encodeURL (request.getContextPath() + "/" + smClient.getString("htmlHostManagerServlet.helpHtmlManagerFile")); args[4] = smClient.getString("htmlHostManagerServlet.helpHtmlManager"); args[5] = response.encodeURL (request.getContextPath() + "/" + smClient.getString("htmlHostManagerServlet.helpManagerFile")); args[6] = smClient.getString("htmlHostManagerServlet.helpManager"); args[7] = response.encodeURL("/manager/status"); args[8] = smClient.getString("statusServlet.title"); writer.print(MessageFormat.format(Constants.MANAGER_SECTION, args)); // Hosts Header Section args = new Object[3]; args[0] = smClient.getString("htmlHostManagerServlet.hostName"); args[1] = smClient.getString("htmlHostManagerServlet.hostAliases"); args[2] = smClient.getString("htmlHostManagerServlet.hostTasks"); writer.print(MessageFormat.format(HOSTS_HEADER_SECTION, args)); // Hosts Row Section // Create sorted map of host names. Container[] children = engine.findChildren(); String hostNames[] = new String[children.length]; for (int i = 0; i < children.length; i++) hostNames[i] = children[i].getName(); TreeMap<String,String> sortedHostNamesMap = new TreeMap<String,String>(); for (int i = 0; i < hostNames.length; i++) { String displayPath = hostNames[i]; sortedHostNamesMap.put(displayPath, hostNames[i]); } String hostsStart = smClient.getString("htmlHostManagerServlet.hostsStart"); String hostsStop = smClient.getString("htmlHostManagerServlet.hostsStop"); String hostsRemove = smClient.getString("htmlHostManagerServlet.hostsRemove"); Iterator<Map.Entry<String,String>> iterator = sortedHostNamesMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String,String> entry = iterator.next(); String hostName = entry.getKey(); Host host = (Host) engine.findChild(hostName); if (host != null ) { args = new Object[2]; args[0] = RequestUtil.filter(hostName); String[] aliases = host.findAliases(); StringBuilder buf = new StringBuilder(); if (aliases.length > 0) { buf.append(aliases[0]); for (int j = 1; j < aliases.length; j++) { buf.append(", ").append(aliases[j]); } } if (buf.length() == 0) { buf.append("&nbsp;"); args[1] = buf.toString(); } else { args[1] = RequestUtil.filter(buf.toString()); } writer.print (MessageFormat.format(HOSTS_ROW_DETAILS_SECTION, args)); args = new Object[4]; if (host.getState().isAvailable()) { args[0] = response.encodeURL (request.getContextPath() + "/html/stop?name=" + URLEncoder.encode(hostName, "UTF-8")); args[1] = hostsStop; } else { args[0] = response.encodeURL (request.getContextPath() + "/html/start?name=" + URLEncoder.encode(hostName, "UTF-8")); args[1] = hostsStart; } args[2] = response.encodeURL (request.getContextPath() + "/html/remove?name=" + URLEncoder.encode(hostName, "UTF-8")); args[3] = hostsRemove; if (host == this.installedHost) { writer.print(MessageFormat.format( MANAGER_HOST_ROW_BUTTON_SECTION, args)); } else { writer.print(MessageFormat.format( HOSTS_ROW_BUTTON_SECTION, args)); } } } // Add Section args = new Object[6]; args[0] = smClient.getString("htmlHostManagerServlet.addTitle"); args[1] = smClient.getString("htmlHostManagerServlet.addHost"); args[2] = response.encodeURL(request.getContextPath() + "/html/add"); args[3] = smClient.getString("htmlHostManagerServlet.addName"); args[4] = smClient.getString("htmlHostManagerServlet.addAliases"); args[5] = smClient.getString("htmlHostManagerServlet.addAppBase"); writer.print(MessageFormat.format(ADD_SECTION_START, args)); args = new Object[3]; args[0] = smClient.getString("htmlHostManagerServlet.addAutoDeploy"); args[1] = "autoDeploy"; args[2] = "checked"; writer.print(MessageFormat.format(ADD_SECTION_BOOLEAN, args)); args[0] = smClient.getString( "htmlHostManagerServlet.addDeployOnStartup"); args[1] = "deployOnStartup"; args[2] = "checked"; writer.print(MessageFormat.format(ADD_SECTION_BOOLEAN, args)); args[0] = smClient.getString("htmlHostManagerServlet.addDeployXML"); args[1] = "deployXML"; args[2] = "checked"; writer.print(MessageFormat.format(ADD_SECTION_BOOLEAN, args)); args[0] = smClient.getString("htmlHostManagerServlet.addUnpackWARs"); args[1] = "unpackWARs"; args[2] = "checked"; writer.print(MessageFormat.format(ADD_SECTION_BOOLEAN, args)); args[0] = smClient.getString("htmlHostManagerServlet.addManager"); args[1] = "manager"; args[2] = "checked"; writer.print(MessageFormat.format(ADD_SECTION_BOOLEAN, args)); args = new Object[1]; args[0] = smClient.getString("htmlHostManagerServlet.addButton"); writer.print(MessageFormat.format(ADD_SECTION_END, args)); // Server Header Section args = new Object[7]; args[0] = smClient.getString("htmlHostManagerServlet.serverTitle"); args[1] = smClient.getString("htmlHostManagerServlet.serverVersion"); args[2] = smClient.getString("htmlHostManagerServlet.serverJVMVersion"); args[3] = smClient.getString("htmlHostManagerServlet.serverJVMVendor"); args[4] = smClient.getString("htmlHostManagerServlet.serverOSName"); args[5] = smClient.getString("htmlHostManagerServlet.serverOSVersion"); args[6] = smClient.getString("htmlHostManagerServlet.serverOSArch"); writer.print(MessageFormat.format (Constants.SERVER_HEADER_SECTION, args)); // Server Row Section args = new Object[6]; args[0] = ServerInfo.getServerInfo(); args[1] = System.getProperty("java.runtime.version"); args[2] = System.getProperty("java.vm.vendor"); args[3] = System.getProperty("os.name"); args[4] = System.getProperty("os.version"); args[5] = System.getProperty("os.arch"); writer.print(MessageFormat.format(Constants.SERVER_ROW_SECTION, args)); // HTML Tail Section writer.print(Constants.HTML_TAIL_SECTION); // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // mode is flag for HTML or XML output int mode = 0; // if ?XML=true, set the mode to XML if (request.getParameter("XML") != null && request.getParameter("XML").equals("true")) { mode = 1; } StatusTransformer.setContentType(response, mode); PrintWriter writer = response.getWriter(); boolean completeStatus = false; if ((request.getPathInfo() != null) && (request.getPathInfo().equals("/all"))) { completeStatus = true; } // use StatusTransformer to output status Object[] args = new Object[1]; args[0] = request.getContextPath(); StatusTransformer.writeHeader(writer,args,mode); // Body Header Section args = new Object[2]; args[0] = request.getContextPath(); if (completeStatus) { args[1] = sm.getString("statusServlet.complete"); } else { args[1] = sm.getString("statusServlet.title"); } // use StatusTransformer to output status StatusTransformer.writeBody(writer,args,mode); // Manager Section args = new Object[9]; args[0] = sm.getString("htmlManagerServlet.manager"); args[1] = response.encodeURL(request.getContextPath() + "/html/list"); args[2] = sm.getString("htmlManagerServlet.list"); args[3] = response.encodeURL (request.getContextPath() + "/" + sm.getString("htmlManagerServlet.helpHtmlManagerFile")); args[4] = sm.getString("htmlManagerServlet.helpHtmlManager"); args[5] = response.encodeURL (request.getContextPath() + "/" + sm.getString("htmlManagerServlet.helpManagerFile")); args[6] = sm.getString("htmlManagerServlet.helpManager"); if (completeStatus) { args[7] = response.encodeURL (request.getContextPath() + "/status"); args[8] = sm.getString("statusServlet.title"); } else { args[7] = response.encodeURL (request.getContextPath() + "/status/all"); args[8] = sm.getString("statusServlet.complete"); } // use StatusTransformer to output status StatusTransformer.writeManager(writer,args,mode); // Server Header Section args = new Object[9]; args[0] = sm.getString("htmlManagerServlet.serverTitle"); args[1] = sm.getString("htmlManagerServlet.serverVersion"); args[2] = sm.getString("htmlManagerServlet.serverJVMVersion"); args[3] = sm.getString("htmlManagerServlet.serverJVMVendor"); args[4] = sm.getString("htmlManagerServlet.serverOSName"); args[5] = sm.getString("htmlManagerServlet.serverOSVersion"); args[6] = sm.getString("htmlManagerServlet.serverOSArch"); args[7] = sm.getString("htmlManagerServlet.serverHostname"); args[8] = sm.getString("htmlManagerServlet.serverIPAddress"); // use StatusTransformer to output status StatusTransformer.writePageHeading(writer,args,mode); // Server Row Section args = new Object[8]; args[0] = ServerInfo.getServerInfo(); args[1] = System.getProperty("java.runtime.version"); args[2] = System.getProperty("java.vm.vendor"); args[3] = System.getProperty("os.name"); args[4] = System.getProperty("os.version"); args[5] = System.getProperty("os.arch"); try { InetAddress address = InetAddress.getLocalHost(); args[6] = address.getHostName(); args[7] = address.getHostAddress(); } catch (UnknownHostException e) { args[6] = "-"; args[7] = "-"; } // use StatusTransformer to output status StatusTransformer.writeServerInfo(writer, args, mode); try { // Display operating system statistics using APR if available StatusTransformer.writeOSState(writer,mode); // Display virtual machine statistics StatusTransformer.writeVMState(writer,mode); Enumeration<ObjectName> enumeration = threadPools.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); String name = objectName.getKeyProperty("name"); // use StatusTransformer to output status StatusTransformer.writeConnectorState (writer, objectName, name, mBeanServer, globalRequestProcessors, requestProcessors, mode); } if ((request.getPathInfo() != null) && (request.getPathInfo().equals("/all"))) { // Note: Retrieving the full status is much slower // use StatusTransformer to output status StatusTransformer.writeDetailedState (writer, mBeanServer, mode); } } catch (Exception e) { throw new ServletException(e); } // use StatusTransformer to output status StatusTransformer.writeFooter(writer, mode); }
// in java/org/apache/catalina/manager/ManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null) command = request.getServletPath(); String config = request.getParameter("config"); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } String type = request.getParameter("type"); String war = request.getParameter("war"); String tag = request.getParameter("tag"); boolean update = false; if ((request.getParameter("update") != null) && (request.getParameter("update").equals("true"))) { update = true; } boolean statusLine = false; if ("true".equals(request.getParameter("statusLine"))) { statusLine = true; } // Prepare our output writer to generate the response message response.setContentType("text/plain; charset=" + Constants.CHARSET); PrintWriter writer = response.getWriter(); // Process the requested command (note - "/deploy" is not listed here) if (command == null) { writer.println(smClient.getString("managerServlet.noCommand")); } else if (command.equals("/deploy")) { if (war != null || config != null) { deploy(writer, config, cn, war, update, smClient); } else { deploy(writer, cn, tag, smClient); } } else if (command.equals("/list")) { list(writer, smClient); } else if (command.equals("/reload")) { reload(writer, cn, smClient); } else if (command.equals("/resources")) { resources(writer, type, smClient); } else if (command.equals("/save")) { save(writer, path, smClient); } else if (command.equals("/serverinfo")) { serverinfo(writer, smClient); } else if (command.equals("/sessions")) { expireSessions(writer, cn, request, smClient); } else if (command.equals("/expire")) { expireSessions(writer, cn, request, smClient); } else if (command.equals("/start")) { start(writer, cn, smClient); } else if (command.equals("/stop")) { stop(writer, cn, smClient); } else if (command.equals("/undeploy")) { undeploy(writer, cn, smClient); } else if (command.equals("/findleaks")) { findleaks(statusLine, writer, smClient); } else { writer.println(smClient.getString("managerServlet.unknownCommand", command)); } // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
Override public void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null) command = request.getServletPath(); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } String tag = request.getParameter("tag"); boolean update = false; if ((request.getParameter("update") != null) && (request.getParameter("update").equals("true"))) { update = true; } // Prepare our output writer to generate the response message response.setContentType("text/plain;charset="+Constants.CHARSET); PrintWriter writer = response.getWriter(); // Process the requested command if (command == null) { writer.println(smClient.getString("managerServlet.noCommand")); } else if (command.equals("/deploy")) { deploy(writer, cn, tag, update, request, smClient); } else { writer.println(smClient.getString("managerServlet.unknownCommand", command)); } // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
protected void uploadWar(PrintWriter writer, HttpServletRequest request, File war, StringManager smClient) throws IOException { if (war.exists() && !war.delete()) { String msg = smClient.getString("managerServlet.deleteFail", war); throw new IOException(msg); } ServletInputStream istream = null; BufferedOutputStream ostream = null; try { istream = request.getInputStream(); ostream = new BufferedOutputStream(new FileOutputStream(war), 1024); byte buffer[] = new byte[1024]; while (true) { int n = istream.read(buffer); if (n < 0) { break; } ostream.write(buffer, 0, n); } ostream.flush(); ostream.close(); ostream = null; istream.close(); istream = null; } catch (IOException e) { if (war.exists() && !war.delete()) { writer.println( smClient.getString("managerServlet.deleteFail", war)); } throw e; } finally { if (ostream != null) { try { ostream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } ostream = null; } if (istream != null) { try { istream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } istream = null; } } }
// in java/org/apache/catalina/tribes/group/RpcMessage.java
Override public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException { reply = in.readBoolean(); int length = in.readInt(); uuid = new byte[length]; in.readFully(uuid); length = in.readInt(); rpcId = new byte[length]; in.readFully(rpcId); message = (Serializable)in.readObject(); }
// in java/org/apache/catalina/tribes/group/RpcMessage.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeBoolean(reply); out.writeInt(uuid.length); out.write(uuid, 0, uuid.length); out.writeInt(rpcId.length); out.write(rpcId, 0, rpcId.length); out.writeObject(message); }
// in java/org/apache/catalina/tribes/group/RpcMessage.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { reply = true; int length = in.readInt(); uuid = new byte[length]; in.readFully(uuid); length = in.readInt(); rpcId = new byte[length]; in.readFully(rpcId); }
// in java/org/apache/catalina/tribes/group/RpcMessage.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(uuid.length); out.write(uuid, 0, uuid.length); out.writeInt(rpcId.length); out.write(rpcId, 0, rpcId.length); }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
public static byte[] compress(byte[] data) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); GZIPOutputStream gout = new GZIPOutputStream(bout); gout.write(data); gout.flush(); gout.close(); return bout.toByteArray(); }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
public static byte[] decompress(byte[] data) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE); ByteArrayInputStream bin = new ByteArrayInputStream(data); GZIPInputStream gin = new GZIPInputStream(bin); byte[] tmp = new byte[DEFAULT_BUFFER_SIZE]; int length = gin.read(tmp); while (length > -1) { bout.write(tmp, 0, length); length = gin.read(tmp); } return bout.toByteArray(); }
// in java/org/apache/catalina/tribes/ByteMessage.java
Override public void readExternal(ObjectInput in ) throws IOException { int length = in.readInt(); message = new byte[length]; in.readFully(message); }
// in java/org/apache/catalina/tribes/ByteMessage.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(message!=null?message.length:0); if ( message!=null ) out.write(message,0,message.length); }
// in java/org/apache/catalina/tribes/io/ObjectReader.java
public int append(ByteBuffer data, int len, boolean count) throws java.io.IOException { buffer.append(data,len); int pkgCnt = -1; if ( count ) pkgCnt = buffer.countPackages(); return pkgCnt; }
// in java/org/apache/catalina/tribes/io/ObjectReader.java
public ChannelMessage[] execute() throws java.io.IOException { int pkgCnt = buffer.countPackages(); ChannelMessage[] result = new ChannelMessage[pkgCnt]; for (int i=0; i<pkgCnt; i++) { ChannelMessage data = buffer.extractPackage(true); result[i] = data; } return result; }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data) throws IOException, ClassNotFoundException, ClassCastException { return deserialize(data,0,data.length); }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data, int offset, int length) throws IOException, ClassNotFoundException, ClassCastException { return deserialize(data,offset,length,null); }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data, int offset, int length, ClassLoader[] cls) throws IOException, ClassNotFoundException, ClassCastException { invokecount.addAndGet(1); Object message = null; if ( cls == null ) cls = new ClassLoader[0]; if (data != null && length > 0) { InputStream instream = new ByteArrayInputStream(data,offset,length); ObjectInputStream stream = null; stream = (cls.length>0)? new ReplicationStream(instream,cls):new ObjectInputStream(instream); message = stream.readObject(); instream.close(); stream.close(); } if ( message == null ) { return null; } else if (message instanceof Serializable) return (Serializable) message; else { throw new ClassCastException("Message has the wrong class. It should implement Serializable, instead it is:"+message.getClass().getName()); } }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static byte[] serialize(Serializable msg) throws IOException { ByteArrayOutputStream outs = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(outs); out.writeObject(msg); out.flush(); byte[] data = outs.toByteArray(); return data; }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
Override public Class<?> resolveClass(ObjectStreamClass classDesc) throws ClassNotFoundException, IOException { String name = classDesc.getName(); try { return resolveClass(name); } catch (ClassNotFoundException e) { return super.resolveClass(classDesc); } }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
Override protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { ClassLoader latestLoader = (classLoaders!=null && classLoaders.length==0)?null:classLoaders[0]; ClassLoader nonPublicLoader = null; boolean hasNonPublicInterface = false; // define proxy in class loader of non-public interface(s), if any Class<?>[] classObjs = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { Class<?> cl = this.resolveClass(interfaces[i]); if (latestLoader==null) latestLoader = cl.getClassLoader(); if ((cl.getModifiers() & Modifier.PUBLIC) == 0) { if (hasNonPublicInterface) { if (nonPublicLoader != cl.getClassLoader()) { throw new IllegalAccessError( "conflicting non-public interface class loaders"); } } else { nonPublicLoader = cl.getClassLoader(); hasNonPublicInterface = true; } } classObjs[i] = cl; } try { return Proxy.getProxyClass(hasNonPublicInterface ? nonPublicLoader : latestLoader, classObjs); } catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); } }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
Override public void close() throws IOException { this.classLoaders = null; super.close(); }
// in java/org/apache/catalina/tribes/io/DirectByteArrayOutputStream.java
Override public void write(int b) throws IOException { buffer.append((byte)b); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
Override public void connect() throws IOException { openSocket(); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
public void sendMessage(byte[] data, boolean waitForAck) throws IOException { IOException exception = null; setAttempt(0); try { // first try with existing connection pushMessage(data,false,waitForAck); } catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } } finally { setRequestCount(getRequestCount()+1); keepalive(); if ( exception != null ) throw exception; } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
protected void openSocket() throws IOException { if(isConnected()) return ; try { socket = new Socket(); InetSocketAddress sockaddr = new InetSocketAddress(getAddress(), getPort()); socket.connect(sockaddr,(int)getTimeout()); socket.setSendBufferSize(getTxBufSize()); socket.setReceiveBufferSize(getRxBufSize()); socket.setSoTimeout( (int) getTimeout()); socket.setTcpNoDelay(getTcpNoDelay()); socket.setKeepAlive(getSoKeepAlive()); socket.setReuseAddress(getSoReuseAddress()); socket.setOOBInline(getOoBInline()); socket.setSoLinger(getSoLingerOn(),getSoLingerTime()); socket.setTrafficClass(getSoTrafficClass()); setConnected(true); soOut = socket.getOutputStream(); soIn = socket.getInputStream(); setRequestCount(0); setConnectTime(System.currentTimeMillis()); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket", getAddress().getHostAddress(), new Integer(getPort()), new Long(0))); } catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
protected void pushMessage(byte[] data, boolean reconnect, boolean waitForAck) throws IOException { keepalive(); if ( reconnect ) closeSocket(); if (!isConnected()) openSocket(); soOut.write(data); soOut.flush(); if (waitForAck) waitForAck(); SenderState.getSenderState(getDestination()).setReady(); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
protected void waitForAck() throws java.io.IOException { try { boolean ackReceived = false; boolean failAckReceived = false; ackbuf.clear(); int bytesRead = 0; int i = soIn.read(); while ((i != -1) && (bytesRead < Constants.ACK_COMMAND.length)) { bytesRead++; byte d = (byte)i; ackbuf.append(d); if (ackbuf.doesPackageExist() ) { byte[] ackcmd = ackbuf.extractDataPackage(true).getBytes(); ackReceived = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.ACK_DATA); failAckReceived = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA); ackReceived = ackReceived || failAckReceived; break; } i = soIn.read(); } if (!ackReceived) { if (i == -1) throw new IOException(sm.getString("IDataSender.ack.eof",getAddress(), new Integer(socket.getLocalPort()))); else throw new IOException(sm.getString("IDataSender.ack.wrong",getAddress(), new Integer(socket.getLocalPort()))); } else if ( failAckReceived && getThrowOnFailedAck()) { throw new RemoteProcessException("Received a failed ack:org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA"); } } catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; } finally { ackbuf.clear(); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
Override public void start() throws IOException { super.start(); try { setPool(new RxTaskPool(getMaxThreads(),getMinThreads(),this)); } catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } try { getBind(); bind(); Thread t = new Thread(this, "BioReceiver"); t.setDaemon(true); t.start(); } catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
protected void bind() throws IOException { // allocate an unbound server socket channel serverSocket = new ServerSocket(); // set the port the server channel will listen to //serverSocket.bind(new InetSocketAddress(getBind(), getTcpListenPort())); bind(serverSocket,getPort(),getAutoBind()); }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
Override public void connect() throws IOException { //do nothing, we connect on demand setConnected(true); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
Override public void start() throws IOException { if ( executor == null ) { //executor = new ThreadPoolExecutor(minThreads,maxThreads,60,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>()); TaskThreadFactory tf = new TaskThreadFactory("Tribes-Task-Receiver-"); executor = ExecutorFactory.newThreadPool(minThreads, maxThreads, maxIdleTime, TimeUnit.MILLISECONDS, tf); } }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
protected void bind(ServerSocket socket, int portstart, int retries) throws IOException { synchronized (bindLock) { InetSocketAddress addr = null; int port = portstart; while (retries > 0) { try { addr = new InetSocketAddress(getBind(), port); socket.bind(addr); setPort(port); log.info("Receiver Server Socket bound to:"+addr); retries = 0; } catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind server socket to:" + addr + " throwing error."); throw x; } port++; } } } }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
protected int bindUdp(DatagramSocket socket, int portstart, int retries) throws IOException { InetSocketAddress addr = null; while ( retries > 0 ) { try { addr = new InetSocketAddress(getBind(), portstart); socket.bind(addr); setUdpPort(portstart); log.info("UDP Receiver Server Socket bound to:"+addr); return 0; }catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); } } return retries; }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
public boolean process(SelectionKey key, boolean waitForAck) throws IOException { int ops = key.readyOps(); key.interestOps(key.interestOps() & ~ops); //in case disconnect has been called if ((!isConnected()) && (!connecting)) throw new IOException("Sender has been disconnected, can't selection key."); if ( !key.isValid() ) throw new IOException("Key is not valid, it must have been cancelled."); if ( key.isConnectable() ) { if ( socketChannel.finishConnect() ) { completeConnect(); if ( current != null ) key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); return false; } else { //wait for the connection to finish key.interestOps(key.interestOps() | SelectionKey.OP_CONNECT); return false; }//end if } else if ( key.isWritable() ) { boolean writecomplete = write(); if ( writecomplete ) { //we are completed, should we read an ack? if ( waitForAck ) { //register to read the ack key.interestOps(key.interestOps() | SelectionKey.OP_READ); } else { //if not, we are ready, setMessage will reregister us for another write interest //do a health check, we have no way of verify a disconnected //socket since we don't register for OP_READ on waitForAck=false read();//this causes overhead setRequestCount(getRequestCount()+1); return true; } } else { //we are not complete, lets write some more key.interestOps(key.interestOps()|SelectionKey.OP_WRITE); }//end if } else if ( key.isReadable() ) { boolean readcomplete = read(); if ( readcomplete ) { setRequestCount(getRequestCount()+1); return true; } else { key.interestOps(key.interestOps() | SelectionKey.OP_READ); }//end if } else { //unknown state, should never happen log.warn("Data is in unknown state. readyOps="+ops); throw new IOException("Data is in unknown state. readyOps="+ops); }//end if return false; }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
protected boolean read() throws IOException { //if there is no message here, we are done if ( current == null ) return true; int read = isUdpBased()?dataChannel.read(readbuf) : socketChannel.read(readbuf); //end of stream if ( read == -1 ) throw new IOException("Unable to receive an ack message. EOF on socket channel has been reached."); //no data read else if ( read == 0 ) return false; readbuf.flip(); ackbuf.append(readbuf,read); readbuf.clear(); if (ackbuf.doesPackageExist() ) { byte[] ackcmd = ackbuf.extractDataPackage(true).getBytes(); boolean ack = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.ACK_DATA); boolean fack = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA); if ( fack && getThrowOnFailedAck() ) throw new RemoteProcessException("Received a failed ack:org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA"); return ack || fack; } else { return false; } }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
protected boolean write() throws IOException { if ( (!isConnected()) || (this.socketChannel==null && this.dataChannel==null)) { throw new IOException("NioSender is not connected, this should not occur."); } if ( current != null ) { if ( remaining > 0 ) { //we have written everything, or we are starting a new package //protect against buffer overwrite int byteswritten = isUdpBased()?dataChannel.write(writebuf) : socketChannel.write(writebuf); if (byteswritten == -1 ) throw new EOFException(); remaining -= byteswritten; //if the entire message was written from the buffer //reset the position counter if ( remaining < 0 ) { remaining = 0; } } return (remaining==0); } //no message to send, we can consider that complete return true; }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
Override public synchronized void connect() throws IOException { if ( connecting || isConnected()) return; connecting = true; if ( isConnected() ) throw new IOException("NioSender is already in connected state."); if ( readbuf == null ) { readbuf = getReadBuffer(); } else { readbuf.clear(); } if ( writebuf == null ) { writebuf = getWriteBuffer(); } else { writebuf.clear(); } if (isUdpBased()) { InetSocketAddress daddr = new InetSocketAddress(getAddress(),getUdpPort()); if ( dataChannel != null ) throw new IOException("Datagram channel has already been established. Connection might be in progress."); dataChannel = DatagramChannel.open(); dataChannel.configureBlocking(false); dataChannel.connect(daddr); completeConnect(); dataChannel.register(getSelector(),SelectionKey.OP_WRITE, this); } else { InetSocketAddress addr = new InetSocketAddress(getAddress(),getPort()); if ( socketChannel != null ) throw new IOException("Socket channel has already been established. Connection might be in progress."); socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); if ( socketChannel.connect(addr) ) { completeConnect(); socketChannel.register(getSelector(), SelectionKey.OP_WRITE, this); } else { socketChannel.register(getSelector(), SelectionKey.OP_CONNECT, this); } } }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
public synchronized void setMessage(byte[] data) throws IOException { setMessage(data,0,data.length); }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
public synchronized void setMessage(byte[] data,int offset, int length) throws IOException { if ( data != null ) { current = data; remaining = length; ackbuf.clear(); if ( writebuf != null ) writebuf.clear(); else writebuf = getBuffer(length); if ( writebuf.capacity() < length ) writebuf = getBuffer(length); //TODO use ByteBuffer.wrap to avoid copying the data. writebuf.put(data,offset,length); //writebuf.rewind(); //set the limit so that we don't write non wanted data //writebuf.limit(length); writebuf.flip(); if (isConnected()) { if (isUdpBased()) dataChannel.register(getSelector(), SelectionKey.OP_WRITE, this); else socketChannel.register(getSelector(), SelectionKey.OP_WRITE, this); } } }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
Override public synchronized void connect() throws IOException { this.connected = true; super.connect(); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
private int doLoop(long selectTimeOut, int maxAttempts, boolean waitForAck, ChannelMessage msg) throws IOException, ChannelException { int completed = 0; int selectedKeys = selector.select(selectTimeOut); if (selectedKeys == 0) { return 0; } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey sk = it.next(); it.remove(); int readyOps = sk.readyOps(); sk.interestOps(sk.interestOps() & ~readyOps); NioSender sender = (NioSender) sk.attachment(); try { if (sender.process(sk,waitForAck)) { completed++; sender.setComplete(true); if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("ParallelNioSender - Sent msg:" + new UniqueId(msg.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " to "+sender.getDestination().getName()); } SenderState.getSenderState(sender.getDestination()).setReady(); }//end if } catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if } } return completed; }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
Override public void start() throws IOException { super.start(); try { setPool(new RxTaskPool(getMaxThreads(),getMinThreads(),this)); } catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } try { getBind(); bind(); Thread t = new Thread(this, "NioReceiver"); t.setDaemon(true); t.start(); } catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
protected void bind() throws IOException { // allocate an unbound server socket channel serverChannel = ServerSocketChannel.open(); // Get the associated ServerSocket to bind it with ServerSocket serverSocket = serverChannel.socket(); // create a new Selector for use below synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 selector = Selector.open(); } // set the port the server channel will listen to //serverSocket.bind(new InetSocketAddress(getBind(), getTcpListenPort())); bind(serverSocket,getPort(),getAutoBind()); // set non-blocking mode for the listening socket serverChannel.configureBlocking(false); // register the ServerSocketChannel with the Selector serverChannel.register(selector, SelectionKey.OP_ACCEPT); //set up the datagram channel if (this.getUdpPort()>0) { datagramChannel = DatagramChannel.open(); datagramChannel.configureBlocking(false); //bind to the address to avoid security checks bindUdp(datagramChannel.socket(),getUdpPort(),getAutoBind()); } }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
private void closeSelector() throws IOException { Selector selector = this.selector; this.selector = null; if (selector==null) return; try { Iterator<SelectionKey> it = selector.keys().iterator(); // look at each key in the selected set while (it.hasNext()) { SelectionKey key = it.next(); key.channel().close(); key.attach(null); key.cancel(); } }catch ( IOException ignore ){ if (log.isWarnEnabled()) { log.warn("Unable to cleanup on selector close.",ignore); } }catch ( ClosedSelectorException ignore){} selector.close(); }
// in java/org/apache/catalina/tribes/transport/PooledSender.java
Override public synchronized void connect() throws IOException { //do nothing, happens in the socket sender itself queue.open(); setConnected(true); }
// in java/org/apache/catalina/tribes/transport/ReplicationTransmitter.java
Override public void start() throws java.io.IOException { getTransport().connect(); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public void deserialize(ClassLoader[] cls) throws IOException, ClassNotFoundException { key(cls); value(cls); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public Serializable key(ClassLoader[] cls) throws IOException, ClassNotFoundException { if ( key!=null ) return key; if ( keydata == null || keydata.length == 0 ) return null; key = XByteBuffer.deserialize(keydata,0,keydata.length,cls); keydata = null; return key; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public Serializable value(ClassLoader[] cls) throws IOException, ClassNotFoundException { if ( value!=null ) return value; if ( valuedata == null || valuedata.length == 0 ) return null; value = XByteBuffer.deserialize(valuedata,0,valuedata.length,cls); valuedata = null; return value; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
protected Member[] readMembers(ObjectInput in) throws IOException { int nodecount = in.readInt(); Member[] members = new Member[nodecount]; for ( int i=0; i<members.length; i++ ) { byte[] d = new byte[in.readInt()]; in.readFully(d); if (d.length > 0) members[i] = MemberImpl.getMember(d); } return members; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
protected void writeMembers(ObjectOutput out,Member[] members) throws IOException { if ( members == null ) members = new Member[0]; out.writeInt(members.length); for (int i=0; i<members.length; i++ ) { if ( members[i] != null ) { byte[] d = members[i] != null ? ( (MemberImpl)members[i]).getData(false) : new byte[0]; out.writeInt(d.length); out.write(d); } } }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
public void setHostname(String host) throws IOException { hostname = host; this.host = java.net.InetAddress.getByName(host).getAddress(); }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { int length = in.readInt(); byte[] message = new byte[length]; in.readFully(message); getMember(message,this); }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
Override public void writeExternal(ObjectOutput out) throws IOException { byte[] data = this.getData(); out.writeInt(data.length); out.write(data); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public void init() throws IOException { setupSocket(); sendPacket = new DatagramPacket(new byte[MAX_PACKET_SIZE],MAX_PACKET_SIZE); sendPacket.setAddress(address); sendPacket.setPort(port); receivePacket = new DatagramPacket(new byte[MAX_PACKET_SIZE],MAX_PACKET_SIZE); receivePacket.setAddress(address); receivePacket.setPort(port); member.setCommand(new byte[0]); member.getData(true, true); if ( membership == null ) membership = new Membership(member); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
protected void setupSocket() throws IOException { if (mcastBindAddress != null) { try { log.info("Attempting to bind the multicast socket to "+address+":"+port); socket = new MulticastSocket(new InetSocketAddress(address,port)); } catch (BindException e) { /* * On some platforms (e.g. Linux) it is not possible to bind * to the multicast address. In this case only bind to the * port. */ log.info("Binding to multicast address, failed. Binding to port only."); socket = new MulticastSocket(port); } } else { socket = new MulticastSocket(port); } socket.setLoopbackMode(localLoopbackDisabled); //hint if we want disable loop back(local machine) messages if (mcastBindAddress != null) { if(log.isInfoEnabled()) log.info("Setting multihome multicast interface to:" +mcastBindAddress); socket.setInterface(mcastBindAddress); } //end if //force a so timeout so that we don't block forever if ( mcastSoTimeout <= 0 ) mcastSoTimeout = (int)sendFrequency; if(log.isInfoEnabled()) log.info("Setting cluster mcast soTimeout to "+mcastSoTimeout); socket.setSoTimeout(mcastSoTimeout); if ( mcastTTL >= 0 ) { if(log.isInfoEnabled()) log.info("Setting cluster mcast TTL to " + mcastTTL); socket.setTimeToLive(mcastTTL); } }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public synchronized void start(int level) throws IOException { boolean valid = false; if ( (level & Channel.MBR_RX_SEQ)==Channel.MBR_RX_SEQ ) { if ( receiver != null ) throw new IllegalStateException("McastService.receive already running."); try { if ( sender == null ) socket.joinGroup(address); }catch (IOException iox) { log.error("Unable to join multicast group, make sure your system has multicasting enabled."); throw iox; } doRunReceiver = true; receiver = new ReceiverThread(); receiver.setDaemon(true); receiver.start(); valid = true; } if ( (level & Channel.MBR_TX_SEQ)==Channel.MBR_TX_SEQ ) { if ( sender != null ) throw new IllegalStateException("McastService.send already running."); if ( receiver == null ) socket.joinGroup(address); //make sure at least one packet gets out there send(false); doRunSender = true; sender = new SenderThread(sendFrequency); sender.setDaemon(true); sender.start(); //we have started the receiver, but not yet waited for membership to establish valid = true; } if (!valid) { throw new IllegalArgumentException("Invalid start level. Only acceptable levels are Channel.MBR_RX_SEQ and Channel.MBR_TX_SEQ"); } //pause, once or twice waitForMembers(level); startLevel = (startLevel | level); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public synchronized boolean stop(int level) throws IOException { boolean valid = false; if ( (level & Channel.MBR_RX_SEQ)==Channel.MBR_RX_SEQ ) { valid = true; doRunReceiver = false; if ( receiver !=null ) receiver.interrupt(); receiver = null; } if ( (level & Channel.MBR_TX_SEQ)==Channel.MBR_TX_SEQ ) { valid = true; doRunSender = false; if ( sender != null )sender.interrupt(); sender = null; } if (!valid) { throw new IllegalArgumentException("Invalid stop level. Only acceptable levels are Channel.MBR_RX_SEQ and Channel.MBR_TX_SEQ"); } startLevel = (startLevel & (~level)); //we're shutting down, send a shutdown message and close the socket if ( startLevel == 0 ) { //send a stop message member.setCommand(Member.SHUTDOWN_PAYLOAD); member.getData(true, true); send(false); //leave mcast group try {socket.leaveGroup(address);}catch ( Exception ignore){} try {socket.close();}catch ( Exception ignore){} member.setServiceStartTime(-1); } return (startLevel == 0); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public void receive() throws IOException { boolean checkexpired = true; try { socket.receive(receivePacket); if(receivePacket.getLength() > MAX_PACKET_SIZE) { log.error("Multicast packet received was too long, dropping package:"+receivePacket.getLength()); } else { byte[] data = new byte[receivePacket.getLength()]; System.arraycopy(receivePacket.getData(), receivePacket.getOffset(), data, 0, data.length); if (XByteBuffer.firstIndexOf(data,0,MemberImpl.TRIBES_MBR_BEGIN)==0) { memberDataReceived(data); } else { memberBroadcastsReceived(data); } } } catch (SocketTimeoutException x ) { //do nothing, this is normal, we don't want to block forever //since the receive thread is the same thread //that does membership expiration } if (checkexpired) checkExpired(); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public void send(boolean checkexpired) throws IOException{ send(checkexpired,null); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public void send(boolean checkexpired, DatagramPacket packet) throws IOException{ checkexpired = (checkexpired && (packet==null)); //ignore if we haven't started the sender //if ( (startLevel&Channel.MBR_TX_SEQ) != Channel.MBR_TX_SEQ ) return; if (packet==null) { member.inc(); if(log.isTraceEnabled()) { log.trace("Mcast send ping from member " + member); } byte[] data = member.getData(); packet = new DatagramPacket(data,data.length); } else if (log.isTraceEnabled()) { log.trace("Sending message broadcast "+packet.getLength()+ " bytes from "+ member); } packet.setAddress(address); packet.setPort(port); //TODO this operation is not thread safe synchronized (sendLock) { socket.send(packet); } if ( checkexpired ) checkExpired(); }
// in java/org/apache/catalina/session/StandardManager.java
Override public void load() throws ClassNotFoundException, IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ AccessController.doPrivileged( new PrivilegedDoLoad() ); } catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof ClassNotFoundException){ throw (ClassNotFoundException)exception; } else if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in load() " + exception); } } else { doLoad(); } }
// in java/org/apache/catalina/session/StandardManager.java
protected void doLoad() throws ClassNotFoundException, IOException { if (log.isDebugEnabled()) log.debug("Start: Loading persisted sessions"); // Initialize our internal data structures sessions.clear(); // Open an input stream to the specified pathname, if any File file = file(); if (file == null) return; if (log.isDebugEnabled()) log.debug(sm.getString("standardManager.loading", pathname)); FileInputStream fis = null; BufferedInputStream bis = null; ObjectInputStream ois = null; Loader loader = null; ClassLoader classLoader = null; try { fis = new FileInputStream(file.getAbsolutePath()); bis = new BufferedInputStream(fis); if (container != null) loader = container.getLoader(); if (loader != null) classLoader = loader.getClassLoader(); if (classLoader != null) { if (log.isDebugEnabled()) log.debug("Creating custom object input stream for class loader "); ois = new CustomObjectInputStream(bis, classLoader); } else { if (log.isDebugEnabled()) log.debug("Creating standard object input stream"); ois = new ObjectInputStream(bis); } } catch (FileNotFoundException e) { if (log.isDebugEnabled()) log.debug("No persisted data file found"); return; } catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } throw e; } // Load the previously unloaded active sessions synchronized (sessions) { try { Integer count = (Integer) ois.readObject(); int n = count.intValue(); if (log.isDebugEnabled()) log.debug("Loading " + n + " persisted sessions"); for (int i = 0; i < n; i++) { StandardSession session = getNewSession(); session.readObjectData(ois); session.setManager(this); sessions.put(session.getIdInternal(), session); session.activate(); if (!session.isValidInternal()) { // If session is already invalid, // expire session to prevent memory leak. session.setValid(true); session.expire(); } sessionCounter++; } } catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; } catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; } finally { // Close the input stream try { ois.close(); } catch (IOException f) { // ignored } // Delete the persistent storage file if (file.exists() ) file.delete(); } } if (log.isDebugEnabled()) log.debug("Finish: Loading persisted sessions"); }
// in java/org/apache/catalina/session/StandardManager.java
Override public void unload() throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ AccessController.doPrivileged( new PrivilegedDoUnload() ); } catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in unLoad() " + exception); } } else { doUnload(); } }
// in java/org/apache/catalina/session/StandardManager.java
protected void doUnload() throws IOException { if (log.isDebugEnabled()) log.debug(sm.getString("standardManager.unloading.debug")); if (sessions.isEmpty()) { log.debug(sm.getString("standardManager.unloading.nosessions")); return; // nothing to do } // Open an output stream to the specified pathname, if any File file = file(); if (file == null) return; if (log.isDebugEnabled()) log.debug(sm.getString("standardManager.unloading", pathname)); FileOutputStream fos = null; BufferedOutputStream bos = null; ObjectOutputStream oos = null; boolean error = false; try { fos = new FileOutputStream(file.getAbsolutePath()); bos = new BufferedOutputStream(fos); oos = new ObjectOutputStream(bos); } catch (IOException e) { error = true; log.error(sm.getString("standardManager.unloading.ioe", e), e); throw e; } finally { if (error) { if (oos != null) { try { oos.close(); } catch (IOException ioe) { // Ignore } } if (bos != null) { try { bos.close(); } catch (IOException ioe) { // Ignore } } if (fos != null) { try { fos.close(); } catch (IOException ioe) { // Ignore } } } } // Write the number of active sessions, followed by the details ArrayList<StandardSession> list = new ArrayList<StandardSession>(); synchronized (sessions) { if (log.isDebugEnabled()) log.debug("Unloading " + sessions.size() + " sessions"); try { oos.writeObject(new Integer(sessions.size())); Iterator<Session> elements = sessions.values().iterator(); while (elements.hasNext()) { StandardSession session = (StandardSession) elements.next(); list.add(session); session.passivate(); session.writeObjectData(oos); } } catch (IOException e) { log.error(sm.getString("standardManager.unloading.ioe", e), e); try { oos.close(); } catch (IOException f) { // Ignore } throw e; } } // Flush and close the output stream try { oos.flush(); } finally { try { oos.close(); } catch (IOException f) { // Ignore } } // Expire all the sessions we just wrote if (log.isDebugEnabled()) log.debug("Expiring " + list.size() + " persisted sessions"); Iterator<StandardSession> expires = list.iterator(); while (expires.hasNext()) { StandardSession session = expires.next(); try { session.expire(false); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } finally { session.recycle(); } } if (log.isDebugEnabled()) log.debug("Unloading complete"); }
// in java/org/apache/catalina/session/ManagerBase.java
Override public Session findSession(String id) throws IOException { if (id == null) return (null); return sessions.get(id); }
// in java/org/apache/catalina/session/JDBCStore.java
Override public String[] keys() throws IOException { ResultSet rst = null; String keys[] = null; synchronized (this) { int numberOfTries = 2; while (numberOfTries > 0) { Connection _conn = getConnection(); if (_conn == null) { return (new String[0]); } try { if (preparedKeysSql == null) { String keysSql = "SELECT " + sessionIdCol + " FROM " + sessionTable + " WHERE " + sessionAppCol + " = ?"; preparedKeysSql = _conn.prepareStatement(keysSql); } preparedKeysSql.setString(1, getName()); rst = preparedKeysSql.executeQuery(); ArrayList<String> tmpkeys = new ArrayList<String>(); if (rst != null) { while (rst.next()) { tmpkeys.add(rst.getString(1)); } } keys = tmpkeys.toArray(new String[tmpkeys.size()]); // Break out after the finally block numberOfTries = 0; } catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); keys = new String[0]; // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); } finally { try { if (rst != null) { rst.close(); } } catch (SQLException e) { // Ignore } release(_conn); } numberOfTries--; } } return (keys); }
// in java/org/apache/catalina/session/JDBCStore.java
Override public int getSize() throws IOException { int size = 0; ResultSet rst = null; synchronized (this) { int numberOfTries = 2; while (numberOfTries > 0) { Connection _conn = getConnection(); if (_conn == null) { return (size); } try { if (preparedSizeSql == null) { String sizeSql = "SELECT COUNT(" + sessionIdCol + ") FROM " + sessionTable + " WHERE " + sessionAppCol + " = ?"; preparedSizeSql = _conn.prepareStatement(sizeSql); } preparedSizeSql.setString(1, getName()); rst = preparedSizeSql.executeQuery(); if (rst.next()) { size = rst.getInt(1); } // Break out after the finally block numberOfTries = 0; } catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); } finally { try { if (rst != null) rst.close(); } catch (SQLException e) { // Ignore } release(_conn); } numberOfTries--; } } return (size); }
// in java/org/apache/catalina/session/JDBCStore.java
Override public Session load(String id) throws ClassNotFoundException, IOException { ResultSet rst = null; StandardSession _session = null; Loader loader = null; ClassLoader classLoader = null; ObjectInputStream ois = null; BufferedInputStream bis = null; Container container = manager.getContainer(); synchronized (this) { int numberOfTries = 2; while (numberOfTries > 0) { Connection _conn = getConnection(); if (_conn == null) { return (null); } try { if (preparedLoadSql == null) { String loadSql = "SELECT " + sessionIdCol + ", " + sessionDataCol + " FROM " + sessionTable + " WHERE " + sessionIdCol + " = ? AND " + sessionAppCol + " = ?"; preparedLoadSql = _conn.prepareStatement(loadSql); } preparedLoadSql.setString(1, id); preparedLoadSql.setString(2, getName()); rst = preparedLoadSql.executeQuery(); if (rst.next()) { bis = new BufferedInputStream(rst.getBinaryStream(2)); if (container != null) { loader = container.getLoader(); } if (loader != null) { classLoader = loader.getClassLoader(); } if (classLoader != null) { ois = new CustomObjectInputStream(bis, classLoader); } else { ois = new ObjectInputStream(bis); } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName() + ".loading", id, sessionTable)); } _session = (StandardSession) manager.createEmptySession(); _session.readObjectData(ois); _session.setManager(manager); } else if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(getStoreName() + ": No persisted data object found"); } // Break out after the finally block numberOfTries = 0; } catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); } finally { try { if (rst != null) { rst.close(); } } catch (SQLException e) { // Ignore } if (ois != null) { try { ois.close(); } catch (IOException e) { // Ignore } } release(_conn); } numberOfTries--; } } return (_session); }
// in java/org/apache/catalina/session/JDBCStore.java
Override public void remove(String id) throws IOException { synchronized (this) { int numberOfTries = 2; while (numberOfTries > 0) { Connection _conn = getConnection(); if (_conn == null) { return; } try { remove(id, _conn); // Break out after the finally block numberOfTries = 0; } catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); } finally { release(_conn); } numberOfTries--; } } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName() + ".removing", id, sessionTable)); } }
// in java/org/apache/catalina/session/JDBCStore.java
Override public void clear() throws IOException { synchronized (this) { int numberOfTries = 2; while (numberOfTries > 0) { Connection _conn = getConnection(); if (_conn == null) { return; } try { if (preparedClearSql == null) { String clearSql = "DELETE FROM " + sessionTable + " WHERE " + sessionAppCol + " = ?"; preparedClearSql = _conn.prepareStatement(clearSql); } preparedClearSql.setString(1, getName()); preparedClearSql.execute(); // Break out after the finally block numberOfTries = 0; } catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); } finally { release(_conn); } numberOfTries--; } } }
// in java/org/apache/catalina/session/JDBCStore.java
Override public void save(Session session) throws IOException { ObjectOutputStream oos = null; ByteArrayOutputStream bos = null; ByteArrayInputStream bis = null; InputStream in = null; synchronized (this) { int numberOfTries = 2; while (numberOfTries > 0) { Connection _conn = getConnection(); if (_conn == null) { return; } try { // If sessions already exist in DB, remove and insert again. // TODO: // * Check if ID exists in database and if so use UPDATE. remove(session.getIdInternal(), _conn); bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(new BufferedOutputStream(bos)); ((StandardSession) session).writeObjectData(oos); oos.close(); oos = null; byte[] obs = bos.toByteArray(); int size = obs.length; bis = new ByteArrayInputStream(obs, 0, size); in = new BufferedInputStream(bis, size); if (preparedSaveSql == null) { String saveSql = "INSERT INTO " + sessionTable + " (" + sessionIdCol + ", " + sessionAppCol + ", " + sessionDataCol + ", " + sessionValidCol + ", " + sessionMaxInactiveCol + ", " + sessionLastAccessedCol + ") VALUES (?, ?, ?, ?, ?, ?)"; preparedSaveSql = _conn.prepareStatement(saveSql); } preparedSaveSql.setString(1, session.getIdInternal()); preparedSaveSql.setString(2, getName()); preparedSaveSql.setBinaryStream(3, in, size); preparedSaveSql.setString(4, session.isValid() ? "1" : "0"); preparedSaveSql.setInt(5, session.getMaxInactiveInterval()); preparedSaveSql.setLong(6, session.getLastAccessedTime()); preparedSaveSql.execute(); // Break out after the finally block numberOfTries = 0; } catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); } catch (IOException e) { // Ignore } finally { if (oos != null) { oos.close(); } if (bis != null) { bis.close(); } if (in != null) { in.close(); } release(_conn); } numberOfTries--; } } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName() + ".saving", session.getIdInternal(), sessionTable)); } }
// in java/org/apache/catalina/session/FileStore.java
Override public int getSize() throws IOException { // Acquire the list of files in our storage directory File file = directory(); if (file == null) { return (0); } String files[] = file.list(); // Figure out which files are sessions int keycount = 0; for (int i = 0; i < files.length; i++) { if (files[i].endsWith(FILE_EXT)) { keycount++; } } return (keycount); }
// in java/org/apache/catalina/session/FileStore.java
Override public void clear() throws IOException { String[] keys = keys(); for (int i = 0; i < keys.length; i++) { remove(keys[i]); } }
// in java/org/apache/catalina/session/FileStore.java
Override public String[] keys() throws IOException { // Acquire the list of files in our storage directory File file = directory(); if (file == null) { return (new String[0]); } String files[] = file.list(); // Bugzilla 32130 if((files == null) || (files.length < 1)) { return (new String[0]); } // Build and return the list of session identifiers ArrayList<String> list = new ArrayList<String>(); int n = FILE_EXT.length(); for (int i = 0; i < files.length; i++) { if (files[i].endsWith(FILE_EXT)) { list.add(files[i].substring(0, files[i].length() - n)); } } return list.toArray(new String[list.size()]); }
// in java/org/apache/catalina/session/FileStore.java
Override public Session load(String id) throws ClassNotFoundException, IOException { // Open an input stream to the specified pathname, if any File file = file(id); if (file == null) { return (null); } if (! file.exists()) { return (null); } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName()+".loading", id, file.getAbsolutePath())); } FileInputStream fis = null; BufferedInputStream bis = null; ObjectInputStream ois = null; Loader loader = null; ClassLoader classLoader = null; try { fis = new FileInputStream(file.getAbsolutePath()); bis = new BufferedInputStream(fis); Container container = manager.getContainer(); if (container != null) loader = container.getLoader(); if (loader != null) classLoader = loader.getClassLoader(); if (classLoader != null) ois = new CustomObjectInputStream(bis, classLoader); else ois = new ObjectInputStream(bis); } catch (FileNotFoundException e) { if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug("No persisted data file found"); return (null); } catch (IOException e) { if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } throw e; } try { StandardSession session = (StandardSession) manager.createEmptySession(); session.readObjectData(ois); session.setManager(manager); return (session); } finally { // Close the input stream try { ois.close(); } catch (IOException f) { // Ignore } } }
// in java/org/apache/catalina/session/FileStore.java
Override public void remove(String id) throws IOException { File file = file(id); if (file == null) { return; } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName()+".removing", id, file.getAbsolutePath())); } file.delete(); }
// in java/org/apache/catalina/session/FileStore.java
Override public void save(Session session) throws IOException { // Open an output stream to the specified pathname, if any File file = file(session.getIdInternal()); if (file == null) { return; } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName()+".saving", session.getIdInternal(), file.getAbsolutePath())); } FileOutputStream fos = null; ObjectOutputStream oos = null; try { fos = new FileOutputStream(file.getAbsolutePath()); oos = new ObjectOutputStream(new BufferedOutputStream(fos)); } catch (IOException e) { if (fos != null) { try { fos.close(); } catch (IOException f) { // Ignore } } throw e; } try { ((StandardSession)session).writeObjectData(oos); } finally { oos.close(); } }
// in java/org/apache/catalina/session/FileStore.java
private File directory() throws IOException { if (this.directory == null) { return (null); } if (this.directoryFile != null) { // NOTE: Race condition is harmless, so do not synchronize return (this.directoryFile); } File file = new File(this.directory); if (!file.isAbsolute()) { Container container = manager.getContainer(); if (container instanceof Context) { ServletContext servletContext = ((Context) container).getServletContext(); File work = (File) servletContext.getAttribute(ServletContext.TEMPDIR); file = new File(work, this.directory); } else { throw new IllegalArgumentException ("Parent Container is not a Context"); } } if (!file.exists() || !file.isDirectory()) { if (!file.delete() && file.exists()) { throw new IOException( sm.getString("fileStore.deleteFailed", file)); } if (!file.mkdirs() && !file.isDirectory()) { throw new IOException( sm.getString("fileStore.createFailed", file)); } } this.directoryFile = file; return (file); }
// in java/org/apache/catalina/session/FileStore.java
private File file(String id) throws IOException { if (this.directory == null) { return (null); } String filename = id + FILE_EXT; File file = new File(directory(), filename); return (file); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override public Session findSession(String id) throws IOException { Session session = super.findSession(id); // OK, at this point, we're not sure if another thread is trying to // remove the session or not so the only way around this is to lock it // (or attempt to) and then try to get it by this session id again. If // the other code ran swapOut, then we should get a null back during // this run, and if not, we lock it out so we can access the session // safely. if(session != null) { synchronized(session){ session = super.findSession(session.getIdInternal()); if(session != null){ // To keep any external calling code from messing up the // concurrency. session.access(); session.endAccess(); } } } if (session != null) return (session); // See if the Session is in the Store session = swapIn(id); return (session); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
protected Session swapIn(String id) throws IOException { if (store == null) return null; Object swapInLock = null; /* * The purpose of this sync and these locks is to make sure that a * session is only loaded once. It doesn't matter if the lock is removed * and then another thread enters this method and tries to load the same * session. That thread will re-create a swapIn lock for that session, * quickly find that the session is already in sessions, use it and * carry on. */ synchronized (this) { swapInLock = sessionSwapInLocks.get(id); if (swapInLock == null) { swapInLock = new Object(); sessionSwapInLocks.put(id, swapInLock); } } Session session = null; synchronized (swapInLock) { // First check to see if another thread has loaded the session into // the manager session = sessions.get(id); if (session == null) { try { if (SecurityUtil.isPackageProtectionEnabled()){ try { session = AccessController.doPrivileged( new PrivilegedStoreLoad(id)); } catch (PrivilegedActionException ex) { Exception e = ex.getException(); log.error(sm.getString( "persistentManager.swapInException", id), e); if (e instanceof IOException){ throw (IOException)e; } else if (e instanceof ClassNotFoundException) { throw (ClassNotFoundException)e; } } } else { session = store.load(id); } } catch (ClassNotFoundException e) { String msg = sm.getString( "persistentManager.deserializeError", id); log.error(msg, e); throw new IllegalStateException(msg, e); } if (session != null && !session.isValid()) { log.error(sm.getString( "persistentManager.swapInInvalid", id)); session.expire(); removeSession(id); session = null; } if (session != null) { if(log.isDebugEnabled()) log.debug(sm.getString("persistentManager.swapIn", id)); session.setManager(this); // make sure the listeners know about it. ((StandardSession)session).tellNew(); add(session); ((StandardSession)session).activate(); // endAccess() to ensure timeouts happen correctly. // access() to keep access count correct or it will end up // negative session.access(); session.endAccess(); } } } // Make sure the lock is removed synchronized (this) { sessionSwapInLocks.remove(id); } return (session); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
protected void swapOut(Session session) throws IOException { if (store == null || !session.isValid()) { return; } ((StandardSession)session).passivate(); writeSession(session); super.remove(session, true); session.recycle(); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
protected void writeSession(Session session) throws IOException { if (store == null || !session.isValid()) { return; } try { if (SecurityUtil.isPackageProtectionEnabled()){ try{ AccessController.doPrivileged(new PrivilegedStoreSave(session)); }catch(PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException) { throw (IOException) exception; } log.error("Exception in the Store during writeSession: " + exception, exception); } } else { store.save(session); } } catch (IOException e) { log.error(sm.getString ("persistentManager.serializeError", session.getIdInternal(), e)); throw e; } }
// in java/org/apache/catalina/session/StandardSession.java
public void readObjectData(ObjectInputStream stream) throws ClassNotFoundException, IOException { readObject(stream); }
// in java/org/apache/catalina/session/StandardSession.java
public void writeObjectData(ObjectOutputStream stream) throws IOException { writeObject(stream); }
// in java/org/apache/catalina/session/StandardSession.java
protected void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException { // Deserialize the scalar instance variables (except Manager) authType = null; // Transient only creationTime = ((Long) stream.readObject()).longValue(); lastAccessedTime = ((Long) stream.readObject()).longValue(); maxInactiveInterval = ((Integer) stream.readObject()).intValue(); isNew = ((Boolean) stream.readObject()).booleanValue(); isValid = ((Boolean) stream.readObject()).booleanValue(); thisAccessedTime = ((Long) stream.readObject()).longValue(); principal = null; // Transient only // setId((String) stream.readObject()); id = (String) stream.readObject(); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug ("readObject() loading session " + id); // Deserialize the attribute count and attribute values if (attributes == null) attributes = new ConcurrentHashMap<String, Object>(); int n = ((Integer) stream.readObject()).intValue(); boolean isValidSave = isValid; isValid = true; for (int i = 0; i < n; i++) { String name = (String) stream.readObject(); Object value = stream.readObject(); if ((value instanceof String) && (value.equals(NOT_SERIALIZED))) continue; if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug(" loading attribute '" + name + "' with value '" + value + "'"); attributes.put(name, value); } isValid = isValidSave; if (listeners == null) { listeners = new ArrayList<SessionListener>(); } if (notes == null) { notes = new Hashtable<String, Object>(); } }
// in java/org/apache/catalina/session/StandardSession.java
protected void writeObject(ObjectOutputStream stream) throws IOException { // Write the scalar instance variables (except Manager) stream.writeObject(Long.valueOf(creationTime)); stream.writeObject(Long.valueOf(lastAccessedTime)); stream.writeObject(Integer.valueOf(maxInactiveInterval)); stream.writeObject(Boolean.valueOf(isNew)); stream.writeObject(Boolean.valueOf(isValid)); stream.writeObject(Long.valueOf(thisAccessedTime)); stream.writeObject(id); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug ("writeObject() storing session " + id); // Accumulate the names of serializable and non-serializable attributes String keys[] = keys(); ArrayList<String> saveNames = new ArrayList<String>(); ArrayList<Object> saveValues = new ArrayList<Object>(); for (int i = 0; i < keys.length; i++) { Object value = attributes.get(keys[i]); if (value == null) continue; else if ( (value instanceof Serializable) && (!exclude(keys[i]) )) { saveNames.add(keys[i]); saveValues.add(value); } else { removeAttributeInternal(keys[i], true); } } // Serialize the attribute count and the Serializable attributes int n = saveNames.size(); stream.writeObject(Integer.valueOf(n)); for (int i = 0; i < n; i++) { stream.writeObject(saveNames.get(i)); try { stream.writeObject(saveValues.get(i)); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug (" storing attribute '" + saveNames.get(i) + "' with value '" + saveValues.get(i) + "'"); } catch (NotSerializableException e) { manager.getContainer().getLogger().warn (sm.getString("standardSession.notSerializable", saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug (" storing attribute '" + saveNames.get(i) + "' with value NOT_SERIALIZED"); } } }
// in java/org/apache/catalina/valves/RequestFilterValve.java
protected void process(String property, Request request, Response response) throws IOException, ServletException { if (isAllowed(property)) { getNext().invoke(request, response); return; } // Deny this request denyRequest(request, response); }
// in java/org/apache/catalina/valves/RequestFilterValve.java
protected void denyRequest(Request request, Response response) throws IOException, ServletException { response.sendError(denyStatus); }
// in java/org/apache/catalina/valves/RemoteHostValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { process(request.getRequest().getRemoteHost(), request, response); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { // Perform the request getNext().invoke(request, response); if (request.isComet() && !response.isClosed()) { // Start tracking this connection, since this is a // begin event, and Comet mode is on HttpSession session = request.getSession(true); // Track the connection for webapp reload cometRequests.add(request); // Track the connection for session expiration synchronized (session) { Request[] requests = (Request[]) session.getAttribute(cometRequestsAttribute); if (requests == null) { requests = new Request[1]; requests[0] = request; session.setAttribute(cometRequestsAttribute, requests); } else { Request[] newRequests = new Request[requests.length + 1]; for (int i = 0; i < requests.length; i++) { newRequests[i] = requests[i]; } newRequests[requests.length] = request; session.setAttribute(cometRequestsAttribute, newRequests); } } } }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
Override public void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Perform the request boolean ok = false; try { getNext().event(request, response, event); ok = true; } finally { if (!ok || response.isClosed() || (event.getEventType() == CometEvent.EventType.END) || (event.getEventType() == CometEvent.EventType.ERROR && !(event.getEventSubType() == CometEvent.EventSubType.TIMEOUT))) { // Remove the connection from webapp reload tracking cometRequests.remove(request); // Remove connection from session expiration tracking // Note: can't get the session if it has been invalidated but // OK since session listener will have done clean-up HttpSession session = request.getSession(false); if (session != null) { synchronized (session) { Request[] reqs = null; try { reqs = (Request[]) session.getAttribute(cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } if (reqs != null) { boolean found = false; for (int i = 0; !found && (i < reqs.length); i++) { found = (reqs[i] == request); } if (found) { if (reqs.length > 1) { Request[] newConnectionInfos = new Request[reqs.length - 1]; int pos = 0; for (int i = 0; i < reqs.length; i++) { if (reqs[i] != request) { newConnectionInfos[pos++] = reqs[i]; } } try { session.setAttribute( cometRequestsAttribute, newConnectionInfos); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } else { try { session.removeAttribute( cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } } } } } } } }
// in java/org/apache/catalina/valves/CrawlerSessionManagerValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { boolean isBot = false; String sessionId = null; String clientIp = null; if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": ClientIp=" + request.getRemoteAddr() + ", RequestedSessionId=" + request.getRequestedSessionId()); } // If the incoming request has a valid session ID, no action is required if (request.getSession(false) == null) { // Is this a crawler - check the UA headers Enumeration<String> uaHeaders = request.getHeaders("user-agent"); String uaHeader = null; if (uaHeaders.hasMoreElements()) { uaHeader = uaHeaders.nextElement(); } // If more than one UA header - assume not a bot if (uaHeader != null && !uaHeaders.hasMoreElements()) { if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": UserAgent=" + uaHeader); } if (uaPattern.matcher(uaHeader).matches()) { isBot = true; if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": Bot found. UserAgent=" + uaHeader); } } } // If this is a bot, is the session ID known? if (isBot) { clientIp = request.getRemoteAddr(); sessionId = clientIpSessionId.get(clientIp); if (sessionId != null) { request.setRequestedSessionId(sessionId); if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": SessionID=" + sessionId); } } } } getNext().invoke(request, response); if (isBot) { if (sessionId == null) { // Has bot just created a session, if so make a note of it HttpSession s = request.getSession(false); if (s != null) { clientIpSessionId.put(clientIp, s.getId()); sessionIdClientIp.put(s.getId(), clientIp); // #valueUnbound() will be called on session expiration s.setAttribute(this.getClass().getName(), this); s.setMaxInactiveInterval(sessionInactiveInterval); if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": New bot session. SessionID=" + s.getId()); } } } else { if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": Bot session accessed. SessionID=" + sessionId); } } } }
// in java/org/apache/catalina/valves/RemoteAddrValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { process(request.getRequest().getRemoteAddr(), request, response); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { getNext().invoke(request, response); }
// in java/org/apache/catalina/valves/StuckThreadDetectionValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (threshold <= 0) { // short-circuit if not monitoring stuck threads getNext().invoke(request, response); return; } // Save the thread/runnable // Keeping a reference to the thread object here does not prevent // GC'ing, as the reference is removed from the Map in the finally clause Long key = Long.valueOf(Thread.currentThread().getId()); StringBuffer requestUrl = request.getRequestURL(); if(request.getQueryString()!=null) { requestUrl.append("?"); requestUrl.append(request.getQueryString()); } MonitoredThread monitoredThread = new MonitoredThread(Thread.currentThread(), requestUrl.toString()); activeThreads.put(key, monitoredThread); try { getNext().invoke(request, response); } finally { activeThreads.remove(key); if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) { completedStuckThreadsQueue.add( new CompletedStuckThread(monitoredThread.getThread().getName(), monitoredThread.getActiveTimeInMillis())); } } }
// in java/org/apache/catalina/valves/SSLValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { /* mod_header converts the '\n' into ' ' so we have to rebuild the client certificate */ String strcert0 = mygetHeader(request, "ssl_client_cert"); if (strcert0 != null && strcert0.length()>28) { String strcert1 = strcert0.replace(' ', '\n'); String strcert2 = strcert1.substring(28, strcert1.length()-26); String strcert3 = "-----BEGIN CERTIFICATE-----\n"; String strcert4 = strcert3.concat(strcert2); String strcerts = strcert4.concat("\n-----END CERTIFICATE-----\n"); // ByteArrayInputStream bais = new ByteArrayInputStream(strcerts.getBytes("UTF-8")); ByteArrayInputStream bais = new ByteArrayInputStream( strcerts.getBytes(B2CConverter.ISO_8859_1)); X509Certificate jsseCerts[] = null; String providerName = (String) request.getConnector().getProperty( "clientCertProvider"); try { CertificateFactory cf; if (providerName == null) { cf = CertificateFactory.getInstance("X.509"); } else { cf = CertificateFactory.getInstance("X.509", providerName); } X509Certificate cert = (X509Certificate) cf.generateCertificate(bais); jsseCerts = new X509Certificate[1]; jsseCerts[0] = cert; } catch (java.security.cert.CertificateException e) { log.warn(sm.getString("sslValve.certError", strcerts), e); } catch (NoSuchProviderException e) { log.error(sm.getString( "sslValve.invalidProvider", providerName), e); } request.setAttribute(Globals.CERTIFICATES_ATTR, jsseCerts); } strcert0 = mygetHeader(request, "ssl_cipher"); if (strcert0 != null) { request.setAttribute(Globals.CIPHER_SUITE_ATTR, strcert0); } strcert0 = mygetHeader(request, "ssl_session_id"); if (strcert0 != null) { request.setAttribute(Globals.SSL_SESSION_ID_ATTR, strcert0); } strcert0 = mygetHeader(request, "ssl_cipher_usekeysize"); if (strcert0 != null) { request.setAttribute(Globals.KEY_SIZE_ATTR, Integer.valueOf(strcert0)); } getNext().invoke(request, response); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { // Perform the request getNext().invoke(request, response); if (response.isCommitted()) { return; } Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); if (request.isAsyncStarted() && response.getStatus() < 400 && throwable == null) { return; } if (throwable != null) { // The response is an error response.setError(); // Reset the response (if possible) try { response.reset(); } catch (IllegalStateException e) { // Ignore } response.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } response.setSuspended(false); try { report(request, response, throwable); } catch (Throwable tt) { ExceptionUtils.handleThrowable(tt); } if (request.isAsyncStarted()) { request.getAsyncContext().complete(); } }
// in java/org/apache/catalina/valves/SemaphoreValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (controlConcurrency(request, response)) { boolean shouldRelease = true; try { if (block) { if (interruptible) { try { semaphore.acquire(); } catch (InterruptedException e) { shouldRelease = false; permitDenied(request, response); return; } } else { semaphore.acquireUninterruptibly(); } } else { if (!semaphore.tryAcquire()) { shouldRelease = false; permitDenied(request, response); return; } } getNext().invoke(request, response); } finally { if (shouldRelease) { semaphore.release(); } } } else { getNext().invoke(request, response); } }
// in java/org/apache/catalina/valves/SemaphoreValve.java
public void permitDenied(Request request, Response response) throws IOException, ServletException { // NO-OP by default }
// in java/org/apache/catalina/valves/PersistentValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { // Select the Context to be used for this Request Context context = request.getContext(); if (context == null) { response.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, sm.getString("standardHost.noContext")); return; } // Bind the context CL to the current thread Thread.currentThread().setContextClassLoader (context.getLoader().getClassLoader()); // Update the session last access time for our session (if any) String sessionId = request.getRequestedSessionId(); Manager manager = context.getManager(); if (sessionId != null && manager != null) { if (manager instanceof StoreManager) { Store store = ((StoreManager) manager).getStore(); if (store != null) { Session session = null; try { session = store.load(sessionId); } catch (Exception e) { container.getLogger().error("deserializeError"); } if (session != null) { if (!session.isValid() || isSessionStale(session, System.currentTimeMillis())) { if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("session swapped in is invalid or expired"); } session.expire(); store.remove(sessionId); } else { session.setManager(manager); // session.setId(sessionId); Only if new ??? manager.add(session); // ((StandardSession)session).activate(); session.access(); session.endAccess(); } } } } } if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("sessionId: " + sessionId); } // Ask the next valve to process the request. getNext().invoke(request, response); // If still processing async, don't try to store the session // TODO: Are there some async states where it is would be safe to store // the session? if (!request.isAsync()) { // Read the sessionid after the response. // HttpSession hsess = hreq.getSession(false); Session hsess; try { hsess = request.getSessionInternal(); } catch (Exception ex) { hsess = null; } String newsessionId = null; if (hsess!=null) { newsessionId = hsess.getIdInternal(); } if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("newsessionId: " + newsessionId); } if (newsessionId!=null) { /* store the session and remove it from the manager */ if (manager instanceof StoreManager) { Session session = manager.findSession(newsessionId); Store store = ((StoreManager) manager).getStore(); if (store != null && session!=null && session.isValid() && !isSessionStale(session, System.currentTimeMillis())) { // ((StandardSession)session).passivate(); store.save(session); ((StoreManager) manager).removeSuper(session); session.recycle(); } else { if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("newsessionId store: " + store + " session: " + session + " valid: " + (session == null ? "N/A" : Boolean.toString( session.isValid())) + " stale: " + isSessionStale(session, System.currentTimeMillis())); } } } else { if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("newsessionId Manager: " + manager); } } } } }
// in java/org/apache/catalina/valves/AccessLogValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { getNext().invoke(request, response); }
// in java/org/apache/catalina/valves/RemoteIpValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { final String originalRemoteAddr = request.getRemoteAddr(); final String originalRemoteHost = request.getRemoteHost(); final String originalScheme = request.getScheme(); final boolean originalSecure = request.isSecure(); final int originalServerPort = request.getServerPort(); if (internalProxies !=null && internalProxies.matcher(originalRemoteAddr).matches()) { String remoteIp = null; // In java 6, proxiesHeaderValue should be declared as a java.util.Deque LinkedList<String> proxiesHeaderValue = new LinkedList<String>(); StringBuilder concatRemoteIpHeaderValue = new StringBuilder(); for (Enumeration<String> e = request.getHeaders(remoteIpHeader); e.hasMoreElements();) { if (concatRemoteIpHeaderValue.length() > 0) { concatRemoteIpHeaderValue.append(", "); } concatRemoteIpHeaderValue.append(e.nextElement()); } String[] remoteIpHeaderValue = commaDelimitedListToStringArray(concatRemoteIpHeaderValue.toString()); int idx; // loop on remoteIpHeaderValue to find the first trusted remote ip and to build the proxies chain for (idx = remoteIpHeaderValue.length - 1; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; remoteIp = currentRemoteIp; if (internalProxies.matcher(currentRemoteIp).matches()) { // do nothing, internalProxies IPs are not appended to the } else if (trustedProxies != null && trustedProxies.matcher(currentRemoteIp).matches()) { proxiesHeaderValue.addFirst(currentRemoteIp); } else { idx--; // decrement idx because break statement doesn't do it break; } } // continue to loop on remoteIpHeaderValue to build the new value of the remoteIpHeader LinkedList<String> newRemoteIpHeaderValue = new LinkedList<String>(); for (; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; newRemoteIpHeaderValue.addFirst(currentRemoteIp); } if (remoteIp != null) { request.setRemoteAddr(remoteIp); request.setRemoteHost(remoteIp); // use request.coyoteRequest.mimeHeaders.setValue(str).setString(str) because request.addHeader(str, str) is no-op in Tomcat // 6.0 if (proxiesHeaderValue.size() == 0) { request.getCoyoteRequest().getMimeHeaders().removeHeader(proxiesHeader); } else { String commaDelimitedListOfProxies = listToCommaDelimitedString(proxiesHeaderValue); request.getCoyoteRequest().getMimeHeaders().setValue(proxiesHeader).setString(commaDelimitedListOfProxies); } if (newRemoteIpHeaderValue.size() == 0) { request.getCoyoteRequest().getMimeHeaders().removeHeader(remoteIpHeader); } else { String commaDelimitedRemoteIpHeaderValue = listToCommaDelimitedString(newRemoteIpHeaderValue); request.getCoyoteRequest().getMimeHeaders().setValue(remoteIpHeader).setString(commaDelimitedRemoteIpHeaderValue); } } if (protocolHeader != null) { String protocolHeaderValue = request.getHeader(protocolHeader); if (protocolHeaderValue == null) { // don't modify the secure,scheme and serverPort attributes // of the request } else if (protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue)) { request.setSecure(true); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString("https"); setPorts(request, httpsServerPort); } else { request.setSecure(false); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString("http"); setPorts(request, httpServerPort); } } if (log.isDebugEnabled()) { log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr '" + originalRemoteAddr + "', originalRemoteHost='" + originalRemoteHost + "', originalSecure='" + originalSecure + "', originalScheme='" + originalScheme + "' will be seen as newRemoteAddr='" + request.getRemoteAddr() + "', newRemoteHost='" + request.getRemoteHost() + "', newScheme='" + request.getScheme() + "', newSecure='" + request.isSecure() + "'"); } } else { if (log.isDebugEnabled()) { log.debug("Skip RemoteIpValve for request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "'"); } } if (requestAttributesEnabled) { request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE, request.getRemoteAddr()); request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE, request.getRemoteHost()); request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE, request.getProtocol()); request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE, Integer.valueOf(request.getServerPort())); } try { getNext().invoke(request, response); } finally { request.setRemoteAddr(originalRemoteAddr); request.setRemoteHost(originalRemoteHost); request.setSecure(originalSecure); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString(originalScheme); request.setServerPort(originalServerPort); } }
// in java/org/apache/catalina/valves/ValveBase.java
Override public void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Perform the request getNext().event(request, response, event); }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
public String getToken() throws IOException { if(ended) { return null ; } String result = null; subToken = false; parameter = false; int c = sr.read(); while (c != -1) { switch (c) { case ' ': result = buf.toString(); buf = new StringBuilder(); buf.append((char) c); return result; case '-': result = buf.toString(); buf = new StringBuilder(); subToken = true; return result; case '(': result = buf.toString(); buf = new StringBuilder(); parameter = true; return result; case ')': result = buf.toString(); buf = new StringBuilder(); break; default: buf.append((char) c); } c = sr.read(); } ended = true; if (buf.length() != 0) { return buf.toString(); } else { return null; } }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
public String getParameter()throws IOException { String result; if (!parameter) { return null; } parameter = false; int c = sr.read(); while (c != -1) { if (c == ')') { result = buf.toString(); buf = new StringBuilder(); return result; } buf.append((char) c); c = sr.read(); } return null; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
public String getWhiteSpaces() throws IOException { if(isEnded()) { return "" ; } StringBuilder whiteSpaces = new StringBuilder(); if (buf.length() > 0) { whiteSpaces.append(buf); buf = new StringBuilder(); } int c = sr.read(); while (Character.isWhitespace((char) c)) { whiteSpaces.append((char) c); c = sr.read(); } if (c == -1) { ended = true; } else { buf.append((char) c); } return whiteSpaces.toString(); }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
public String getRemains() throws IOException { StringBuilder remains = new StringBuilder(); for(int c = sr.read(); c != -1; c = sr.read()) { remains.append((char) c); } return remains.toString(); }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
protected AccessLogElement getLogElement(String token, PatternTokenizer tokenizer) throws IOException { if ("date".equals(token)) { return new DateElement(); } else if ("time".equals(token)) { if (tokenizer.hasSubToken()) { String nextToken = tokenizer.getToken(); if ("taken".equals(nextToken)) { return new ElapsedTimeElement(false); } } else { return new TimeElement(); } } else if ("bytes".equals(token)) { return new ByteSentElement(true); } else if ("cached".equals(token)) { /* I don't know how to evaluate this! */ return new StringElement("-"); } else if ("c".equals(token)) { String nextToken = tokenizer.getToken(); if ("ip".equals(nextToken)) { return new RemoteAddrElement(); } else if ("dns".equals(nextToken)) { return new HostElement(); } } else if ("s".equals(token)) { String nextToken = tokenizer.getToken(); if ("ip".equals(nextToken)) { return new LocalAddrElement(); } else if ("dns".equals(nextToken)) { return new AccessLogElement() { @Override public void addElement(StringBuilder buf, Date date, Request request, Response response, long time) { String value; try { value = InetAddress.getLocalHost().getHostName(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); value = "localhost"; } buf.append(value); } }; } } else if ("cs".equals(token)) { return getClientToServerElement(tokenizer); } else if ("sc".equals(token)) { return getServerToClientElement(tokenizer); } else if ("sr".equals(token) || "rs".equals(token)) { return getProxyElement(tokenizer); } else if ("x".equals(token)) { return getXParameterElement(tokenizer); } log.error("unable to decode with rest of chars starting: " + token); return null; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
protected AccessLogElement getClientToServerElement( PatternTokenizer tokenizer) throws IOException { if (tokenizer.hasSubToken()) { String token = tokenizer.getToken(); if ("method".equals(token)) { return new MethodElement(); } else if ("uri".equals(token)) { if (tokenizer.hasSubToken()) { token = tokenizer.getToken(); if ("stem".equals(token)) { return new RequestURIElement(); } else if ("query".equals(token)) { return new AccessLogElement() { @Override public void addElement(StringBuilder buf, Date date, Request request, Response response, long time) { String query = request.getQueryString(); if (query != null) { buf.append(query); } else { buf.append('-'); } } }; } } else { return new AccessLogElement() { @Override public void addElement(StringBuilder buf, Date date, Request request, Response response, long time) { String query = request.getQueryString(); if (query == null) { buf.append(request.getRequestURI()); } else { buf.append(request.getRequestURI()); buf.append('?'); buf.append(request.getQueryString()); } } }; } } } else if (tokenizer.hasParameter()) { String parameter = tokenizer.getParameter(); if (parameter == null) { log.error("No closing ) found for in decode"); return null; } return new RequestHeaderElement(parameter); } log.error("The next characters couldn't be decoded: " + tokenizer.getRemains()); return null; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
protected AccessLogElement getServerToClientElement( PatternTokenizer tokenizer) throws IOException { if (tokenizer.hasSubToken()) { String token = tokenizer.getToken(); if ("status".equals(token)) { return new HttpStatusCodeElement(); } else if ("comment".equals(token)) { return new StringElement("?"); } } else if (tokenizer.hasParameter()) { String parameter = tokenizer.getParameter(); if (parameter == null) { log.error("No closing ) found for in decode"); return null; } return new ResponseHeaderElement(parameter); } log.error("The next characters couldn't be decoded: " + tokenizer.getRemains()); return null; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
protected AccessLogElement getProxyElement(PatternTokenizer tokenizer) throws IOException { String token = null; if (tokenizer.hasSubToken()) { tokenizer.getToken(); return new StringElement("-"); } else if (tokenizer.hasParameter()) { tokenizer.getParameter(); return new StringElement("-"); } log.error("The next characters couldn't be decoded: " + token); return null; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
protected AccessLogElement getXParameterElement(PatternTokenizer tokenizer) throws IOException { if (!tokenizer.hasSubToken()) { log.error("x param in wrong format. Needs to be 'x-#(...)' read the docs!"); return null; } String token = tokenizer.getToken(); if ("threadname".equals(token)) { return new ThreadNameElement(); } if (!tokenizer.hasParameter()) { log.error("x param in wrong format. Needs to be 'x-#(...)' read the docs!"); return null; } String parameter = tokenizer.getParameter(); if (parameter == null) { log.error("No closing ) found for in decode"); return null; } if ("A".equals(token)) { return new ServletContextElement(parameter); } else if ("C".equals(token)) { return new CookieElement(parameter); } else if ("R".equals(token)) { return new RequestAttributeElement(parameter); } else if ("S".equals(token)) { return new SessionAttributeElement(parameter); } else if ("H".equals(token)) { return getServletRequestElement(parameter); } else if ("P".equals(token)) { return new RequestParameterElement(parameter); } else if ("O".equals(token)) { return new ResponseAllHeaderElement(parameter); } log.error("x param for servlet request, couldn't decode value: " + token); return null; }
// in java/org/apache/catalina/authenticator/SingleSignOn.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { request.removeNote(Constants.REQ_SSOID_NOTE); // Has a valid user already been authenticated? if (containerLog.isDebugEnabled()) { containerLog.debug("Process request for '" + request.getRequestURI() + "'"); } if (request.getUserPrincipal() != null) { if (containerLog.isDebugEnabled()) { containerLog.debug(" Principal '" + request.getUserPrincipal().getName() + "' has already been authenticated"); } getNext().invoke(request, response); return; } // Check for the single sign on cookie if (containerLog.isDebugEnabled()) { containerLog.debug(" Checking for SSO cookie"); } Cookie cookie = null; Cookie cookies[] = request.getCookies(); if (cookies == null) { cookies = new Cookie[0]; } for (int i = 0; i < cookies.length; i++) { if (Constants.SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) { cookie = cookies[i]; break; } } if (cookie == null) { if (containerLog.isDebugEnabled()) { containerLog.debug(" SSO cookie is not present"); } getNext().invoke(request, response); return; } // Look up the cached Principal associated with this cookie value if (containerLog.isDebugEnabled()) { containerLog.debug(" Checking for cached principal for " + cookie.getValue()); } SingleSignOnEntry entry = lookup(cookie.getValue()); if (entry != null) { if (containerLog.isDebugEnabled()) { containerLog.debug(" Found cached principal '" + (entry.getPrincipal() != null ? entry.getPrincipal().getName() : "") + "' with auth type '" + entry.getAuthType() + "'"); } request.setNote(Constants.REQ_SSOID_NOTE, cookie.getValue()); // Only set security elements if reauthentication is not required if (!getRequireReauthentication()) { request.setAuthType(entry.getAuthType()); request.setUserPrincipal(entry.getPrincipal()); } } else { if (containerLog.isDebugEnabled()) { containerLog.debug(" No cached principal found, erasing SSO cookie"); } cookie.setMaxAge(0); response.addCookie(cookie); } // Invoke the next Valve in our pipeline getNext().invoke(request, response); }
// in java/org/apache/catalina/authenticator/SSLAuthenticator.java
Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { // Have we already authenticated someone? Principal principal = request.getUserPrincipal(); //String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (containerLog.isDebugEnabled()) { containerLog.debug("Already authenticated '" + principal.getName() + "'"); } // Associate the session with any existing SSO session in order // to get coordinated session invalidation at logout String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return (true); } // NOTE: We don't try to reauthenticate using any existing SSO session, // because that will only work if the original authentication was // BASIC or FORM, which are less secure than the CLIENT_CERT auth-type // specified for this webapp // // Uncomment below to allow previous FORM or BASIC authentications // to authenticate users for this webapp // TODO make this a configurable attribute (in SingleSignOn??) /* // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); // Try to reauthenticate using data cached by SSO. If this fails, // either the original SSO logon was of DIGEST or SSL (which // we can't reauthenticate ourselves because there is no // cached username and password), or the realm denied // the user's reauthentication for some reason. // In either case we have to prompt the user for a logon if (reauthenticateFromSSO(ssoId, request)) return true; } */ // Retrieve the certificate chain for this client if (containerLog.isDebugEnabled()) { containerLog.debug(" Looking up certificates"); } X509Certificate certs[] = (X509Certificate[]) request.getAttribute(Globals.CERTIFICATES_ATTR); if ((certs == null) || (certs.length < 1)) { try { request.getCoyoteRequest().action (ActionCode.REQ_SSL_CERTIFICATE, null); } catch (IllegalStateException ise) { // Request body was too large for save buffer response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.certificates")); return false; } certs = (X509Certificate[]) request.getAttribute(Globals.CERTIFICATES_ATTR); } if ((certs == null) || (certs.length < 1)) { if (containerLog.isDebugEnabled()) { containerLog.debug(" No certificates included with this request"); } response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.certificates")); return (false); } // Authenticate the specified certificate chain principal = context.getRealm().authenticate(certs); if (principal == null) { if (containerLog.isDebugEnabled()) { containerLog.debug(" Realm.authenticate() returned false"); } response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.unauthorized")); return (false); } // Cache the principal (if requested) and record this authentication register(request, response, principal, HttpServletRequest.CLIENT_CERT_AUTH, null, null); return (true); }
// in java/org/apache/catalina/authenticator/NonLoginAuthenticator.java
Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { Principal principal = request.getPrincipal(); if (principal != null) { // excellent... we have already authenticated the client somehow, // probably from another container that has a login-config if (containerLog.isDebugEnabled()) containerLog.debug("Already authenticated as '" + principal.getName() + "'"); if (cache) { // create a new session (only if necessary) Session session = request.getSessionInternal(true); // save the inherited Principal (if necessary) in this // session so it can remain authenticated until it expires session.setPrincipal(principal); // is there an SSO session cookie? String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (ssoId != null) { if (containerLog.isDebugEnabled()) containerLog.debug("User authenticated by existing SSO"); // Associate session with the existing SSO ID if necessary associate(ssoId, session); } } // user was already authenticated, with or without a cookie return true; } // No Principal means the user is not already authenticated // and so will not be assigned any roles. It is safe to // to say the user is now authenticated because access to // protected resources will only be allowed with a matching role. // i.e. SC_FORBIDDEN (403 status) will be generated later. if (containerLog.isDebugEnabled()) containerLog.debug("User authenticated without any roles"); return true; }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (log.isDebugEnabled()) { log.debug("Security checking request " + request.getMethod() + " " + request.getRequestURI()); } // Have we got a cached authenticated Principal to record? if (cache) { Principal principal = request.getUserPrincipal(); if (principal == null) { Session session = request.getSessionInternal(false); if (session != null) { principal = session.getPrincipal(); if (principal != null) { if (log.isDebugEnabled()) { log.debug("We have cached auth type " + session.getAuthType() + " for principal " + session.getPrincipal()); } request.setAuthType(session.getAuthType()); request.setUserPrincipal(principal); } } } } // Special handling for form-based logins to deal with the case // where the login form (and therefore the "j_security_check" URI // to which it submits) might be outside the secured area String contextPath = this.context.getPath(); String requestURI = request.getDecodedRequestURI(); if (requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION)) { if (!authenticate(request, response)) { if (log.isDebugEnabled()) { log.debug(" Failed authenticate() test ??" + requestURI ); } return; } } // The Servlet may specify security constraints through annotations. // Ensure that they have been processed before constraints are checked Wrapper wrapper = (Wrapper) request.getMappingData().wrapper; if (wrapper != null) { wrapper.servletSecurityAnnotationScan(); } Realm realm = this.context.getRealm(); // Is this request URI subject to a security constraint? SecurityConstraint [] constraints = realm.findSecurityConstraints(request, this.context); if (constraints == null && !context.getPreemptiveAuthentication()) { if (log.isDebugEnabled()) { log.debug(" Not subject to any constraint"); } getNext().invoke(request, response); return; } // Make sure that constrained resources are not cached by web proxies // or browsers as caching can provide a security hole if (constraints != null && disableProxyCaching && !"POST".equalsIgnoreCase(request.getMethod())) { if (securePagesWithPragma) { // Note: These can cause problems with downloading files with IE response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); } else { response.setHeader("Cache-Control", "private"); } response.setHeader("Expires", DATE_ONE); } int i; if (constraints != null) { // Enforce any user data constraint for this security constraint if (log.isDebugEnabled()) { log.debug(" Calling hasUserDataPermission()"); } if (!realm.hasUserDataPermission(request, response, constraints)) { if (log.isDebugEnabled()) { log.debug(" Failed hasUserDataPermission() test"); } /* * ASSERT: Authenticator already set the appropriate * HTTP status code, so we do not have to do anything special */ return; } } // Since authenticate modifies the response on failure, // we have to check for allow-from-all first. boolean authRequired; if (constraints == null) { authRequired = false; } else { authRequired = true; for(i=0; i < constraints.length && authRequired; i++) { if(!constraints[i].getAuthConstraint()) { authRequired = false; } else if(!constraints[i].getAllRoles()) { String [] roles = constraints[i].findAuthRoles(); if(roles == null || roles.length == 0) { authRequired = false; } } } } if (!authRequired && context.getPreemptiveAuthentication()) { authRequired = request.getCoyoteRequest().getMimeHeaders().getValue( "authorization") != null; } if (!authRequired && context.getPreemptiveAuthentication()) { X509Certificate[] certs = (X509Certificate[]) request.getAttribute( Globals.CERTIFICATES_ATTR); authRequired = certs != null && certs.length > 0; } if(authRequired) { if (log.isDebugEnabled()) { log.debug(" Calling authenticate()"); } if (!authenticate(request, response)) { if (log.isDebugEnabled()) { log.debug(" Failed authenticate() test"); } /* * ASSERT: Authenticator already set the appropriate * HTTP status code, so we do not have to do anything * special */ return; } } if (constraints != null) { if (log.isDebugEnabled()) { log.debug(" Calling accessControl()"); } if (!realm.hasResourcePermission(request, response, constraints, this.context)) { if (log.isDebugEnabled()) { log.debug(" Failed accessControl() test"); } /* * ASSERT: AccessControl method has already set the * appropriate HTTP status code, so we do not have to do * anything special */ return; } } // Any and all specified constraints have been satisfied if (log.isDebugEnabled()) { log.debug(" Successfully passed all security constraints"); } getNext().invoke(request, response); }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { // Have we already authenticated someone? Principal principal = request.getUserPrincipal(); //String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (log.isDebugEnabled()) { log.debug("Already authenticated '" + principal.getName() + "'"); } // Associate the session with any existing SSO session in order // to get coordinated session invalidation at logout String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return (true); } // NOTE: We don't try to reauthenticate using any existing SSO session, // because that will only work if the original authentication was // BASIC or FORM, which are less secure than the DIGEST auth-type // specified for this webapp // // Uncomment below to allow previous FORM or BASIC authentications // to authenticate users for this webapp // TODO make this a configurable attribute (in SingleSignOn??) /* // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); // Try to reauthenticate using data cached by SSO. If this fails, // either the original SSO logon was of DIGEST or SSL (which // we can't reauthenticate ourselves because there is no // cached username and password), or the realm denied // the user's reauthentication for some reason. // In either case we have to prompt the user for a logon if (reauthenticateFromSSO(ssoId, request)) return true; } */ // Validate any credentials already included with this request String authorization = request.getHeader("authorization"); DigestInfo digestInfo = new DigestInfo(getOpaque(), getNonceValidity(), getKey(), cnonces, isValidateUri()); if (authorization != null) { if (digestInfo.validate(request, authorization)) { principal = digestInfo.authenticate(context.getRealm()); } if (principal != null) { String username = parseUsername(authorization); register(request, response, principal, HttpServletRequest.DIGEST_AUTH, username, null); return (true); } } // Send an "unauthorized" response and an appropriate challenge // Next, generate a nonce token (that is a token which is supposed // to be unique). String nonce = generateNonce(request); setAuthenticateHeader(request, response, nonce, digestInfo.isNonceStale()); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); // hres.flushBuffer(); return (false); }
// in java/org/apache/catalina/authenticator/BasicAuthenticator.java
Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { // Have we already authenticated someone? Principal principal = request.getUserPrincipal(); String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (log.isDebugEnabled()) { log.debug("Already authenticated '" + principal.getName() + "'"); } // Associate the session with any existing SSO session if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return (true); } // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) { log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); } /* Try to reauthenticate using data cached by SSO. If this fails, either the original SSO logon was of DIGEST or SSL (which we can't reauthenticate ourselves because there is no cached username and password), or the realm denied the user's reauthentication for some reason. In either case we have to prompt the user for a logon */ if (reauthenticateFromSSO(ssoId, request)) { return true; } } // Validate any credentials already included with this request String username = null; String password = null; MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders() .getValue("authorization"); if (authorization != null) { authorization.toBytes(); ByteChunk authorizationBC = authorization.getByteChunk(); if (authorizationBC.startsWithIgnoreCase("basic ", 0)) { authorizationBC.setOffset(authorizationBC.getOffset() + 6); // FIXME: Add trimming // authorizationBC.trim(); CharChunk authorizationCC = authorization.getCharChunk(); Base64.decode(authorizationBC, authorizationCC); // Get username and password int colon = authorizationCC.indexOf(':'); if (colon < 0) { username = authorizationCC.toString(); } else { char[] buf = authorizationCC.getBuffer(); username = new String(buf, 0, colon); password = new String(buf, colon + 1, authorizationCC.getEnd() - colon - 1); } authorizationBC.setOffset(authorizationBC.getOffset() - 6); } principal = context.getRealm().authenticate(username, password); if (principal != null) { register(request, response, principal, HttpServletRequest.BASIC_AUTH, username, password); return (true); } } StringBuilder value = new StringBuilder(16); value.append("Basic realm=\""); value.append(getRealmName(context)); value.append('\"'); response.setHeader(AUTH_HEADER_NAME, value.toString()); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return (false); }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { // Have we already authenticated someone? Principal principal = request.getUserPrincipal(); String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (log.isDebugEnabled()) { log.debug("Already authenticated '" + principal.getName() + "'"); } // Associate the session with any existing SSO session if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return true; } // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) { log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); } /* Try to reauthenticate using data cached by SSO. If this fails, either the original SSO logon was of DIGEST or SSL (which we can't reauthenticate ourselves because there is no cached username and password), or the realm denied the user's reauthentication for some reason. In either case we have to prompt the user for a logon */ if (reauthenticateFromSSO(ssoId, request)) { return true; } } MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders() .getValue("authorization"); if (authorization == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("authenticator.noAuthHeader")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } authorization.toBytes(); ByteChunk authorizationBC = authorization.getByteChunk(); if (!authorizationBC.startsWithIgnoreCase("negotiate ", 0)) { if (log.isDebugEnabled()) { log.debug(sm.getString( "spnegoAuthenticator.authHeaderNotNego")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } authorizationBC.setOffset(authorizationBC.getOffset() + 10); // FIXME: Add trimming // authorizationBC.trim(); ByteChunk decoded = new ByteChunk(); Base64.decode(authorizationBC, decoded); if (decoded.getLength() == 0) { if (log.isDebugEnabled()) { log.debug(sm.getString( "spnegoAuthenticator.authHeaderNoToken")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } LoginContext lc = null; GSSContext gssContext = null; byte[] outToken = null; try { try { lc = new LoginContext(getLoginConfigName()); lc.login(); } catch (LoginException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; } // Assume the GSSContext is stateless // TODO: Confirm this assumption final GSSManager manager = GSSManager.getInstance(); final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() { @Override public GSSCredential run() throws GSSException { return manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME, new Oid("1.3.6.1.5.5.2"), GSSCredential.ACCEPT_ONLY); } }; gssContext = manager.createContext(Subject.doAs(lc.getSubject(), action)); outToken = gssContext.acceptSecContext(decoded.getBytes(), decoded.getOffset(), decoded.getLength()); if (outToken == null) { if (log.isDebugEnabled()) { log.debug(sm.getString( "spnegoAuthenticator.ticketValidateFail")); } // Start again response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } principal = context.getRealm().authenticate(gssContext, isStoreDelegatedCredential()); } catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail", e)); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } catch (PrivilegedActionException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail", e)); response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } finally { if (gssContext != null) { try { gssContext.dispose(); } catch (GSSException e) { // Ignore } } if (lc != null) { try { lc.logout(); } catch (LoginException e) { // Ignore } } } // Send response token on success and failure response.setHeader("WWW-Authenticate", "Negotiate " + Base64.encode(outToken)); if (principal != null) { register(request, response, principal, Constants.SPNEGO_METHOD, principal.getName(), null); return true; } response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { // References to objects we will need later Session session = null; // Have we already authenticated someone? Principal principal = request.getUserPrincipal(); String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (log.isDebugEnabled()) { log.debug("Already authenticated '" + principal.getName() + "'"); } // Associate the session with any existing SSO session if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return (true); } // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) { log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); } // Try to reauthenticate using data cached by SSO. If this fails, // either the original SSO logon was of DIGEST or SSL (which // we can't reauthenticate ourselves because there is no // cached username and password), or the realm denied // the user's reauthentication for some reason. // In either case we have to prompt the user for a logon */ if (reauthenticateFromSSO(ssoId, request)) { return true; } } // Have we authenticated this user before but have caching disabled? if (!cache) { session = request.getSessionInternal(true); if (log.isDebugEnabled()) { log.debug("Checking for reauthenticate in session " + session); } String username = (String) session.getNote(Constants.SESS_USERNAME_NOTE); String password = (String) session.getNote(Constants.SESS_PASSWORD_NOTE); if ((username != null) && (password != null)) { if (log.isDebugEnabled()) { log.debug("Reauthenticating username '" + username + "'"); } principal = context.getRealm().authenticate(username, password); if (principal != null) { session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal); if (!matchRequest(request)) { register(request, response, principal, HttpServletRequest.FORM_AUTH, username, password); return (true); } } if (log.isDebugEnabled()) { log.debug("Reauthentication failed, proceed normally"); } } } // Is this the re-submit of the original request URI after successful // authentication? If so, forward the *original* request instead. if (matchRequest(request)) { session = request.getSessionInternal(true); if (log.isDebugEnabled()) { log.debug("Restore request from session '" + session.getIdInternal() + "'"); } principal = (Principal) session.getNote(Constants.FORM_PRINCIPAL_NOTE); register(request, response, principal, HttpServletRequest.FORM_AUTH, (String) session.getNote(Constants.SESS_USERNAME_NOTE), (String) session.getNote(Constants.SESS_PASSWORD_NOTE)); // If we're caching principals we no longer need the username // and password in the session, so remove them if (cache) { session.removeNote(Constants.SESS_USERNAME_NOTE); session.removeNote(Constants.SESS_PASSWORD_NOTE); } if (restoreRequest(request, session)) { if (log.isDebugEnabled()) { log.debug("Proceed to restored request"); } return (true); } else { if (log.isDebugEnabled()) { log.debug("Restore of original request failed"); } response.sendError(HttpServletResponse.SC_BAD_REQUEST); return (false); } } // Acquire references to objects we will need to evaluate MessageBytes uriMB = MessageBytes.newInstance(); CharChunk uriCC = uriMB.getCharChunk(); uriCC.setLimit(-1); String contextPath = request.getContextPath(); String requestURI = request.getDecodedRequestURI(); // Is this the action request from the login page? boolean loginAction = requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION); LoginConfig config = context.getLoginConfig(); // No -- Save this request and redirect to the form login page if (!loginAction) { session = request.getSessionInternal(true); if (log.isDebugEnabled()) { log.debug("Save request in session '" + session.getIdInternal() + "'"); } try { saveRequest(request, session); } catch (IOException ioe) { log.debug("Request body too big to save during authentication"); response.sendError(HttpServletResponse.SC_FORBIDDEN, sm.getString("authenticator.requestBodyTooBig")); return (false); } forwardToLoginPage(request, response, config); return (false); } // Yes -- Acknowledge the request, validate the specified credentials // and redirect to the error page if they are not correct request.getResponse().sendAcknowledgement(); Realm realm = context.getRealm(); if (characterEncoding != null) { request.setCharacterEncoding(characterEncoding); } String username = request.getParameter(Constants.FORM_USERNAME); String password = request.getParameter(Constants.FORM_PASSWORD); if (log.isDebugEnabled()) { log.debug("Authenticating username '" + username + "'"); } principal = realm.authenticate(username, password); if (principal == null) { forwardToErrorPage(request, response, config); return (false); } if (log.isDebugEnabled()) { log.debug("Authentication of '" + username + "' was successful"); } if (session == null) { session = request.getSessionInternal(false); } if (session == null) { if (containerLog.isDebugEnabled()) { containerLog.debug ("User took so long to log on the session expired"); } if (landingPage == null) { response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT, sm.getString("authenticator.sessionExpired")); } else { // Make the authenticator think the user originally requested // the landing page String uri = request.getContextPath() + landingPage; SavedRequest saved = new SavedRequest(); saved.setMethod("GET"); saved.setRequestURI(uri); request.getSessionInternal(true).setNote( Constants.FORM_REQUEST_NOTE, saved); response.sendRedirect(response.encodeRedirectURL(uri)); } return (false); } // Save the authenticated Principal in our session session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal); // Save the username and password as well session.setNote(Constants.SESS_USERNAME_NOTE, username); session.setNote(Constants.SESS_PASSWORD_NOTE, password); // Redirect the user to the original request URI (which will cause // the original request to be restored) requestURI = savedRequestURL(session); if (log.isDebugEnabled()) { log.debug("Redirecting to original '" + requestURI + "'"); } if (requestURI == null) { if (landingPage == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, sm.getString("authenticator.formlogin")); } else { // Make the authenticator think the user originally requested // the landing page String uri = request.getContextPath() + landingPage; SavedRequest saved = new SavedRequest(); saved.setMethod("GET"); saved.setRequestURI(uri); session.setNote(Constants.FORM_REQUEST_NOTE, saved); response.sendRedirect(response.encodeRedirectURL(uri)); } } else { response.sendRedirect(response.encodeRedirectURL(requestURI)); } return (false); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
protected void forwardToLoginPage(Request request, HttpServletResponse response, LoginConfig config) throws IOException { if (log.isDebugEnabled()) { log.debug(sm.getString("formAuthenticator.forwardLogin", request.getRequestURI(), request.getMethod(), config.getLoginPage(), context.getName())); } String loginPage = config.getLoginPage(); if (loginPage == null || loginPage.length() == 0) { String msg = sm.getString("formAuthenticator.noLoginPage", context.getName()); log.warn(msg); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); return; } // Always use GET for the login page, regardless of the method used String oldMethod = request.getMethod(); request.getCoyoteRequest().method().setString("GET"); RequestDispatcher disp = context.getServletContext().getRequestDispatcher(loginPage); try { if (context.fireRequestInitEvent(request)) { disp.forward(request.getRequest(), response); context.fireRequestDestroyEvent(request); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardLoginFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } finally { // Restore original method so that it is written into access log request.getCoyoteRequest().method().setString(oldMethod); } }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
protected void forwardToErrorPage(Request request, HttpServletResponse response, LoginConfig config) throws IOException { String errorPage = config.getErrorPage(); if (errorPage == null || errorPage.length() == 0) { String msg = sm.getString("formAuthenticator.noErrorPage", context.getName()); log.warn(msg); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); return; } RequestDispatcher disp = context.getServletContext().getRequestDispatcher (config.getErrorPage()); try { if (context.fireRequestInitEvent(request)) { disp.forward(request.getRequest(), response); context.fireRequestDestroyEvent(request); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardErrorFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
protected boolean restoreRequest(Request request, Session session) throws IOException { // Retrieve and remove the SavedRequest object from our session SavedRequest saved = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE); session.removeNote(Constants.FORM_REQUEST_NOTE); session.removeNote(Constants.FORM_PRINCIPAL_NOTE); if (saved == null) { return (false); } // Modify our current request to reflect the original one request.clearCookies(); Iterator<Cookie> cookies = saved.getCookies(); while (cookies.hasNext()) { request.addCookie(cookies.next()); } String method = saved.getMethod(); MimeHeaders rmh = request.getCoyoteRequest().getMimeHeaders(); rmh.recycle(); boolean cachable = "GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method); Iterator<String> names = saved.getHeaderNames(); while (names.hasNext()) { String name = names.next(); // The browser isn't expecting this conditional response now. // Assuming that it can quietly recover from an unexpected 412. // BZ 43687 if(!("If-Modified-Since".equalsIgnoreCase(name) || (cachable && "If-None-Match".equalsIgnoreCase(name)))) { Iterator<String> values = saved.getHeaderValues(name); while (values.hasNext()) { rmh.addValue(name).setString(values.next()); } } } request.clearLocales(); Iterator<Locale> locales = saved.getLocales(); while (locales.hasNext()) { request.addLocale(locales.next()); } request.getCoyoteRequest().getParameters().recycle(); request.getCoyoteRequest().getParameters().setQueryStringEncoding( request.getConnector().getURIEncoding()); // Swallow any request body since we will be replacing it byte[] buffer = new byte[4096]; InputStream is = request.createInputStream(); while (is.read(buffer) >= 0) { // Ignore request body } ByteChunk body = saved.getBody(); if (body != null) { request.getCoyoteRequest().action (ActionCode.REQ_SET_BODY_REPLAY, body); // Set content type MessageBytes contentType = MessageBytes.newInstance(); // If no content type specified, use default for POST String savedContentType = saved.getContentType(); if (savedContentType == null && "POST".equalsIgnoreCase(method)) { savedContentType = "application/x-www-form-urlencoded"; } contentType.setString(savedContentType); request.getCoyoteRequest().setContentType(contentType); } request.getCoyoteRequest().method().setString(method); request.getCoyoteRequest().queryString().setString (saved.getQueryString()); request.getCoyoteRequest().requestURI().setString (saved.getRequestURI()); return (true); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
protected void saveRequest(Request request, Session session) throws IOException { // Create and populate a SavedRequest object for this request SavedRequest saved = new SavedRequest(); Cookie cookies[] = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { saved.addCookie(cookies[i]); } } Enumeration<String> names = request.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); Enumeration<String> values = request.getHeaders(name); while (values.hasMoreElements()) { String value = values.nextElement(); saved.addHeader(name, value); } } Enumeration<Locale> locales = request.getLocales(); while (locales.hasMoreElements()) { Locale locale = locales.nextElement(); saved.addLocale(locale); } // May need to acknowledge a 100-continue expectation request.getResponse().sendAcknowledgement(); ByteChunk body = new ByteChunk(); body.setLimit(request.getConnector().getMaxSavePostSize()); byte[] buffer = new byte[4096]; int bytesRead; InputStream is = request.getInputStream(); while ( (bytesRead = is.read(buffer) ) >= 0) { body.append(buffer, 0, bytesRead); } // Only save the request body if there is something to save if (body.getLength() > 0) { saved.setContentType(request.getContentType()); saved.setBody(body); } saved.setMethod(request.getMethod()); saved.setQueryString(request.getQueryString()); saved.setRequestURI(request.getRequestURI()); // Stash the SavedRequest in our session for later use session.setNote(Constants.FORM_REQUEST_NOTE, saved); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Serve the requested resource, including the data content serveResource(request, response, true); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doHead(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Serve the requested resource, without the data content serveResource(request, response, false); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { StringBuilder allow = new StringBuilder(); // There is a doGet method allow.append("GET, HEAD"); // There is a doPost allow.append(", POST"); // There is a doPut allow.append(", PUT"); // There is a doDelete allow.append(", DELETE"); // Trace - assume disabled unless we can prove otherwise if (req instanceof RequestFacade && ((RequestFacade) req).getAllowTrace()) { allow.append(", TRACE"); } // Always allow options allow.append(", OPTIONS"); resp.setHeader("Allow", allow.toString()); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String path = getRelativePath(req); boolean exists = true; try { resources.lookup(path); } catch (NamingException e) { exists = false; } boolean result = true; // Temp. content file used to support partial PUT File contentFile = null; Range range = parseContentRange(req, resp); InputStream resourceInputStream = null; // Append data specified in ranges to existing content for this // resource - create a temp. file on the local filesystem to // perform this operation // Assume just one range is specified for now if (range != null) { contentFile = executePartialPut(req, range, path); resourceInputStream = new FileInputStream(contentFile); } else { resourceInputStream = req.getInputStream(); } try { Resource newResource = new Resource(resourceInputStream); // FIXME: Add attributes if (exists) { resources.rebind(path, newResource); } else { resources.bind(path, newResource); } } catch(NamingException e) { result = false; } if (result) { if (exists) { resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { resp.setStatus(HttpServletResponse.SC_CREATED); } } else { resp.sendError(HttpServletResponse.SC_CONFLICT); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected File executePartialPut(HttpServletRequest req, Range range, String path) throws IOException { // Append data specified in ranges to existing content for this // resource - create a temp. file on the local filesystem to // perform this operation File tempDir = (File) getServletContext().getAttribute (ServletContext.TEMPDIR); // Convert all '/' characters to '.' in resourcePath String convertedResourcePath = path.replace('/', '.'); File contentFile = new File(tempDir, convertedResourcePath); if (contentFile.createNewFile()) { // Clean up contentFile when Tomcat is terminated contentFile.deleteOnExit(); } RandomAccessFile randAccessContentFile = new RandomAccessFile(contentFile, "rw"); Resource oldResource = null; try { Object obj = resources.lookup(path); if (obj instanceof Resource) oldResource = (Resource) obj; } catch (NamingException e) { // Ignore } // Copy data in oldRevisionContent to contentFile if (oldResource != null) { BufferedInputStream bufOldRevStream = new BufferedInputStream(oldResource.streamContent(), BUFFER_SIZE); int numBytesRead; byte[] copyBuffer = new byte[BUFFER_SIZE]; while ((numBytesRead = bufOldRevStream.read(copyBuffer)) != -1) { randAccessContentFile.write(copyBuffer, 0, numBytesRead); } bufOldRevStream.close(); } randAccessContentFile.setLength(range.length); // Append data in request input stream to contentFile randAccessContentFile.seek(range.start); int numBytesRead; byte[] transferBuffer = new byte[BUFFER_SIZE]; BufferedInputStream requestBufInStream = new BufferedInputStream(req.getInputStream(), BUFFER_SIZE); while ((numBytesRead = requestBufInStream.read(transferBuffer)) != -1) { randAccessContentFile.write(transferBuffer, 0, numBytesRead); } randAccessContentFile.close(); requestBufInStream.close(); return contentFile; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String path = getRelativePath(req); boolean exists = true; try { resources.lookup(path); } catch (NamingException e) { exists = false; } if (exists) { boolean result = true; try { resources.unbind(path); } catch (NamingException e) { result = false; } if (result) { resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected boolean checkIfHeaders(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) throws IOException { return checkIfMatch(request, response, resourceAttributes) && checkIfModifiedSince(request, response, resourceAttributes) && checkIfNoneMatch(request, response, resourceAttributes) && checkIfUnmodifiedSince(request, response, resourceAttributes); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException { boolean serveContent = content; // Identify the requested resource path String path = getRelativePath(request); if (debug > 0) { if (serveContent) log("DefaultServlet.serveResource: Serving resource '" + path + "' headers and data"); else log("DefaultServlet.serveResource: Serving resource '" + path + "' headers only"); } CacheEntry cacheEntry = resources.lookupCache(path); if (!cacheEntry.exists) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } else { // We're included // SRV.9.3 says we must throw a FNFE throw new FileNotFoundException( sm.getString("defaultServlet.missingResource", requestUri)); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } // If the resource is not a collection, and the resource path // ends with "/" or "\", return NOT FOUND if (cacheEntry.context == null) { if (path.endsWith("/") || (path.endsWith("\\"))) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } } boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST; // Check if the conditions specified in the optional If headers are // satisfied. if (cacheEntry.context == null) { // Checking If headers boolean included = (request.getAttribute( RequestDispatcher.INCLUDE_CONTEXT_PATH) != null); if (!included && !isError && !checkIfHeaders(request, response, cacheEntry.attributes)) { return; } } // Find content type. String contentType = cacheEntry.attributes.getMimeType(); if (contentType == null) { contentType = getServletContext().getMimeType(cacheEntry.name); cacheEntry.attributes.setMimeType(contentType); } ArrayList<Range> ranges = null; long contentLength = -1L; if (cacheEntry.context != null) { // Skip directory listings if we have been configured to // suppress them if (!listings) { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); return; } contentType = "text/html;charset=UTF-8"; } else { if (!isError) { if (useAcceptRanges) { // Accept ranges header response.setHeader("Accept-Ranges", "bytes"); } // Parse range specifier ranges = parseRange(request, response, cacheEntry.attributes); // ETag header response.setHeader("ETag", cacheEntry.attributes.getETag()); // Last-Modified header response.setHeader("Last-Modified", cacheEntry.attributes.getLastModifiedHttp()); } // Get content length contentLength = cacheEntry.attributes.getContentLength(); // Special case for zero length files, which would cause a // (silent) ISE when setting the output buffer size if (contentLength == 0L) { serveContent = false; } } ServletOutputStream ostream = null; PrintWriter writer = null; if (serveContent) { // Trying to retrieve the servlet output stream try { ostream = response.getOutputStream(); } catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } } } // Check to see if a Filter, Valve of wrapper has written some content. // If it has, disable range requests and setting of a content length // since neither can be done reliably. ServletResponse r = response; long contentWritten = 0; while (r instanceof ServletResponseWrapper) { r = ((ServletResponseWrapper) r).getResponse(); } if (r instanceof ResponseFacade) { contentWritten = ((ResponseFacade) r).getContentWritten(); } if (contentWritten > 0) { ranges = FULL; } if ( (cacheEntry.context != null) || isError || ( ((ranges == null) || (ranges.isEmpty())) && (request.getHeader("Range") == null) ) || (ranges == FULL) ) { // Set the appropriate output headers if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if ((cacheEntry.resource != null) && (contentLength >= 0) && (!serveContent || ostream != null)) { if (debug > 0) log("DefaultServlet.serveFile: contentLength=" + contentLength); // Don't set a content length if something else has already // written to the response. if (contentWritten == 0) { if (contentLength < Integer.MAX_VALUE) { response.setContentLength((int) contentLength); } else { // Set the content-length as String to be able to use a // long response.setHeader("content-length", "" + contentLength); } } } InputStream renderResult = null; if (cacheEntry.context != null) { if (serveContent) { // Serve the directory browser renderResult = render(getPathPrefix(request), cacheEntry); } } // Copy the input stream to our output stream (if requested) if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, contentLength, null)) copy(cacheEntry, renderResult, ostream); } else { copy(cacheEntry, renderResult, writer); } } } else { if ((ranges == null) || (ranges.isEmpty())) return; // Partial content response. response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); if (ranges.size() == 1) { Range range = ranges.get(0); response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; if (length < Integer.MAX_VALUE) { response.setContentLength((int) length); } else { // Set the content-length as String to be able to use a long response.setHeader("content-length", "" + length); } if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, range.end - range.start + 1, range)) copy(cacheEntry, ostream, range); } else { // we should not get here throw new IllegalStateException(); } } } else { response.setContentType("multipart/byteranges; boundary=" + mimeSeparation); if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { copy(cacheEntry, ostream, ranges.iterator(), contentType); } else { // we should not get here throw new IllegalStateException(); } } } } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected Range parseContentRange(HttpServletRequest request, HttpServletResponse response) throws IOException { // Retrieving the content-range header (if any is specified String rangeHeader = request.getHeader("Content-Range"); if (rangeHeader == null) return null; // bytes is the only range unit supported if (!rangeHeader.startsWith("bytes")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } rangeHeader = rangeHeader.substring(6).trim(); int dashPos = rangeHeader.indexOf('-'); int slashPos = rangeHeader.indexOf('/'); if (dashPos == -1) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } if (slashPos == -1) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } Range range = new Range(); try { range.start = Long.parseLong(rangeHeader.substring(0, dashPos)); range.end = Long.parseLong(rangeHeader.substring(dashPos + 1, slashPos)); range.length = Long.parseLong (rangeHeader.substring(slashPos + 1, rangeHeader.length())); } catch (NumberFormatException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } if (!range.validate()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } return range; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected ArrayList<Range> parseRange(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) throws IOException { // Checking If-Range String headerValue = request.getHeader("If-Range"); if (headerValue != null) { long headerValueTime = (-1L); try { headerValueTime = request.getDateHeader("If-Range"); } catch (IllegalArgumentException e) { // Ignore } String eTag = resourceAttributes.getETag(); long lastModified = resourceAttributes.getLastModified(); if (headerValueTime == (-1L)) { // If the ETag the client gave does not match the entity // etag, then the entire entity is returned. if (!eTag.equals(headerValue.trim())) return FULL; } else { // If the timestamp of the entity the client got is older than // the last modification date of the entity, the entire entity // is returned. if (lastModified > (headerValueTime + 1000)) return FULL; } } long fileLength = resourceAttributes.getContentLength(); if (fileLength == 0) return null; // Retrieving the range header (if any is specified String rangeHeader = request.getHeader("Range"); if (rangeHeader == null) return null; // bytes is the only range unit supported (and I don't see the point // of adding new ones). if (!rangeHeader.startsWith("bytes")) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } rangeHeader = rangeHeader.substring(6); // Vector which will contain all the ranges which are successfully // parsed. ArrayList<Range> result = new ArrayList<Range>(); StringTokenizer commaTokenizer = new StringTokenizer(rangeHeader, ","); // Parsing the range list while (commaTokenizer.hasMoreTokens()) { String rangeDefinition = commaTokenizer.nextToken().trim(); Range currentRange = new Range(); currentRange.length = fileLength; int dashPos = rangeDefinition.indexOf('-'); if (dashPos == -1) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } if (dashPos == 0) { try { long offset = Long.parseLong(rangeDefinition); currentRange.start = fileLength + offset; currentRange.end = fileLength - 1; } catch (NumberFormatException e) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse .SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } } else { try { currentRange.start = Long.parseLong (rangeDefinition.substring(0, dashPos)); if (dashPos < rangeDefinition.length() - 1) currentRange.end = Long.parseLong (rangeDefinition.substring (dashPos + 1, rangeDefinition.length())); else currentRange.end = fileLength - 1; } catch (NumberFormatException e) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse .SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } } if (!currentRange.validate()) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } result.add(currentRange); } return result; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream render(String contextPath, CacheEntry cacheEntry) throws IOException, ServletException { InputStream xsltInputStream = findXsltInputStream(cacheEntry.context); if (xsltInputStream==null) { return renderHtml(contextPath, cacheEntry); } return renderXml(contextPath, cacheEntry, xsltInputStream); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream renderXml(String contextPath, CacheEntry cacheEntry, InputStream xsltInputStream) throws IOException, ServletException { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<listing "); sb.append(" contextPath='"); sb.append(contextPath); sb.append("'"); sb.append(" directory='"); sb.append(cacheEntry.name); sb.append("' "); sb.append(" hasParent='").append(!cacheEntry.name.equals("/")); sb.append("'>"); sb.append("<entries>"); try { // Render the directory entries within this directory NamingEnumeration<NameClassPair> enumeration = resources.list(cacheEntry.name); // rewriteUrl(contextPath) is expensive. cache result for later reuse String rewrittenContextPath = rewriteUrl(contextPath); while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String resourceName = ncPair.getName(); String trimmed = resourceName/*.substring(trim)*/; if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF") || trimmed.equalsIgnoreCase(localXsltFile)) continue; if ((cacheEntry.name + trimmed).equals(contextXsltFile)) continue; CacheEntry childCacheEntry = resources.lookupCache(cacheEntry.name + resourceName); if (!childCacheEntry.exists) { continue; } sb.append("<entry"); sb.append(" type='") .append((childCacheEntry.context != null)?"dir":"file") .append("'"); sb.append(" urlPath='") .append(rewrittenContextPath) .append(rewriteUrl(cacheEntry.name + resourceName)) .append((childCacheEntry.context != null)?"/":"") .append("'"); if (childCacheEntry.resource != null) { sb.append(" size='") .append(renderSize(childCacheEntry.attributes.getContentLength())) .append("'"); } sb.append(" date='") .append(childCacheEntry.attributes.getLastModifiedHttp()) .append("'"); sb.append(">"); sb.append(RequestUtil.filter(trimmed)); if (childCacheEntry.context != null) sb.append("/"); sb.append("</entry>"); } } catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); } sb.append("</entries>"); String readme = getReadme(cacheEntry.context); if (readme!=null) { sb.append("<readme><![CDATA["); sb.append(readme); sb.append("]]></readme>"); } sb.append("</listing>"); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Source xmlSource = new StreamSource(new StringReader(sb.toString())); Source xslSource = new StreamSource(xsltInputStream); Transformer transformer = tFactory.newTransformer(xslSource); ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8"); StreamResult out = new StreamResult(osWriter); transformer.transform(xmlSource, out); osWriter.flush(); return (new ByteArrayInputStream(stream.toByteArray())); } catch (TransformerException e) { throw new ServletException("XSL transformer error", e); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream renderHtml(String contextPath, CacheEntry cacheEntry) throws IOException, ServletException { String name = cacheEntry.name; // Prepare a writer to a buffered area ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8"); PrintWriter writer = new PrintWriter(osWriter); StringBuilder sb = new StringBuilder(); // rewriteUrl(contextPath) is expensive. cache result for later reuse String rewrittenContextPath = rewriteUrl(contextPath); // Render the page header sb.append("<html>\r\n"); sb.append("<head>\r\n"); sb.append("<title>"); sb.append(sm.getString("directory.title", name)); sb.append("</title>\r\n"); sb.append("<STYLE><!--"); sb.append(org.apache.catalina.util.TomcatCSS.TOMCAT_CSS); sb.append("--></STYLE> "); sb.append("</head>\r\n"); sb.append("<body>"); sb.append("<h1>"); sb.append(sm.getString("directory.title", name)); // Render the link to our parent (if required) String parentDirectory = name; if (parentDirectory.endsWith("/")) { parentDirectory = parentDirectory.substring(0, parentDirectory.length() - 1); } int slash = parentDirectory.lastIndexOf('/'); if (slash >= 0) { String parent = name.substring(0, slash); sb.append(" - <a href=\""); sb.append(rewrittenContextPath); if (parent.equals("")) parent = "/"; sb.append(rewriteUrl(parent)); if (!parent.endsWith("/")) sb.append("/"); sb.append("\">"); sb.append("<b>"); sb.append(sm.getString("directory.parent", parent)); sb.append("</b>"); sb.append("</a>"); } sb.append("</h1>"); sb.append("<HR size=\"1\" noshade=\"noshade\">"); sb.append("<table width=\"100%\" cellspacing=\"0\"" + " cellpadding=\"5\" align=\"center\">\r\n"); // Render the column headings sb.append("<tr>\r\n"); sb.append("<td align=\"left\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.filename")); sb.append("</strong></font></td>\r\n"); sb.append("<td align=\"center\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.size")); sb.append("</strong></font></td>\r\n"); sb.append("<td align=\"right\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.lastModified")); sb.append("</strong></font></td>\r\n"); sb.append("</tr>"); try { // Render the directory entries within this directory NamingEnumeration<NameClassPair> enumeration = resources.list(cacheEntry.name); boolean shade = false; while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String resourceName = ncPair.getName(); String trimmed = resourceName/*.substring(trim)*/; if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF")) continue; CacheEntry childCacheEntry = resources.lookupCache(cacheEntry.name + resourceName); if (!childCacheEntry.exists) { continue; } sb.append("<tr"); if (shade) sb.append(" bgcolor=\"#eeeeee\""); sb.append(">\r\n"); shade = !shade; sb.append("<td align=\"left\">&nbsp;&nbsp;\r\n"); sb.append("<a href=\""); sb.append(rewrittenContextPath); resourceName = rewriteUrl(name + resourceName); sb.append(resourceName); if (childCacheEntry.context != null) sb.append("/"); sb.append("\"><tt>"); sb.append(RequestUtil.filter(trimmed)); if (childCacheEntry.context != null) sb.append("/"); sb.append("</tt></a></td>\r\n"); sb.append("<td align=\"right\"><tt>"); if (childCacheEntry.context != null) sb.append("&nbsp;"); else sb.append(renderSize(childCacheEntry.attributes.getContentLength())); sb.append("</tt></td>\r\n"); sb.append("<td align=\"right\"><tt>"); sb.append(childCacheEntry.attributes.getLastModifiedHttp()); sb.append("</tt></td>\r\n"); sb.append("</tr>\r\n"); } } catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); } // Render the page footer sb.append("</table>\r\n"); sb.append("<HR size=\"1\" noshade=\"noshade\">"); String readme = getReadme(cacheEntry.context); if (readme!=null) { sb.append(readme); sb.append("<HR size=\"1\" noshade=\"noshade\">"); } sb.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>"); sb.append("</body>\r\n"); sb.append("</html>\r\n"); // Return an input stream to the underlying bytes writer.write(sb.toString()); writer.flush(); return (new ByteArrayInputStream(stream.toByteArray())); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected String getReadme(DirContext directory) throws IOException { if (readmeFile != null) { try { Object obj = directory.lookup(readmeFile); if ((obj != null) && (obj instanceof Resource)) { StringWriter buffer = new StringWriter(); InputStream is = ((Resource) obj).streamContent(); copyRange(new InputStreamReader(is), new PrintWriter(buffer)); return buffer.toString(); } } catch (NamingException e) { if (debug > 10) log("readme '" + readmeFile + "' not found", e); return null; } } return null; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream findXsltInputStream(DirContext directory) throws IOException { if (localXsltFile != null) { try { Object obj = directory.lookup(localXsltFile); if ((obj != null) && (obj instanceof Resource)) { InputStream is = ((Resource) obj).streamContent(); if (is != null) return is; } } catch (NamingException e) { if (debug > 10) log("localXsltFile '" + localXsltFile + "' not found", e); } } if (contextXsltFile != null) { InputStream is = getServletContext().getResourceAsStream(contextXsltFile); if (is != null) return is; if (debug > 10) log("contextXsltFile '" + contextXsltFile + "' not found"); } /* Open and read in file in one fell swoop to reduce chance * chance of leaving handle open. */ if (globalXsltFile!=null) { FileInputStream fis = null; try { File f = new File(globalXsltFile); if (f.exists()){ fis =new FileInputStream(f); byte b[] = new byte[(int)f.length()]; /* danger! */ fis.read(b); return new ByteArrayInputStream(b); } } finally { if (fis!=null) fis.close(); } } return null; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected boolean checkIfMatch(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) throws IOException { String eTag = resourceAttributes.getETag(); String headerValue = request.getHeader("If-Match"); if (headerValue != null) { if (headerValue.indexOf('*') == -1) { StringTokenizer commaTokenizer = new StringTokenizer (headerValue, ","); boolean conditionSatisfied = false; while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) { String currentToken = commaTokenizer.nextToken(); if (currentToken.trim().equals(eTag)) conditionSatisfied = true; } // If none of the given ETags match, 412 Precodition failed is // sent back if (!conditionSatisfied) { response.sendError (HttpServletResponse.SC_PRECONDITION_FAILED); return false; } } } return true; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected boolean checkIfNoneMatch(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) throws IOException { String eTag = resourceAttributes.getETag(); String headerValue = request.getHeader("If-None-Match"); if (headerValue != null) { boolean conditionSatisfied = false; if (!headerValue.equals("*")) { StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ","); while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) { String currentToken = commaTokenizer.nextToken(); if (currentToken.trim().equals(eTag)) conditionSatisfied = true; } } else { conditionSatisfied = true; } if (conditionSatisfied) { // For GET and HEAD, we should respond with // 304 Not Modified. // For every other method, 412 Precondition Failed is sent // back. if ( ("GET".equals(request.getMethod())) || ("HEAD".equals(request.getMethod())) ) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); return false; } response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } } return true; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected boolean checkIfUnmodifiedSince(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) throws IOException { try { long lastModified = resourceAttributes.getLastModified(); long headerValue = request.getDateHeader("If-Unmodified-Since"); if (headerValue != -1) { if ( lastModified >= (headerValue + 1000)) { // The entity has not been modified since the date // specified by the client. This is not an error case. response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } } } catch(IllegalArgumentException illegalArgument) { return true; } return true; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void copy(CacheEntry cacheEntry, InputStream is, ServletOutputStream ostream) throws IOException { IOException exception = null; InputStream resourceInputStream = null; // Optimization: If the binary content has already been loaded, send // it directly if (cacheEntry.resource != null) { byte buffer[] = cacheEntry.resource.getContent(); if (buffer != null) { ostream.write(buffer, 0, buffer.length); return; } resourceInputStream = cacheEntry.resource.streamContent(); } else { resourceInputStream = is; } InputStream istream = new BufferedInputStream (resourceInputStream, input); // Copy the input stream to the output stream exception = copyRange(istream, ostream); // Clean up the input stream istream.close(); // Rethrow any exception that has occurred if (exception != null) throw exception; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void copy(CacheEntry cacheEntry, InputStream is, PrintWriter writer) throws IOException { IOException exception = null; InputStream resourceInputStream = null; if (cacheEntry.resource != null) { resourceInputStream = cacheEntry.resource.streamContent(); } else { resourceInputStream = is; } Reader reader; if (fileEncoding == null) { reader = new InputStreamReader(resourceInputStream); } else { reader = new InputStreamReader(resourceInputStream, fileEncoding); } // Copy the input stream to the output stream exception = copyRange(reader, writer); // Clean up the reader reader.close(); // Rethrow any exception that has occurred if (exception != null) throw exception; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void copy(CacheEntry cacheEntry, ServletOutputStream ostream, Range range) throws IOException { IOException exception = null; InputStream resourceInputStream = cacheEntry.resource.streamContent(); InputStream istream = new BufferedInputStream(resourceInputStream, input); exception = copyRange(istream, ostream, range.start, range.end); // Clean up the input stream istream.close(); // Rethrow any exception that has occurred if (exception != null) throw exception; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void copy(CacheEntry cacheEntry, ServletOutputStream ostream, Iterator<Range> ranges, String contentType) throws IOException { IOException exception = null; while ( (exception == null) && (ranges.hasNext()) ) { InputStream resourceInputStream = cacheEntry.resource.streamContent(); InputStream istream = new BufferedInputStream(resourceInputStream, input); Range currentRange = ranges.next(); // Writing MIME header. ostream.println(); ostream.println("--" + mimeSeparation); if (contentType != null) ostream.println("Content-Type: " + contentType); ostream.println("Content-Range: bytes " + currentRange.start + "-" + currentRange.end + "/" + currentRange.length); ostream.println(); // Printing content exception = copyRange(istream, ostream, currentRange.start, currentRange.end); istream.close(); } ostream.println(); ostream.print("--" + mimeSeparation + "--"); // Rethrow any exception that has occurred if (exception != null) throw exception; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final String path = getRelativePath(req); // Block access to special subdirectories. // DefaultServlet assumes it services resources from the root of the web app // and doesn't add any special path protection // WebdavServlet remounts the webapp under a new path, so this check is // necessary on all methods (including GET). if (isSpecialPath(path)) { resp.sendError(WebdavStatus.SC_NOT_FOUND); return; } final String method = req.getMethod(); if (debug > 0) { log("[" + method + "] " + path); } if (method.equals(METHOD_PROPFIND)) { doPropfind(req, resp); } else if (method.equals(METHOD_PROPPATCH)) { doProppatch(req, resp); } else if (method.equals(METHOD_MKCOL)) { doMkcol(req, resp); } else if (method.equals(METHOD_COPY)) { doCopy(req, resp); } else if (method.equals(METHOD_MOVE)) { doMove(req, resp); } else if (method.equals(METHOD_LOCK)) { doLock(req, resp); } else if (method.equals(METHOD_UNLOCK)) { doUnlock(req, resp); } else { // DefaultServlet processing super.service(req, resp); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected boolean checkIfHeaders(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) throws IOException { if (!super.checkIfHeaders(request, response, resourceAttributes)) return false; // TODO : Checking the WebDAV If header return true; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("DAV", "1,2"); StringBuilder methodsAllowed = determineMethodsAllowed(resources, req); resp.addHeader("Allow", methodsAllowed.toString()); resp.addHeader("MS-Author-Via", "DAV"); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doPropfind(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (!listings) { // Get allowed methods StringBuilder methodsAllowed = determineMethodsAllowed(resources, req); resp.addHeader("Allow", methodsAllowed.toString()); resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED); return; } String path = getRelativePath(req); if (path.endsWith("/")) path = path.substring(0, path.length() - 1); // Properties which are to be displayed. Vector<String> properties = null; // Propfind depth int depth = maxDepth; // Propfind type int type = FIND_ALL_PROP; String depthStr = req.getHeader("Depth"); if (depthStr == null) { depth = maxDepth; } else { if (depthStr.equals("0")) { depth = 0; } else if (depthStr.equals("1")) { depth = 1; } else if (depthStr.equals("infinity")) { depth = maxDepth; } } Node propNode = null; if (req.getContentLength() > 0) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse (new InputSource(req.getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); NodeList childList = rootElement.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: if (currentNode.getNodeName().endsWith("prop")) { type = FIND_BY_PROPERTY; propNode = currentNode; } if (currentNode.getNodeName().endsWith("propname")) { type = FIND_PROPERTY_NAMES; } if (currentNode.getNodeName().endsWith("allprop")) { type = FIND_ALL_PROP; } break; } } } catch (SAXException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); } catch (IOException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); } } if (type == FIND_BY_PROPERTY) { properties = new Vector<String>(); // propNode must be non-null if type == FIND_BY_PROPERTY @SuppressWarnings("null") NodeList childList = propNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String nodeName = currentNode.getNodeName(); String propertyName = null; if (nodeName.indexOf(':') != -1) { propertyName = nodeName.substring (nodeName.indexOf(':') + 1); } else { propertyName = nodeName; } // href is a live property which is handled differently properties.addElement(propertyName); break; } } } boolean exists = true; Object object = null; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } } if (!exists) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, path); return; } resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); if (depth == 0) { parseProperties(req, generatedXML, path, type, properties); } else { // The stack always contains the object of the current level Stack<String> stack = new Stack<String>(); stack.push(path); // Stack of the objects one level below Stack<String> stackBelow = new Stack<String>(); while ((!stack.isEmpty()) && (depth >= 0)) { String currentPath = stack.pop(); parseProperties(req, generatedXML, currentPath, type, properties); try { object = resources.lookup(currentPath); } catch (NamingException e) { continue; } if ((object instanceof DirContext) && (depth > 0)) { try { NamingEnumeration<NameClassPair> enumeration = resources.list(currentPath); while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String newPath = currentPath; if (!(newPath.endsWith("/"))) newPath += "/"; newPath += ncPair.getName(); stackBelow.push(newPath); } } catch (NamingException e) { resp.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } // Displaying the lock-null resources present in that // collection String lockPath = currentPath; if (lockPath.endsWith("/")) lockPath = lockPath.substring(0, lockPath.length() - 1); Vector<String> currentLockNullResources = lockNullResources.get(lockPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); } } } if (stack.isEmpty()) { depth--; stack = stackBelow; stackBelow = new Stack<String>(); } generatedXML.sendData(); } } generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doProppatch(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doMkcol(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } String path = getRelativePath(req); boolean exists = true; try { resources.lookup(path); } catch (NamingException e) { exists = false; } // Can't create a collection if a resource already exists at the given // path if (exists) { // Get allowed methods StringBuilder methodsAllowed = determineMethodsAllowed(resources, req); resp.addHeader("Allow", methodsAllowed.toString()); resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED); return; } if (req.getContentLength() > 0) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { // Document document = documentBuilder.parse(new InputSource(req.getInputStream())); // TODO : Process this request body resp.sendError(WebdavStatus.SC_NOT_IMPLEMENTED); return; } catch(SAXException saxe) { // Parse error - assume invalid content resp.sendError(WebdavStatus.SC_UNSUPPORTED_MEDIA_TYPE); return; } } boolean result = true; try { resources.createSubcontext(path); } catch (NamingException e) { result = false; } if (!result) { resp.sendError(WebdavStatus.SC_CONFLICT, WebdavStatus.getStatusText (WebdavStatus.SC_CONFLICT)); } else { resp.setStatus(WebdavStatus.SC_CREATED); // Removing any lock-null resource which would be present lockNullResources.remove(path); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } deleteResource(req, resp); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } super.doPut(req, resp); String path = getRelativePath(req); // Removing any lock-null resource which would be present lockNullResources.remove(path); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doCopy(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } copyResource(req, resp); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doMove(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } String path = getRelativePath(req); if (copyResource(req, resp)) { deleteResource(path, req, resp, false); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doLock(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } LockInfo lock = new LockInfo(); // Parsing lock request // Parsing depth header String depthStr = req.getHeader("Depth"); if (depthStr == null) { lock.depth = maxDepth; } else { if (depthStr.equals("0")) { lock.depth = 0; } else { lock.depth = maxDepth; } } // Parsing timeout header int lockDuration = DEFAULT_TIMEOUT; String lockDurationStr = req.getHeader("Timeout"); if (lockDurationStr == null) { lockDuration = DEFAULT_TIMEOUT; } else { int commaPos = lockDurationStr.indexOf(","); // If multiple timeouts, just use the first if (commaPos != -1) { lockDurationStr = lockDurationStr.substring(0,commaPos); } if (lockDurationStr.startsWith("Second-")) { lockDuration = (new Integer(lockDurationStr.substring(7))).intValue(); } else { if (lockDurationStr.equalsIgnoreCase("infinity")) { lockDuration = MAX_TIMEOUT; } else { try { lockDuration = (new Integer(lockDurationStr)).intValue(); } catch (NumberFormatException e) { lockDuration = MAX_TIMEOUT; } } } if (lockDuration == 0) { lockDuration = DEFAULT_TIMEOUT; } if (lockDuration > MAX_TIMEOUT) { lockDuration = MAX_TIMEOUT; } } lock.expiresAt = System.currentTimeMillis() + (lockDuration * 1000); int lockRequestType = LOCK_CREATION; Node lockInfoNode = null; DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse(new InputSource (req.getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); lockInfoNode = rootElement; } catch (IOException e) { lockRequestType = LOCK_REFRESH; } catch (SAXException e) { lockRequestType = LOCK_REFRESH; } if (lockInfoNode != null) { // Reading lock information NodeList childList = lockInfoNode.getChildNodes(); StringWriter strWriter = null; DOMWriter domWriter = null; Node lockScopeNode = null; Node lockTypeNode = null; Node lockOwnerNode = null; for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String nodeName = currentNode.getNodeName(); if (nodeName.endsWith("lockscope")) { lockScopeNode = currentNode; } if (nodeName.endsWith("locktype")) { lockTypeNode = currentNode; } if (nodeName.endsWith("owner")) { lockOwnerNode = currentNode; } break; } } if (lockScopeNode != null) { childList = lockScopeNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String tempScope = currentNode.getNodeName(); if (tempScope.indexOf(':') != -1) { lock.scope = tempScope.substring (tempScope.indexOf(':') + 1); } else { lock.scope = tempScope; } break; } } if (lock.scope == null) { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } } else { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } if (lockTypeNode != null) { childList = lockTypeNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String tempType = currentNode.getNodeName(); if (tempType.indexOf(':') != -1) { lock.type = tempType.substring(tempType.indexOf(':') + 1); } else { lock.type = tempType; } break; } } if (lock.type == null) { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } } else { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } if (lockOwnerNode != null) { childList = lockOwnerNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: lock.owner += currentNode.getNodeValue(); break; case Node.ELEMENT_NODE: strWriter = new StringWriter(); domWriter = new DOMWriter(strWriter, true); domWriter.setQualifiedNames(false); domWriter.print(currentNode); lock.owner += strWriter.toString(); break; } } if (lock.owner == null) { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } } else { lock.owner = ""; } } String path = getRelativePath(req); lock.path = path; boolean exists = true; Object object = null; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; } Enumeration<LockInfo> locksList = null; if (lockRequestType == LOCK_CREATION) { // Generating lock id String lockTokenStr = req.getServletPath() + "-" + lock.type + "-" + lock.scope + "-" + req.getUserPrincipal() + "-" + lock.depth + "-" + lock.owner + "-" + lock.tokens + "-" + lock.expiresAt + "-" + System.currentTimeMillis() + "-" + secret; String lockToken = md5Encoder.encode(md5Helper.digest( lockTokenStr.getBytes(B2CConverter.ISO_8859_1))); if ( (exists) && (object instanceof DirContext) && (lock.depth == maxDepth) ) { // Locking a collection (and all its member resources) // Checking if a child resource of this collection is // already locked Vector<String> lockPaths = new Vector<String>(); locksList = collectionLocks.elements(); while (locksList.hasMoreElements()) { LockInfo currentLock = locksList.nextElement(); if (currentLock.hasExpired()) { resourceLocks.remove(currentLock.path); continue; } if ( (currentLock.path.startsWith(lock.path)) && ((currentLock.isExclusive()) || (lock.isExclusive())) ) { // A child collection of this collection is locked lockPaths.addElement(currentLock.path); } } locksList = resourceLocks.elements(); while (locksList.hasMoreElements()) { LockInfo currentLock = locksList.nextElement(); if (currentLock.hasExpired()) { resourceLocks.remove(currentLock.path); continue; } if ( (currentLock.path.startsWith(lock.path)) && ((currentLock.isExclusive()) || (lock.isExclusive())) ) { // A child resource of this collection is locked lockPaths.addElement(currentLock.path); } } if (!lockPaths.isEmpty()) { // One of the child paths was locked // We generate a multistatus error report Enumeration<String> lockPathsList = lockPaths.elements(); resp.setStatus(WebdavStatus.SC_CONFLICT); XMLWriter generatedXML = new XMLWriter(); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); while (lockPathsList.hasMoreElements()) { generatedXML.writeElement("D", "response", XMLWriter.OPENING); generatedXML.writeElement("D", "href", XMLWriter.OPENING); generatedXML.writeText(lockPathsList.nextElement()); generatedXML.writeElement("D", "href", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML .writeText("HTTP/1.1 " + WebdavStatus.SC_LOCKED + " " + WebdavStatus .getStatusText(WebdavStatus.SC_LOCKED)); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "response", XMLWriter.CLOSING); } generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); Writer writer = resp.getWriter(); writer.write(generatedXML.toString()); writer.close(); return; } boolean addLock = true; // Checking if there is already a shared lock on this path locksList = collectionLocks.elements(); while (locksList.hasMoreElements()) { LockInfo currentLock = locksList.nextElement(); if (currentLock.path.equals(lock.path)) { if (currentLock.isExclusive()) { resp.sendError(WebdavStatus.SC_LOCKED); return; } else { if (lock.isExclusive()) { resp.sendError(WebdavStatus.SC_LOCKED); return; } } currentLock.tokens.addElement(lockToken); lock = currentLock; addLock = false; } } if (addLock) { lock.tokens.addElement(lockToken); collectionLocks.addElement(lock); } } else { // Locking a single resource // Retrieving an already existing lock on that resource LockInfo presentLock = resourceLocks.get(lock.path); if (presentLock != null) { if ((presentLock.isExclusive()) || (lock.isExclusive())) { // If either lock is exclusive, the lock can't be // granted resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED); return; } else { presentLock.tokens.addElement(lockToken); lock = presentLock; } } else { lock.tokens.addElement(lockToken); resourceLocks.put(lock.path, lock); // Checking if a resource exists at this path exists = true; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; } if (!exists) { // "Creating" a lock-null resource int slash = lock.path.lastIndexOf('/'); String parentPath = lock.path.substring(0, slash); Vector<String> lockNulls = lockNullResources.get(parentPath); if (lockNulls == null) { lockNulls = new Vector<String>(); lockNullResources.put(parentPath, lockNulls); } lockNulls.addElement(lock.path); } // Add the Lock-Token header as by RFC 2518 8.10.1 // - only do this for newly created locks resp.addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">"); } } } if (lockRequestType == LOCK_REFRESH) { String ifHeader = req.getHeader("If"); if (ifHeader == null) ifHeader = ""; // Checking resource locks LockInfo toRenew = resourceLocks.get(path); Enumeration<String> tokenList = null; if (toRenew != null) { // At least one of the tokens of the locks must have been given tokenList = toRenew.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (ifHeader.indexOf(token) != -1) { toRenew.expiresAt = lock.expiresAt; lock = toRenew; } } } // Checking inheritable collection locks Enumeration<LockInfo> collectionLocksList = collectionLocks.elements(); while (collectionLocksList.hasMoreElements()) { toRenew = collectionLocksList.nextElement(); if (path.equals(toRenew.path)) { tokenList = toRenew.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (ifHeader.indexOf(token) != -1) { toRenew.expiresAt = lock.expiresAt; lock = toRenew; } } } } } // Set the status, then generate the XML response containing // the lock information XMLWriter generatedXML = new XMLWriter(); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "prop", XMLWriter.OPENING); generatedXML.writeElement("D", "lockdiscovery", XMLWriter.OPENING); lock.toXML(generatedXML); generatedXML.writeElement("D", "lockdiscovery", XMLWriter.CLOSING); generatedXML.writeElement("D", "prop", XMLWriter.CLOSING); resp.setStatus(WebdavStatus.SC_OK); resp.setContentType("text/xml; charset=UTF-8"); Writer writer = resp.getWriter(); writer.write(generatedXML.toString()); writer.close(); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doUnlock(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } String path = getRelativePath(req); String lockTokenHeader = req.getHeader("Lock-Token"); if (lockTokenHeader == null) lockTokenHeader = ""; // Checking resource locks LockInfo lock = resourceLocks.get(path); Enumeration<String> tokenList = null; if (lock != null) { // At least one of the tokens of the locks must have been given tokenList = lock.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (lockTokenHeader.indexOf(token) != -1) { lock.tokens.removeElement(token); } } if (lock.tokens.isEmpty()) { resourceLocks.remove(path); // Removing any lock-null resource which would be present lockNullResources.remove(path); } } // Checking inheritable collection locks Enumeration<LockInfo> collectionLocksList = collectionLocks.elements(); while (collectionLocksList.hasMoreElements()) { lock = collectionLocksList.nextElement(); if (path.equals(lock.path)) { tokenList = lock.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (lockTokenHeader.indexOf(token) != -1) { lock.tokens.removeElement(token); break; } } if (lock.tokens.isEmpty()) { collectionLocks.removeElement(lock); // Removing any lock-null resource which would be present lockNullResources.remove(path); } } } resp.setStatus(WebdavStatus.SC_NO_CONTENT); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
private boolean copyResource(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Parsing destination header String destinationPath = req.getHeader("Destination"); if (destinationPath == null) { resp.sendError(WebdavStatus.SC_BAD_REQUEST); return false; } // Remove url encoding from destination destinationPath = org.apache.catalina.util.RequestUtil.URLDecode( destinationPath, "UTF8"); int protocolIndex = destinationPath.indexOf("://"); if (protocolIndex >= 0) { // if the Destination URL contains the protocol, we can safely // trim everything upto the first "/" character after "://" int firstSeparator = destinationPath.indexOf("/", protocolIndex + 4); if (firstSeparator < 0) { destinationPath = "/"; } else { destinationPath = destinationPath.substring(firstSeparator); } } else { String hostName = req.getServerName(); if ((hostName != null) && (destinationPath.startsWith(hostName))) { destinationPath = destinationPath.substring(hostName.length()); } int portIndex = destinationPath.indexOf(":"); if (portIndex >= 0) { destinationPath = destinationPath.substring(portIndex); } if (destinationPath.startsWith(":")) { int firstSeparator = destinationPath.indexOf("/"); if (firstSeparator < 0) { destinationPath = "/"; } else { destinationPath = destinationPath.substring(firstSeparator); } } } // Normalise destination path (remove '.' and '..') destinationPath = RequestUtil.normalize(destinationPath); String contextPath = req.getContextPath(); if ((contextPath != null) && (destinationPath.startsWith(contextPath))) { destinationPath = destinationPath.substring(contextPath.length()); } String pathInfo = req.getPathInfo(); if (pathInfo != null) { String servletPath = req.getServletPath(); if ((servletPath != null) && (destinationPath.startsWith(servletPath))) { destinationPath = destinationPath .substring(servletPath.length()); } } if (debug > 0) log("Dest path :" + destinationPath); // Check destination path to protect special subdirectories if (isSpecialPath(destinationPath)) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return false; } String path = getRelativePath(req); if (destinationPath.equals(path)) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return false; } // Parsing overwrite header boolean overwrite = true; String overwriteHeader = req.getHeader("Overwrite"); if (overwriteHeader != null) { if (overwriteHeader.equalsIgnoreCase("T")) { overwrite = true; } else { overwrite = false; } } // Overwriting the destination boolean exists = true; try { resources.lookup(destinationPath); } catch (NamingException e) { exists = false; } if (overwrite) { // Delete destination resource, if it exists if (exists) { if (!deleteResource(destinationPath, req, resp, true)) { return false; } } else { resp.setStatus(WebdavStatus.SC_CREATED); } } else { // If the destination exists, then it's a conflict if (exists) { resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED); return false; } } // Copying source to destination Hashtable<String,Integer> errorList = new Hashtable<String,Integer>(); boolean result = copyResource(resources, errorList, path, destinationPath); if ((!result) || (!errorList.isEmpty())) { if (errorList.size() == 1) { resp.sendError(errorList.elements().nextElement().intValue()); } else { sendReport(req, resp, errorList); } return false; } // Copy was successful if (exists) { resp.setStatus(WebdavStatus.SC_NO_CONTENT); } else { resp.setStatus(WebdavStatus.SC_CREATED); } // Removing any lock-null resource which would be present at // the destination path lockNullResources.remove(destinationPath); return true; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
private boolean deleteResource(HttpServletRequest req, HttpServletResponse resp) throws IOException { String path = getRelativePath(req); return deleteResource(path, req, resp, true); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
private boolean deleteResource(String path, HttpServletRequest req, HttpServletResponse resp, boolean setStatus) throws IOException { String ifHeader = req.getHeader("If"); if (ifHeader == null) ifHeader = ""; String lockTokenHeader = req.getHeader("Lock-Token"); if (lockTokenHeader == null) lockTokenHeader = ""; if (isLocked(path, ifHeader + lockTokenHeader)) { resp.sendError(WebdavStatus.SC_LOCKED); return false; } boolean exists = true; Object object = null; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; } if (!exists) { resp.sendError(WebdavStatus.SC_NOT_FOUND); return false; } boolean collection = (object instanceof DirContext); if (!collection) { try { resources.unbind(path); } catch (NamingException e) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); return false; } } else { Hashtable<String,Integer> errorList = new Hashtable<String,Integer>(); deleteCollection(req, resources, path, errorList); try { resources.unbind(path); } catch (NamingException e) { errorList.put(path, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); } if (!errorList.isEmpty()) { sendReport(req, resp, errorList); return false; } } if (setStatus) { resp.setStatus(WebdavStatus.SC_NO_CONTENT); } return true; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
private void sendReport(HttpServletRequest req, HttpServletResponse resp, Hashtable<String,Integer> errorList) throws IOException { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); String absoluteUri = req.getRequestURI(); String relativePath = getRelativePath(req); XMLWriter generatedXML = new XMLWriter(); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); Enumeration<String> pathList = errorList.keys(); while (pathList.hasMoreElements()) { String errorPath = pathList.nextElement(); int errorCode = errorList.get(errorPath).intValue(); generatedXML.writeElement("D", "response", XMLWriter.OPENING); generatedXML.writeElement("D", "href", XMLWriter.OPENING); String toAppend = errorPath.substring(relativePath.length()); if (!toAppend.startsWith("/")) toAppend = "/" + toAppend; generatedXML.writeText(absoluteUri + toAppend); generatedXML.writeElement("D", "href", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML.writeText("HTTP/1.1 " + errorCode + " " + WebdavStatus.getStatusText(errorCode)); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "response", XMLWriter.CLOSING); } generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); Writer writer = resp.getWriter(); writer.write(generatedXML.toString()); writer.close(); }
// in java/org/apache/catalina/servlets/CGIServlet.java
protected void printServletEnvironment(ServletOutputStream out, HttpServletRequest req, HttpServletResponse res) throws IOException { // Document the properties from ServletRequest out.println("<h1>ServletRequest Properties</h1>"); out.println("<ul>"); Enumeration<String> attrs = req.getAttributeNames(); while (attrs.hasMoreElements()) { String attr = attrs.nextElement(); out.println("<li><b>attribute</b> " + attr + " = " + req.getAttribute(attr)); } out.println("<li><b>characterEncoding</b> = " + req.getCharacterEncoding()); out.println("<li><b>contentLength</b> = " + req.getContentLength()); out.println("<li><b>contentType</b> = " + req.getContentType()); Enumeration<Locale> locales = req.getLocales(); while (locales.hasMoreElements()) { Locale locale = locales.nextElement(); out.println("<li><b>locale</b> = " + locale); } Enumeration<String> params = req.getParameterNames(); while (params.hasMoreElements()) { String param = params.nextElement(); String values[] = req.getParameterValues(param); for (int i = 0; i < values.length; i++) out.println("<li><b>parameter</b> " + param + " = " + values[i]); } out.println("<li><b>protocol</b> = " + req.getProtocol()); out.println("<li><b>remoteAddr</b> = " + req.getRemoteAddr()); out.println("<li><b>remoteHost</b> = " + req.getRemoteHost()); out.println("<li><b>scheme</b> = " + req.getScheme()); out.println("<li><b>secure</b> = " + req.isSecure()); out.println("<li><b>serverName</b> = " + req.getServerName()); out.println("<li><b>serverPort</b> = " + req.getServerPort()); out.println("</ul>"); out.println("<hr>"); // Document the properties from HttpServletRequest out.println("<h1>HttpServletRequest Properties</h1>"); out.println("<ul>"); out.println("<li><b>authType</b> = " + req.getAuthType()); out.println("<li><b>contextPath</b> = " + req.getContextPath()); Cookie cookies[] = req.getCookies(); if (cookies!=null) { for (int i = 0; i < cookies.length; i++) out.println("<li><b>cookie</b> " + cookies[i].getName() +" = " +cookies[i].getValue()); } Enumeration<String> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String header = headers.nextElement(); out.println("<li><b>header</b> " + header + " = " + req.getHeader(header)); } out.println("<li><b>method</b> = " + req.getMethod()); out.println("<li><a name=\"pathInfo\"><b>pathInfo</b></a> = " + req.getPathInfo()); out.println("<li><b>pathTranslated</b> = " + req.getPathTranslated()); out.println("<li><b>queryString</b> = " + req.getQueryString()); out.println("<li><b>remoteUser</b> = " + req.getRemoteUser()); out.println("<li><b>requestedSessionId</b> = " + req.getRequestedSessionId()); out.println("<li><b>requestedSessionIdFromCookie</b> = " + req.isRequestedSessionIdFromCookie()); out.println("<li><b>requestedSessionIdFromURL</b> = " + req.isRequestedSessionIdFromURL()); out.println("<li><b>requestedSessionIdValid</b> = " + req.isRequestedSessionIdValid()); out.println("<li><b>requestURI</b> = " + req.getRequestURI()); out.println("<li><b>servletPath</b> = " + req.getServletPath()); out.println("<li><b>userPrincipal</b> = " + req.getUserPrincipal()); out.println("</ul>"); out.println("<hr>"); // Document the servlet request attributes out.println("<h1>ServletRequest Attributes</h1>"); out.println("<ul>"); attrs = req.getAttributeNames(); while (attrs.hasMoreElements()) { String attr = attrs.nextElement(); out.println("<li><b>" + attr + "</b> = " + req.getAttribute(attr)); } out.println("</ul>"); out.println("<hr>"); // Process the current session (if there is one) HttpSession session = req.getSession(false); if (session != null) { // Document the session properties out.println("<h1>HttpSession Properties</h1>"); out.println("<ul>"); out.println("<li><b>id</b> = " + session.getId()); out.println("<li><b>creationTime</b> = " + new Date(session.getCreationTime())); out.println("<li><b>lastAccessedTime</b> = " + new Date(session.getLastAccessedTime())); out.println("<li><b>maxInactiveInterval</b> = " + session.getMaxInactiveInterval()); out.println("</ul>"); out.println("<hr>"); // Document the session attributes out.println("<h1>HttpSession Attributes</h1>"); out.println("<ul>"); attrs = session.getAttributeNames(); while (attrs.hasMoreElements()) { String attr = attrs.nextElement(); out.println("<li><b>" + attr + "</b> = " + session.getAttribute(attr)); } out.println("</ul>"); out.println("<hr>"); } // Document the servlet configuration properties out.println("<h1>ServletConfig Properties</h1>"); out.println("<ul>"); out.println("<li><b>servletName</b> = " + getServletConfig().getServletName()); out.println("</ul>"); out.println("<hr>"); // Document the servlet configuration initialization parameters out.println("<h1>ServletConfig Initialization Parameters</h1>"); out.println("<ul>"); params = getServletConfig().getInitParameterNames(); while (params.hasMoreElements()) { String param = params.nextElement(); String value = getServletConfig().getInitParameter(param); out.println("<li><b>" + param + "</b> = " + value); } out.println("</ul>"); out.println("<hr>"); // Document the servlet context properties out.println("<h1>ServletContext Properties</h1>"); out.println("<ul>"); out.println("<li><b>majorVersion</b> = " + getServletContext().getMajorVersion()); out.println("<li><b>minorVersion</b> = " + getServletContext().getMinorVersion()); out.println("<li><b>realPath('/')</b> = " + getServletContext().getRealPath("/")); out.println("<li><b>serverInfo</b> = " + getServletContext().getServerInfo()); out.println("</ul>"); out.println("<hr>"); // Document the servlet context initialization parameters out.println("<h1>ServletContext Initialization Parameters</h1>"); out.println("<ul>"); params = getServletContext().getInitParameterNames(); while (params.hasMoreElements()) { String param = params.nextElement(); String value = getServletContext().getInitParameter(param); out.println("<li><b>" + param + "</b> = " + value); } out.println("</ul>"); out.println("<hr>"); // Document the servlet context attributes out.println("<h1>ServletContext Attributes</h1>"); out.println("<ul>"); attrs = getServletContext().getAttributeNames(); while (attrs.hasMoreElements()) { String attr = attrs.nextElement(); out.println("<li><b>" + attr + "</b> = " + getServletContext().getAttribute(attr)); } out.println("</ul>"); out.println("<hr>"); }
// in java/org/apache/catalina/servlets/CGIServlet.java
Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doGet(req, res); }
// in java/org/apache/catalina/servlets/CGIServlet.java
Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { CGIEnvironment cgiEnv = new CGIEnvironment(req, getServletContext()); if (cgiEnv.isValid()) { CGIRunner cgi = new CGIRunner(cgiEnv.getCommand(), cgiEnv.getEnvironment(), cgiEnv.getWorkingDirectory(), cgiEnv.getParameters()); //if POST, we need to cgi.setInput //REMIND: how does this interact with Servlet API 2.3's Filters?! if ("POST".equals(req.getMethod())) { cgi.setInput(req.getInputStream()); } cgi.setResponse(res); cgi.run(); } if (!cgiEnv.isValid()) { res.setStatus(404); } if (debug >= 10) { ServletOutputStream out = res.getOutputStream(); out.println("<HTML><HEAD><TITLE>$Name$</TITLE></HEAD>"); out.println("<BODY>$Header$<p>"); if (cgiEnv.isValid()) { out.println(cgiEnv.toString()); } else { out.println("<H3>"); out.println("CGI script not found or not specified."); out.println("</H3>"); out.println("<H4>"); out.println("Check the <b>HttpServletRequest "); out.println("<a href=\"#pathInfo\">pathInfo</a></b> "); out.println("property to see if it is what you meant "); out.println("it to be. You must specify an existant "); out.println("and executable file as part of the "); out.println("path-info."); out.println("</H4>"); out.println("<H4>"); out.println("For a good discussion of how CGI scripts "); out.println("work and what their environment variables "); out.println("mean, please visit the <a "); out.println("href=\"http://cgi-spec.golux.com\">CGI "); out.println("Specification page</a>."); out.println("</H4>"); } printServletEnvironment(out, req, res); out.println("</BODY></HTML>"); } }
// in java/org/apache/catalina/servlets/CGIServlet.java
protected boolean setCGIEnvironment(HttpServletRequest req) throws IOException { /* * This method is slightly ugly; c'est la vie. * "You cannot stop [ugliness], you can only hope to contain [it]" * (apologies to Marv Albert regarding MJ) */ Hashtable<String,String> envp = new Hashtable<String,String>(); // Add the shell environment variables (if any) envp.putAll(shellEnv); // Add the CGI environment variables String sPathInfoOrig = null; String sPathInfoCGI = null; String sPathTranslatedCGI = null; String sCGIFullPath = null; String sCGIScriptName = null; String sCGIFullName = null; String sCGIName = null; String[] sCGINames; sPathInfoOrig = this.pathInfo; sPathInfoOrig = sPathInfoOrig == null ? "" : sPathInfoOrig; if (webAppRootDir == null ) { // The app has not been deployed in exploded form webAppRootDir = tmpDir.toString(); expandCGIScript(); } sCGINames = findCGI(sPathInfoOrig, webAppRootDir, contextPath, servletPath, cgiPathPrefix); sCGIFullPath = sCGINames[0]; sCGIScriptName = sCGINames[1]; sCGIFullName = sCGINames[2]; sCGIName = sCGINames[3]; if (sCGIFullPath == null || sCGIScriptName == null || sCGIFullName == null || sCGIName == null) { return false; } envp.put("SERVER_SOFTWARE", "TOMCAT"); envp.put("SERVER_NAME", nullsToBlanks(req.getServerName())); envp.put("GATEWAY_INTERFACE", "CGI/1.1"); envp.put("SERVER_PROTOCOL", nullsToBlanks(req.getProtocol())); int port = req.getServerPort(); Integer iPort = (port == 0 ? Integer.valueOf(-1) : Integer.valueOf(port)); envp.put("SERVER_PORT", iPort.toString()); envp.put("REQUEST_METHOD", nullsToBlanks(req.getMethod())); envp.put("REQUEST_URI", nullsToBlanks(req.getRequestURI())); /*- * PATH_INFO should be determined by using sCGIFullName: * 1) Let sCGIFullName not end in a "/" (see method findCGI) * 2) Let sCGIFullName equal the pathInfo fragment which * corresponds to the actual cgi script. * 3) Thus, PATH_INFO = request.getPathInfo().substring( * sCGIFullName.length()) * * (see method findCGI, where the real work is done) * */ if (pathInfo == null || (pathInfo.substring(sCGIFullName.length()).length() <= 0)) { sPathInfoCGI = ""; } else { sPathInfoCGI = pathInfo.substring(sCGIFullName.length()); } envp.put("PATH_INFO", sPathInfoCGI); /*- * PATH_TRANSLATED must be determined after PATH_INFO (and the * implied real cgi-script) has been taken into account. * * The following example demonstrates: * * servlet info = /servlet/cgigw/dir1/dir2/cgi1/trans1/trans2 * cgifullpath = /servlet/cgigw/dir1/dir2/cgi1 * path_info = /trans1/trans2 * webAppRootDir = servletContext.getRealPath("/") * * path_translated = servletContext.getRealPath("/trans1/trans2") * * That is, PATH_TRANSLATED = webAppRootDir + sPathInfoCGI * (unless sPathInfoCGI is null or blank, then the CGI * specification dictates that the PATH_TRANSLATED metavariable * SHOULD NOT be defined. * */ if (sPathInfoCGI != null && !("".equals(sPathInfoCGI))) { sPathTranslatedCGI = context.getRealPath(sPathInfoCGI); } if (sPathTranslatedCGI == null || "".equals(sPathTranslatedCGI)) { //NOOP } else { envp.put("PATH_TRANSLATED", nullsToBlanks(sPathTranslatedCGI)); } envp.put("SCRIPT_NAME", nullsToBlanks(sCGIScriptName)); envp.put("QUERY_STRING", nullsToBlanks(req.getQueryString())); envp.put("REMOTE_HOST", nullsToBlanks(req.getRemoteHost())); envp.put("REMOTE_ADDR", nullsToBlanks(req.getRemoteAddr())); envp.put("AUTH_TYPE", nullsToBlanks(req.getAuthType())); envp.put("REMOTE_USER", nullsToBlanks(req.getRemoteUser())); envp.put("REMOTE_IDENT", ""); //not necessary for full compliance envp.put("CONTENT_TYPE", nullsToBlanks(req.getContentType())); /* Note CGI spec says CONTENT_LENGTH must be NULL ("") or undefined * if there is no content, so we cannot put 0 or -1 in as per the * Servlet API spec. */ int contentLength = req.getContentLength(); String sContentLength = (contentLength <= 0 ? "" : (Integer.valueOf(contentLength)).toString()); envp.put("CONTENT_LENGTH", sContentLength); Enumeration<String> headers = req.getHeaderNames(); String header = null; while (headers.hasMoreElements()) { header = null; header = headers.nextElement().toUpperCase(Locale.ENGLISH); //REMIND: rewrite multiple headers as if received as single //REMIND: change character set //REMIND: I forgot what the previous REMIND means if ("AUTHORIZATION".equalsIgnoreCase(header) || "PROXY_AUTHORIZATION".equalsIgnoreCase(header)) { //NOOP per CGI specification section 11.2 } else { envp.put("HTTP_" + header.replace('-', '_'), req.getHeader(header)); } } File fCGIFullPath = new File(sCGIFullPath); command = fCGIFullPath.getCanonicalPath(); envp.put("X_TOMCAT_SCRIPT_PATH", command); //for kicks envp.put("SCRIPT_FILENAME", command); //for PHP this.env = envp; return true; }
// in java/org/apache/catalina/servlets/CGIServlet.java
protected void run() throws IOException { /* * REMIND: this method feels too big; should it be re-written? */ if (!isReady()) { throw new IOException(this.getClass().getName() + ": not ready to run."); } if (debug >= 1 ) { log("runCGI(envp=[" + env + "], command=" + command + ")"); } if ((command.indexOf(File.separator + "." + File.separator) >= 0) || (command.indexOf(File.separator + "..") >= 0) || (command.indexOf(".." + File.separator) >= 0)) { throw new IOException(this.getClass().getName() + "Illegal Character in CGI command " + "path ('.' or '..') detected. Not " + "running CGI [" + command + "]."); } /* original content/structure of this section taken from * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4216884 * with major modifications by Martin Dengler */ Runtime rt = null; BufferedReader cgiHeaderReader = null; InputStream cgiOutput = null; BufferedReader commandsStdErr = null; Thread errReaderThread = null; BufferedOutputStream commandsStdIn = null; Process proc = null; int bufRead = -1; List<String> cmdAndArgs = new ArrayList<String>(); if (cgiExecutable.length() != 0) { cmdAndArgs.add(cgiExecutable); } if (cgiExecutableArgs != null) { cmdAndArgs.addAll(cgiExecutableArgs); } cmdAndArgs.add(command); cmdAndArgs.addAll(params); try { rt = Runtime.getRuntime(); proc = rt.exec( cmdAndArgs.toArray(new String[cmdAndArgs.size()]), hashToStringArray(env), wd); String sContentLength = env.get("CONTENT_LENGTH"); if(!"".equals(sContentLength)) { commandsStdIn = new BufferedOutputStream(proc.getOutputStream()); IOTools.flow(stdin, commandsStdIn); commandsStdIn.flush(); commandsStdIn.close(); } /* we want to wait for the process to exit, Process.waitFor() * is useless in our situation; see * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4223650 */ boolean isRunning = true; commandsStdErr = new BufferedReader (new InputStreamReader(proc.getErrorStream())); final BufferedReader stdErrRdr = commandsStdErr ; errReaderThread = new Thread() { @Override public void run () { sendToLog(stdErrRdr) ; } }; errReaderThread.start(); InputStream cgiHeaderStream = new HTTPHeaderInputStream(proc.getInputStream()); cgiHeaderReader = new BufferedReader(new InputStreamReader(cgiHeaderStream)); while (isRunning) { try { //set headers String line = null; while (((line = cgiHeaderReader.readLine()) != null) && !("".equals(line))) { if (debug >= 2) { log("runCGI: addHeader(\"" + line + "\")"); } if (line.startsWith("HTTP")) { response.setStatus(getSCFromHttpStatusLine(line)); } else if (line.indexOf(":") >= 0) { String header = line.substring(0, line.indexOf(":")).trim(); String value = line.substring(line.indexOf(":") + 1).trim(); if (header.equalsIgnoreCase("status")) { response.setStatus(getSCFromCGIStatusHeader(value)); } else { response.addHeader(header , value); } } else { log("runCGI: bad header line \"" + line + "\""); } } //write output byte[] bBuf = new byte[2048]; OutputStream out = response.getOutputStream(); cgiOutput = proc.getInputStream(); try { while ((bufRead = cgiOutput.read(bBuf)) != -1) { if (debug >= 4) { log("runCGI: output " + bufRead + " bytes of data"); } out.write(bBuf, 0, bufRead); } } finally { // Attempt to consume any leftover byte if something bad happens, // such as a socket disconnect on the servlet side; otherwise, the // external process could hang if (bufRead != -1) { while ((bufRead = cgiOutput.read(bBuf)) != -1) { // NOOP - just read the data } } } proc.exitValue(); // Throws exception if alive isRunning = false; } catch (IllegalThreadStateException e) { try { Thread.sleep(500); } catch (InterruptedException ignored) { // Ignore } } } //replacement for Process.waitFor() } catch (IOException e){ log ("Caught exception " + e); throw e; } finally{ // Close the header reader if (cgiHeaderReader != null) { try { cgiHeaderReader.close(); } catch (IOException ioe) { log ("Exception closing header reader " + ioe); } } // Close the output stream if used if (cgiOutput != null) { try { cgiOutput.close(); } catch (IOException ioe) { log ("Exception closing output stream " + ioe); } } // Make sure the error stream reader has finished if (errReaderThread != null) { try { errReaderThread.join(stderrTimeout); } catch (InterruptedException e) { log ("Interupted waiting for stderr reader thread"); } } if (debug > 4) { log ("Running finally block"); } if (proc != null){ proc.destroy(); proc = null; } } }
// in java/org/apache/catalina/servlets/CGIServlet.java
Override public int read() throws IOException { if (state == STATE_HEADER_END) { return -1; } int i = input.read(); // Update the state // State machine looks like this // // -------->-------- // | (CR) | // | | // CR1--->--- | // | | | // ^(CR) |(LF) | // | | | // CHAR--->--LF1--->--EOH // (LF) | (LF) | // |(CR) ^(LF) // | | // (CR2)-->--- if (i == 10) { // LF switch(state) { case STATE_CHARACTER: state = STATE_FIRST_LF; break; case STATE_FIRST_CR: state = STATE_FIRST_LF; break; case STATE_FIRST_LF: case STATE_SECOND_CR: state = STATE_HEADER_END; break; } } else if (i == 13) { // CR switch(state) { case STATE_CHARACTER: state = STATE_FIRST_CR; break; case STATE_FIRST_CR: state = STATE_HEADER_END; break; case STATE_FIRST_LF: state = STATE_SECOND_CR; break; } } else { state = STATE_CHARACTER; } return i; }
// in java/org/apache/catalina/ha/session/SerializablePrincipal.java
public static GenericPrincipal readPrincipal(ObjectInput in) throws IOException, ClassNotFoundException { String name = in.readUTF(); boolean hasPwd = in.readBoolean(); String pwd = null; if ( hasPwd ) pwd = in.readUTF(); int size = in.readInt(); String[] roles = new String[size]; for ( int i=0; i<size; i++ ) roles[i] = in.readUTF(); Principal userPrincipal = null; boolean hasUserPrincipal = in.readBoolean(); if (hasUserPrincipal) { try { userPrincipal = (Principal) in.readObject(); } catch (ClassNotFoundException e) { log.error(sm.getString( "serializablePrincipal.readPrincipal.cnfe"), e); throw e; } } return new GenericPrincipal(name,pwd,Arrays.asList(roles), userPrincipal); }
// in java/org/apache/catalina/ha/session/SerializablePrincipal.java
public static void writePrincipal(GenericPrincipal p, ObjectOutput out) throws IOException { out.writeUTF(p.getName()); out.writeBoolean(p.getPassword()!=null); if ( p.getPassword()!= null ) out.writeUTF(p.getPassword()); String[] roles = p.getRoles(); if ( roles == null ) roles = new String[0]; out.writeInt(roles.length); for ( int i=0; i<roles.length; i++ ) out.writeUTF(roles[i]); boolean hasUserPrincipal = (p != p.getUserPrincipal() && p.getUserPrincipal() instanceof Serializable); out.writeBoolean(hasUserPrincipal); if (hasUserPrincipal) out.writeObject(p.getUserPrincipal()); }
// in java/org/apache/catalina/ha/session/JvmRouteBinderValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (getEnabled() && request.getContext() != null && request.getContext().getDistributable() && !request.isAsyncDispatching()) { // valve cluster can access manager - other cluster handle turnover // at host level - hopefully! Manager manager = request.getContext().getManager(); if (manager != null && ( (manager instanceof ClusterManager && getCluster() != null && getCluster().getManager(((ClusterManager)manager).getName()) != null) || (manager instanceof PersistentManager))) { handlePossibleTurnover(request); } } // Pass this request on to the next valve in our pipeline getNext().invoke(request, response); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public byte[] getDiff() throws IOException { try{ lock(); return getDeltaRequest().serialize(); }finally{ unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void applyDiff(byte[] diff, int offset, int length) throws IOException, ClassNotFoundException { try { lock(); ReplicationStream stream = ( (ClusterManager) getManager()).getReplicationStream(diff, offset, length); ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); try { ClassLoader[] loaders = getClassLoaders(); if (loaders != null && loaders.length > 0) Thread.currentThread().setContextClassLoader(loaders[0]); getDeltaRequest().readExternal(stream); getDeltaRequest().execute(this, ((ClusterManager)getManager()).isNotifyListenersOnReplication()); } finally { Thread.currentThread().setContextClassLoader(contextLoader); } }finally { unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException { try { lock(); readObjectData(in); }finally{ unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void readObjectData(ObjectInputStream stream) throws ClassNotFoundException, IOException { readObject((ObjectInput)stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
public void readObjectData(ObjectInput stream) throws ClassNotFoundException, IOException { readObject(stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void writeObjectData(ObjectOutputStream stream) throws IOException { writeObjectData((ObjectOutput)stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
public void writeObjectData(ObjectOutput stream) throws IOException { writeObject(stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override protected void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException { readObject((ObjectInput)stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
private void readObject(ObjectInput stream) throws ClassNotFoundException, IOException { // Deserialize the scalar instance variables (except Manager) authType = null; // Transient only creationTime = ( (Long) stream.readObject()).longValue(); lastAccessedTime = ( (Long) stream.readObject()).longValue(); maxInactiveInterval = ( (Integer) stream.readObject()).intValue(); isNew = ( (Boolean) stream.readObject()).booleanValue(); isValid = ( (Boolean) stream.readObject()).booleanValue(); thisAccessedTime = ( (Long) stream.readObject()).longValue(); version = ( (Long) stream.readObject()).longValue(); boolean hasPrincipal = stream.readBoolean(); principal = null; if (hasPrincipal) { principal = SerializablePrincipal.readPrincipal(stream); } // setId((String) stream.readObject()); id = (String) stream.readObject(); if (log.isDebugEnabled()) log.debug(sm.getString("deltaSession.readSession", id)); // Deserialize the attribute count and attribute values if (attributes == null) attributes = new ConcurrentHashMap<String, Object>(); int n = ( (Integer) stream.readObject()).intValue(); boolean isValidSave = isValid; isValid = true; for (int i = 0; i < n; i++) { String name = (String) stream.readObject(); Object value = stream.readObject(); if ( (value instanceof String) && (value.equals(NOT_SERIALIZED))) continue; attributes.put(name, value); } isValid = isValidSave; if (listeners == null) { ArrayList<SessionListener> arrayList = new ArrayList<SessionListener>(); listeners = arrayList; } if (notes == null) { notes = new Hashtable<String,Object>(); } activate(); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void writeExternal(ObjectOutput out ) throws java.io.IOException { try { lock(); writeObject(out); }finally { unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override protected void writeObject(ObjectOutputStream stream) throws IOException { writeObject((ObjectOutput)stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
private void writeObject(ObjectOutput stream) throws IOException { // Write the scalar instance variables (except Manager) stream.writeObject(Long.valueOf(creationTime)); stream.writeObject(Long.valueOf(lastAccessedTime)); stream.writeObject(Integer.valueOf(maxInactiveInterval)); stream.writeObject(Boolean.valueOf(isNew)); stream.writeObject(Boolean.valueOf(isValid)); stream.writeObject(Long.valueOf(thisAccessedTime)); stream.writeObject(Long.valueOf(version)); stream.writeBoolean(getPrincipal() != null); if (getPrincipal() != null) { SerializablePrincipal.writePrincipal((GenericPrincipal) principal,stream); } stream.writeObject(id); if (log.isDebugEnabled()) log.debug(sm.getString("deltaSession.writeSession", id)); // Accumulate the names of serializable and non-serializable attributes String keys[] = keys(); ArrayList<String> saveNames = new ArrayList<String>(); ArrayList<Object> saveValues = new ArrayList<Object>(); for (int i = 0; i < keys.length; i++) { Object value = null; value = attributes.get(keys[i]); if (value == null || exclude(keys[i])) continue; else if (value instanceof Serializable) { saveNames.add(keys[i]); saveValues.add(value); } } // Serialize the attribute count and the Serializable attributes int n = saveNames.size(); stream.writeObject(Integer.valueOf(n)); for (int i = 0; i < n; i++) { stream.writeObject( saveNames.get(i)); try { stream.writeObject(saveValues.get(i)); } catch (NotSerializableException e) { log.error(sm.getString("standardSession.notSerializable",saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); log.error(" storing attribute '" + saveNames.get(i)+ "' with value NOT_SERIALIZED"); } } }
// in java/org/apache/catalina/ha/session/ClusterManagerBase.java
Override public ReplicationStream getReplicationStream(byte[] data) throws IOException { return getReplicationStream(data,0,data.length); }
// in java/org/apache/catalina/ha/session/ClusterManagerBase.java
Override public ReplicationStream getReplicationStream(byte[] data, int offset, int length) throws IOException { ByteArrayInputStream fis = new ByteArrayInputStream(data, offset, length); return new ReplicationStream(fis, getClassLoaders()); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
Override public void readExternal(java.io.ObjectInput in) throws IOException,ClassNotFoundException { //sessionId - String //recordAll - boolean //size - int //AttributeInfo - in an array reset(); sessionId = in.readUTF(); recordAllActions = in.readBoolean(); int cnt = in.readInt(); if (actions == null) actions = new LinkedList<AttributeInfo>(); else actions.clear(); for (int i = 0; i < cnt; i++) { AttributeInfo info = null; if (this.actionPool.size() > 0) { try { info = actionPool.removeFirst(); } catch ( Exception x ) { log.error("Unable to remove element",x); info = new AttributeInfo(); } } else { info = new AttributeInfo(); } info.readExternal(in); actions.addLast(info); }//for }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
Override public void writeExternal(java.io.ObjectOutput out ) throws java.io.IOException { //sessionId - String //recordAll - boolean //size - int //AttributeInfo - in an array out.writeUTF(getSessionId()); out.writeBoolean(recordAllActions); out.writeInt(getSize()); for ( int i=0; i<getSize(); i++ ) { AttributeInfo info = actions.get(i); info.writeExternal(out); } }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
protected byte[] serialize() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); writeExternal(oos); oos.flush(); oos.close(); return bos.toByteArray(); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
Override public void readExternal(java.io.ObjectInput in ) throws IOException,ClassNotFoundException { //type - int //action - int //name - String //hasvalue - boolean //value - object type = in.readInt(); action = in.readInt(); name = in.readUTF(); boolean hasValue = in.readBoolean(); if ( hasValue ) value = in.readObject(); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
Override public void writeExternal(java.io.ObjectOutput out) throws IOException { //type - int //action - int //name - String //hasvalue - boolean //value - object out.writeInt(getType()); out.writeInt(getAction()); out.writeUTF(getName()); out.writeBoolean(getValue()!=null); if (getValue()!=null) out.writeObject(getValue()); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected byte[] serializeSessionId(String sessionId) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeUTF(sessionId); oos.flush(); oos.close(); return bos.toByteArray(); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected String deserializeSessionId(byte[] data) throws IOException { ReplicationStream ois = getReplicationStream(data); String sessionId = ois.readUTF(); ois.close(); return sessionId; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected DeltaRequest deserializeDeltaRequest(DeltaSession session, byte[] data) throws ClassNotFoundException, IOException { try { session.lock(); ReplicationStream ois = getReplicationStream(data); session.getDeltaRequest().readExternal(ois); ois.close(); return session.getDeltaRequest(); }finally { session.unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected byte[] serializeDeltaRequest(DeltaSession session, DeltaRequest deltaRequest) throws IOException { try { session.lock(); return deltaRequest.serialize(); }finally { session.unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void deserializeSessions(byte[] data) throws ClassNotFoundException,IOException { // Initialize our internal data structures //sessions.clear(); //should not do this // Open an input stream to the specified pathname, if any ClassLoader originalLoader = Thread.currentThread().getContextClassLoader(); ObjectInputStream ois = null; // Load the previously unloaded active sessions try { ois = getReplicationStream(data); Integer count = (Integer) ois.readObject(); int n = count.intValue(); for (int i = 0; i < n; i++) { DeltaSession session = (DeltaSession) createEmptySession(); session.readObjectData(ois); session.setManager(this); session.setValid(true); session.setPrimarySession(false); //in case the nodes in the cluster are out of //time synch, this will make sure that we have the //correct timestamp, isValid returns true, cause // accessCount=1 session.access(); //make sure that the session gets ready to expire if // needed session.setAccessCount(0); session.resetDeltaRequest(); // FIXME How inform other session id cache like SingleSignOn // increment sessionCounter to correct stats report if (findSession(session.getIdInternal()) == null ) { sessionCounter++; } else { sessionReplaceCounter++; // FIXME better is to grap this sessions again ! if (log.isWarnEnabled()) log.warn(sm.getString("deltaManager.loading.existing.session",session.getIdInternal())); } add(session); if (notifySessionListenersOnReplication) { session.tellNew(); } } } catch (ClassNotFoundException e) { log.error(sm.getString("deltaManager.loading.cnfe", e), e); throw e; } catch (IOException e) { log.error(sm.getString("deltaManager.loading.ioe", e), e); throw e; } finally { // Close the input stream try { if (ois != null) ois.close(); } catch (IOException f) { // ignored } ois = null; if (originalLoader != null) Thread.currentThread().setContextClassLoader(originalLoader); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected byte[] serializeSessions(Session[] currentSessions) throws IOException { // Open an output stream to the specified pathname, if any ByteArrayOutputStream fos = null; ObjectOutputStream oos = null; try { fos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(new BufferedOutputStream(fos)); oos.writeObject(Integer.valueOf(currentSessions.length)); for(int i=0 ; i < currentSessions.length;i++) { ((DeltaSession)currentSessions[i]).writeObjectData(oos); } // Flush and close the output stream oos.flush(); } catch (IOException e) { log.error(sm.getString("deltaManager.unloading.ioe", e), e); throw e; } finally { if (oos != null) { try { oos.close(); } catch (IOException f) { // Ignore } oos = null; } } // send object data as byte[] return fos.toByteArray(); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleSESSION_DELTA(SessionMessage msg, Member sender) throws IOException, ClassNotFoundException { counterReceive_EVT_SESSION_DELTA++; byte[] delta = msg.getSession(); DeltaSession session = (DeltaSession) findSession(msg.getSessionID()); if (session != null) { if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.delta",getName(), msg.getSessionID())); try { session.lock(); DeltaRequest dreq = deserializeDeltaRequest(session, delta); dreq.execute(session, isNotifyListenersOnReplication()); session.setPrimarySession(false); }finally { session.unlock(); } } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleSESSION_ACCESSED(SessionMessage msg,Member sender) throws IOException { counterReceive_EVT_SESSION_ACCESSED++; DeltaSession session = (DeltaSession) findSession(msg.getSessionID()); if (session != null) { if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.accessed",getName(), msg.getSessionID())); session.access(); session.setPrimarySession(false); session.endAccess(); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleSESSION_EXPIRED(SessionMessage msg,Member sender) throws IOException { counterReceive_EVT_SESSION_EXPIRED++; DeltaSession session = (DeltaSession) findSession(msg.getSessionID()); if (session != null) { if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.expired",getName(), msg.getSessionID())); session.expire(notifySessionListenersOnReplication, false); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleALL_SESSION_DATA(SessionMessage msg,Member sender) throws ClassNotFoundException, IOException { counterReceive_EVT_ALL_SESSION_DATA++; if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataBegin",getName())); byte[] data = msg.getSession(); deserializeSessions(data); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataAfter",getName())); //stateTransferred = true; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleGET_ALL_SESSIONS(SessionMessage msg, Member sender) throws IOException { counterReceive_EVT_GET_ALL_SESSIONS++; //get a list of all the session from this manager if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.unloadingBegin", getName())); // Write the number of active sessions, followed by the details // get all sessions and serialize without sync Session[] currentSessions = findSessions(); long findSessionTimestamp = System.currentTimeMillis() ; if (isSendAllSessions()) { sendSessions(sender, currentSessions, findSessionTimestamp); } else { // send session at blocks for (int i = 0; i < currentSessions.length; i += getSendAllSessionsSize()) { int len = i + getSendAllSessionsSize() > currentSessions.length ? currentSessions.length - i : getSendAllSessionsSize(); Session[] sendSessions = new Session[len]; System.arraycopy(currentSessions, i, sendSessions, 0, len); sendSessions(sender, sendSessions,findSessionTimestamp); if (getSendAllSessionsWaitTime() > 0) { try { Thread.sleep(getSendAllSessionsWaitTime()); } catch (Exception sleep) { } }//end if }//for }//end if SessionMessage newmsg = new SessionMessageImpl(name,SessionMessage.EVT_ALL_SESSION_TRANSFERCOMPLETE, null,"SESSION-STATE-TRANSFERED", "SESSION-STATE-TRANSFERED"+ getName()); newmsg.setTimestamp(findSessionTimestamp); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.createMessage.allSessionTransfered",getName())); counterSend_EVT_ALL_SESSION_TRANSFERCOMPLETE++; cluster.send(newmsg, sender); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleCHANGE_SESSION_ID(SessionMessage msg,Member sender) throws IOException { counterReceive_EVT_CHANGE_SESSION_ID++; DeltaSession session = (DeltaSession) findSession(msg.getSessionID()); if (session != null) { String newSessionID = deserializeSessionId(msg.getSession()); session.setPrimarySession(false); session.setId(newSessionID, false); if (notifyContainerListenersOnReplication) { getContainer().fireContainerEvent(Context.CHANGE_SESSION_ID_EVENT, new String[] {msg.getSessionID(), newSessionID}); } } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void sendSessions(Member sender, Session[] currentSessions,long sendTimestamp) throws IOException { byte[] data = serializeSessions(currentSessions); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.unloadingAfter",getName())); SessionMessage newmsg = new SessionMessageImpl(name,SessionMessage.EVT_ALL_SESSION_DATA, data,"SESSION-STATE", "SESSION-STATE-" + getName()); newmsg.setTimestamp(sendTimestamp); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.createMessage.allSessionData",getName())); counterSend_EVT_ALL_SESSION_DATA++; cluster.send(newmsg, sender); }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public static FileMessageFactory getInstance(File f, boolean openForWrite) throws FileNotFoundException, IOException { return new FileMessageFactory(f, openForWrite); }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public FileMessage readMessage(FileMessage f) throws IllegalArgumentException, IOException { checkState(false); int length = in.read(data); if (length == -1) { cleanup(); return null; } else { f.setData(data, length); f.setTotalLength(size); f.setTotalNrOfMsgs(totalNrOfMessages); f.setMessageNumber(++nrOfMessagesProcessed); return f; }//end if }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public boolean writeMessage(FileMessage msg) throws IllegalArgumentException, IOException { if (!openForWrite) throw new IllegalArgumentException( "Can't write message, this factory is reading."); if (log.isDebugEnabled()) log.debug("Message " + msg + " data " + HexUtils.toHexString(msg.getData()) + " data length " + msg.getDataLength() + " out " + out); if (msg.getMessageNumber() <= lastMessageProcessed.get()) { // Duplicate of message already processed log.warn("Receive Message again -- Sender ActTimeout too short [ name: " + msg.getContextName() + " war: " + msg.getFileName() + " data: " + HexUtils.toHexString(msg.getData()) + " data length: " + msg.getDataLength() + " ]"); return false; } FileMessage previous = msgBuffer.put(Long.valueOf(msg.getMessageNumber()), msg); if (previous !=null) { // Duplicate of message not yet processed log.warn("Receive Message again -- Sender ActTimeout too short [ name: " + msg.getContextName() + " war: " + msg.getFileName() + " data: " + HexUtils.toHexString(msg.getData()) + " data length: " + msg.getDataLength() + " ]"); return false; } FileMessage next = null; synchronized (this) { if (!isWriting) { next = msgBuffer.get(Long.valueOf(lastMessageProcessed.get() + 1)); if (next != null) { isWriting = true; } else { return false; } } else { return false; } } while (next != null) { out.write(next.getData(), 0, next.getDataLength()); lastMessageProcessed.incrementAndGet(); out.flush(); if (next.getMessageNumber() == next.getTotalNrOfMsgs()) { out.close(); cleanup(); return true; } synchronized(this) { next = msgBuffer.get(Long.valueOf(lastMessageProcessed.get() + 1)); if (next == null) { isWriting = false; } } } return false; }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
public synchronized FileMessageFactory getFactory(FileMessage msg) throws java.io.FileNotFoundException, java.io.IOException { File writeToFile = new File(getTempDir(), msg.getFileName()); FileMessageFactory factory = fileFactories.get(msg.getFileName()); if (factory == null) { factory = FileMessageFactory.getInstance(writeToFile, true); fileFactories.put(msg.getFileName(), factory); } return factory; }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
Override public void install(String contextName, File webapp) throws IOException { Member[] members = getCluster().getMembers(); Member localMember = getCluster().getLocalMember(); FileMessageFactory factory = FileMessageFactory.getInstance(webapp, false); FileMessage msg = new FileMessage(localMember, webapp.getName(), contextName); if(log.isDebugEnabled()) log.debug(sm.getString("farmWarDeployer.sendStart", contextName, webapp)); msg = factory.readMessage(msg); while (msg != null) { for (int i = 0; i < members.length; i++) { if (log.isDebugEnabled()) log.debug(sm.getString("farmWarDeployer.sendFragment", contextName, webapp, members[i])); getCluster().send(msg, members[i]); } msg = factory.readMessage(msg); } if(log.isDebugEnabled()) log.debug(sm.getString( "farmWarDeployer.sendEnd", contextName, webapp)); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
Override public void remove(String contextName, boolean undeploy) throws IOException { if (log.isInfoEnabled()) log.info(sm.getString("farmWarDeployer.removeStart", contextName)); Member localMember = getCluster().getLocalMember(); UndeployMessage msg = new UndeployMessage(localMember, System .currentTimeMillis(), "Undeploy:" + contextName + ":" + System.currentTimeMillis(), contextName, undeploy); if (log.isDebugEnabled()) log.debug(sm.getString("farmWarDeployer.removeTxMsg", contextName)); cluster.send(msg); // remove locally if (undeploy) { try { if (!isServiced(contextName)) { addServiced(contextName); try { remove(contextName); } finally { removeServiced(contextName); } } else log.error(sm.getString("farmWarDeployer.removeFailRemote", contextName)); } catch (Exception ex) { log.error(sm.getString("farmWarDeployer.removeFailLocal", contextName), ex); } } }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { long totalstart = 0; //this happens before the request if(doStatistics()) { totalstart = System.currentTimeMillis(); } if (primaryIndicator) { createPrimaryIndicator(request) ; } Context context = request.getContext(); boolean isCrossContext = context != null && context instanceof StandardContext && ((StandardContext) context).getCrossContext(); try { if(isCrossContext) { if(log.isDebugEnabled()) { log.debug(sm.getString("ReplicationValve.crossContext.add")); } //FIXME add Pool of Arraylists crossContextSessions.set(new ArrayList<DeltaSession>()); } getNext().invoke(request, response); if(context != null) { Manager manager = context.getManager(); if (manager != null && manager instanceof ClusterManager) { ClusterManager clusterManager = (ClusterManager) manager; CatalinaCluster containerCluster = (CatalinaCluster) getContainer().getCluster(); if (containerCluster == null) { if (log.isWarnEnabled()) { log.warn(sm.getString("ReplicationValve.nocluster")); } return; } // valve cluster can access manager - other cluster handle replication // at host level - hopefully! if(containerCluster.getManager(clusterManager.getName()) == null) { return ; } if(containerCluster.hasMembers()) { sendReplicationMessage(request, totalstart, isCrossContext, clusterManager, containerCluster); } else { resetReplicationRequest(request,isCrossContext); } } } } finally { // Array must be remove: Current master request send endAccess at recycle. // Don't register this request session again! if(isCrossContext) { if(log.isDebugEnabled()) { log.debug(sm.getString("ReplicationValve.crossContext.remove")); } // crossContextSessions.remove() only exist at Java 5 // register ArrayList at a pool crossContextSessions.set(null); } } }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
protected void createPrimaryIndicator(Request request) throws IOException { String id = request.getRequestedSessionId(); if ((id != null) && (id.length() > 0)) { Manager manager = request.getContext().getManager(); Session session = manager.findSession(id); if (session instanceof ClusterSession) { ClusterSession cses = (ClusterSession) session; if (log.isDebugEnabled()) { log.debug(sm.getString( "ReplicationValve.session.indicator", request.getContext().getName(),id, primaryIndicatorName, Boolean.valueOf(cses.isPrimarySession()))); } request.setAttribute(primaryIndicatorName, cses.isPrimarySession()?Boolean.TRUE:Boolean.FALSE); } else { if (log.isDebugEnabled()) { if (session != null) { log.debug(sm.getString( "ReplicationValve.session.found", request.getContext().getName(),id)); } else { log.debug(sm.getString( "ReplicationValve.session.invalid", request.getContext().getName(),id)); } } } } }
// in java/org/apache/catalina/ssi/SSIFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // cast once HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse res = (HttpServletResponse)response; // indicate that we're in SSI processing req.setAttribute(Globals.SSI_FLAG_ATTR, "true"); // setup to capture output ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream(); ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(config.getServletContext(),req, res, basos); // process remainder of filter chain chain.doFilter(req, responseIncludeWrapper); // we can't assume the chain flushed its output responseIncludeWrapper.flushOutputStreamOrWriter(); byte[] bytes = basos.toByteArray(); // get content type String contentType = responseIncludeWrapper.getContentType(); // is this an allowed type for SSI processing? if (contentTypeRegEx.matcher(contentType).matches()) { String encoding = res.getCharacterEncoding(); // set up SSI processing SSIExternalResolver ssiExternalResolver = new SSIServletExternalResolver(config.getServletContext(), req, res, isVirtualWebappRelative, debug, encoding); SSIProcessor ssiProcessor = new SSIProcessor(ssiExternalResolver, debug, allowExec); // prepare readers/writers Reader reader = new InputStreamReader(new ByteArrayInputStream(bytes), encoding); ByteArrayOutputStream ssiout = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(ssiout, encoding)); // do SSI processing long lastModified = ssiProcessor.process(reader, responseIncludeWrapper.getLastModified(), writer); // set output bytes writer.flush(); bytes = ssiout.toByteArray(); // override headers if (expires != null) { res.setDateHeader("expires", (new java.util.Date()).getTime() + expires.longValue() * 1000); } if (lastModified > 0) { res.setDateHeader("last-modified", lastModified); } res.setContentLength(bytes.length); Matcher shtmlMatcher = shtmlRegEx.matcher(responseIncludeWrapper.getContentType()); if (shtmlMatcher.matches()) { // Convert shtml mime type to ordinary html mime type but preserve // encoding, if any. String enc = shtmlMatcher.group(1); res.setContentType("text/html" + ((enc != null) ? enc : "")); } } // write output OutputStream out = null; try { out = res.getOutputStream(); } catch (IllegalStateException e) { // Ignore, will try to use a writer } if (out == null) { res.getWriter().write(new String(bytes)); } else { out.write(bytes); } }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected String getAbsolutePath(String path) throws IOException { String pathWithoutContext = SSIServletRequestUtil.getRelativePath(req); String prefix = getPathWithoutFileName(pathWithoutContext); if (prefix == null) { throw new IOException("Couldn't remove filename from path: " + pathWithoutContext); } String fullPath = prefix + path; String retVal = RequestUtil.normalize(fullPath); if (retVal == null) { throw new IOException("Normalization yielded null on path: " + fullPath); } return retVal; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected ServletContextAndPath getServletContextAndPathFromNonVirtualPath( String nonVirtualPath) throws IOException { if (nonVirtualPath.startsWith("/") || nonVirtualPath.startsWith("\\")) { throw new IOException("A non-virtual path can't be absolute: " + nonVirtualPath); } if (nonVirtualPath.indexOf("../") >= 0) { throw new IOException("A non-virtual path can't contain '../' : " + nonVirtualPath); } String path = getAbsolutePath(nonVirtualPath); ServletContextAndPath csAndP = new ServletContextAndPath( context, path); return csAndP; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected ServletContextAndPath getServletContextAndPathFromVirtualPath( String virtualPath) throws IOException { if (!virtualPath.startsWith("/") && !virtualPath.startsWith("\\")) { return new ServletContextAndPath(context, getAbsolutePath(virtualPath)); } String normalized = RequestUtil.normalize(virtualPath); if (isVirtualWebappRelative) { return new ServletContextAndPath(context, normalized); } ServletContext normContext = context.getContext(normalized); if (normContext == null) { throw new IOException("Couldn't get context for path: " + normalized); } //If it's the root context, then there is no context element // to remove, // ie: // '/file1.shtml' vs '/appName1/file1.shtml' if (!isRootContext(normContext)) { String noContext = getPathWithoutContext( normContext.getContextPath(), normalized); if (noContext == null) { throw new IOException( "Couldn't remove context from path: " + normalized); } return new ServletContextAndPath(normContext, noContext); } return new ServletContextAndPath(normContext, normalized); }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected ServletContextAndPath getServletContextAndPath( String originalPath, boolean virtual) throws IOException { ServletContextAndPath csAndP = null; if (debug > 0) { log("SSIServletExternalResolver.getServletContextAndPath( " + originalPath + ", " + virtual + ")", null); } if (virtual) { csAndP = getServletContextAndPathFromVirtualPath(originalPath); } else { csAndP = getServletContextAndPathFromNonVirtualPath(originalPath); } return csAndP; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected URLConnection getURLConnection(String originalPath, boolean virtual) throws IOException { ServletContextAndPath csAndP = getServletContextAndPath(originalPath, virtual); ServletContext context = csAndP.getServletContext(); String path = csAndP.getPath(); URL url = context.getResource(path); if (url == null) { throw new IOException("Context did not contain resource: " + path); } URLConnection urlConnection = url.openConnection(); return urlConnection; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
Override public long getFileLastModified(String path, boolean virtual) throws IOException { long lastModified = 0; try { URLConnection urlConnection = getURLConnection(path, virtual); lastModified = urlConnection.getLastModified(); } catch (IOException e) { // Ignore this. It will always fail for non-file based includes } return lastModified; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
Override public long getFileSize(String path, boolean virtual) throws IOException { long fileSize = -1; try { URLConnection urlConnection = getURLConnection(path, virtual); fileSize = urlConnection.getContentLength(); } catch (IOException e) { // Ignore this. It will always fail for non-file based includes } return fileSize; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
Override public String getFileText(String originalPath, boolean virtual) throws IOException { try { ServletContextAndPath csAndP = getServletContextAndPath( originalPath, virtual); ServletContext context = csAndP.getServletContext(); String path = csAndP.getPath(); RequestDispatcher rd = context.getRequestDispatcher(path); if (rd == null) { throw new IOException( "Couldn't get request dispatcher for path: " + path); } ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream(); ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(context, req, res, basos); rd.include(req, responseIncludeWrapper); //We can't assume the included servlet flushed its output responseIncludeWrapper.flushOutputStreamOrWriter(); byte[] bytes = basos.toByteArray(); //Assume platform default encoding unless otherwise specified String retVal; if (inputEncoding == null) { retVal = new String( bytes ); } else { retVal = new String (bytes, B2CConverter.getCharset(inputEncoding)); } //make an assumption that an empty response is a failure. This is // a problem // if a truly empty file //were included, but not sure how else to tell. if (retVal.equals("") && !req.getMethod().equalsIgnoreCase( org.apache.coyote.http11.Constants.HEAD)) { throw new IOException("Couldn't find file: " + path); } return retVal; } catch (ServletException e) { throw new IOException("Couldn't include file: " + originalPath + " because of ServletException: " + e.getMessage()); } }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
public void flushOutputStreamOrWriter() throws IOException { if (servletOutputStream != null) { servletOutputStream.flush(); } if (printWriter != null) { printWriter.flush(); } }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
Override public PrintWriter getWriter() throws java.io.IOException { if (servletOutputStream == null) { if (printWriter == null) { setCharacterEncoding(getCharacterEncoding()); printWriter = new PrintWriter( new OutputStreamWriter(captureServletOutputStream, getCharacterEncoding())); } return printWriter; } throw new IllegalStateException(); }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
Override public ServletOutputStream getOutputStream() throws java.io.IOException { if (printWriter == null) { if (servletOutputStream == null) { servletOutputStream = captureServletOutputStream; } return servletOutputStream; } throw new IllegalStateException(); }
// in java/org/apache/catalina/ssi/SSIServlet.java
Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { if (debug > 0) log("SSIServlet.doGet()"); requestHandler(req, res); }
// in java/org/apache/catalina/ssi/SSIServlet.java
Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { if (debug > 0) log("SSIServlet.doPost()"); requestHandler(req, res); }
// in java/org/apache/catalina/ssi/SSIServlet.java
protected void requestHandler(HttpServletRequest req, HttpServletResponse res) throws IOException { ServletContext servletContext = getServletContext(); String path = SSIServletRequestUtil.getRelativePath(req); if (debug > 0) log("SSIServlet.requestHandler()\n" + "Serving " + (buffered?"buffered ":"unbuffered ") + "resource '" + path + "'"); // Exclude any resource in the /WEB-INF and /META-INF subdirectories // (the "toUpperCase()" avoids problems on Windows systems) if (path == null || path.toUpperCase(Locale.ENGLISH).startsWith("/WEB-INF") || path.toUpperCase(Locale.ENGLISH).startsWith("/META-INF")) { res.sendError(HttpServletResponse.SC_NOT_FOUND, path); log("Can't serve file: " + path); return; } URL resource = servletContext.getResource(path); if (resource == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND, path); log("Can't find file: " + path); return; } String resourceMimeType = servletContext.getMimeType(path); if (resourceMimeType == null) { resourceMimeType = "text/html"; } res.setContentType(resourceMimeType + ";charset=" + outputEncoding); if (expires != null) { res.setDateHeader("Expires", (new java.util.Date()).getTime() + expires.longValue() * 1000); } req.setAttribute(Globals.SSI_FLAG_ATTR, "true"); processSSI(req, res, resource); }
// in java/org/apache/catalina/ssi/SSIServlet.java
protected void processSSI(HttpServletRequest req, HttpServletResponse res, URL resource) throws IOException { SSIExternalResolver ssiExternalResolver = new SSIServletExternalResolver(getServletContext(), req, res, isVirtualWebappRelative, debug, inputEncoding); SSIProcessor ssiProcessor = new SSIProcessor(ssiExternalResolver, debug, allowExec); PrintWriter printWriter = null; StringWriter stringWriter = null; if (buffered) { stringWriter = new StringWriter(); printWriter = new PrintWriter(stringWriter); } else { printWriter = res.getWriter(); } URLConnection resourceInfo = resource.openConnection(); InputStream resourceInputStream = resourceInfo.getInputStream(); String encoding = resourceInfo.getContentEncoding(); if (encoding == null) { encoding = inputEncoding; } InputStreamReader isr; if (encoding == null) { isr = new InputStreamReader(resourceInputStream); } else { isr = new InputStreamReader(resourceInputStream, encoding); } BufferedReader bufferedReader = new BufferedReader(isr); long lastModified = ssiProcessor.process(bufferedReader, resourceInfo.getLastModified(), printWriter); if (lastModified > 0) { res.setDateHeader("last-modified", lastModified); } if (buffered) { printWriter.flush(); @SuppressWarnings("null") String text = stringWriter.toString(); res.getWriter().write(text); } bufferedReader.close(); }
// in java/org/apache/catalina/ssi/SSIProcessor.java
public long process(Reader reader, long lastModifiedDate, PrintWriter writer) throws IOException { SSIMediator ssiMediator = new SSIMediator(ssiExternalResolver, lastModifiedDate, debug); StringWriter stringWriter = new StringWriter(); IOTools.flow(reader, stringWriter); String fileContents = stringWriter.toString(); stringWriter = null; int index = 0; boolean inside = false; StringBuilder command = new StringBuilder(); try { while (index < fileContents.length()) { char c = fileContents.charAt(index); if (!inside) { if (c == COMMAND_START.charAt(0) && charCmp(fileContents, index, COMMAND_START)) { inside = true; index += COMMAND_START.length(); command.setLength(0); //clear the command string } else { if (!ssiMediator.getConditionalState().processConditionalCommandsOnly) { writer.write(c); } index++; } } else { if (c == COMMAND_END.charAt(0) && charCmp(fileContents, index, COMMAND_END)) { inside = false; index += COMMAND_END.length(); String strCmd = parseCmd(command); if (debug > 0) { ssiExternalResolver.log( "SSIProcessor.process -- processing command: " + strCmd, null); } String[] paramNames = parseParamNames(command, strCmd .length()); String[] paramValues = parseParamValues(command, strCmd.length(), paramNames.length); //We need to fetch this value each time, since it may // change // during the loop String configErrMsg = ssiMediator.getConfigErrMsg(); SSICommand ssiCommand = commands.get(strCmd.toLowerCase(Locale.ENGLISH)); String errorMessage = null; if (ssiCommand == null) { errorMessage = "Unknown command: " + strCmd; } else if (paramValues == null) { errorMessage = "Error parsing directive parameters."; } else if (paramNames.length != paramValues.length) { errorMessage = "Parameter names count does not match parameter values count on command: " + strCmd; } else { // don't process the command if we are processing // conditional // commands only and the // command is not conditional if (!ssiMediator.getConditionalState().processConditionalCommandsOnly || ssiCommand instanceof SSIConditional) { long lmd = ssiCommand.process(ssiMediator, strCmd, paramNames, paramValues, writer); if (lmd > lastModifiedDate) { lastModifiedDate = lmd; } } } if (errorMessage != null) { ssiExternalResolver.log(errorMessage, null); writer.write(configErrMsg); } } else { command.append(c); index++; } } } } catch (SSIStopProcessingException e) { //If we are here, then we have already stopped processing, so all // is good } return lastModifiedDate; }
// in java/org/apache/catalina/ssi/SSIMediator.java
public long getFileSize(String path, boolean virtual) throws IOException { return ssiExternalResolver.getFileSize(path, virtual); }
// in java/org/apache/catalina/ssi/SSIMediator.java
public long getFileLastModified(String path, boolean virtual) throws IOException { return ssiExternalResolver.getFileLastModified(path, virtual); }
// in java/org/apache/catalina/ssi/SSIMediator.java
public String getFileText(String path, boolean virtual) throws IOException { return ssiExternalResolver.getFileText(path, virtual); }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void close() throws IOException { if (closed) { return; } if (suspended) { return; } // Flush the convertor if one is in use if (gotEnc && conv != null) { conv.flushBuffer(); } if ((!coyoteResponse.isCommitted()) && (coyoteResponse.getContentLengthLong() == -1)) { // If this didn't cause a commit of the response, the final content // length can be calculated if (!coyoteResponse.isCommitted()) { coyoteResponse.setContentLength(bb.getLength()); } } doFlush(false); closed = true; // The request should have been completely read by the time the response // is closed. Further reads of the input a) are pointless and b) really // confuse AJP (bug 50189) so close the input buffer to prevent them. Request req = (Request) coyoteResponse.getRequest().getNote( CoyoteAdapter.ADAPTER_NOTES); req.inputBuffer.close(); coyoteResponse.finish(); }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void flush() throws IOException { doFlush(true); }
// in java/org/apache/catalina/connector/OutputBuffer.java
protected void doFlush(boolean realFlush) throws IOException { if (suspended) { return; } // Flush the convertor if one is in use if (gotEnc && conv != null) { conv.flushBuffer(); } try { doFlush = true; if (initial) { coyoteResponse.sendHeaders(); initial = false; } if (bb.getLength() > 0) { bb.flushBuffer(); } } finally { doFlush = false; } if (realFlush) { coyoteResponse.action(ActionCode.CLIENT_FLUSH, coyoteResponse); // If some exception occurred earlier, or if some IOE occurred // here, notify the servlet with an IOE if (coyoteResponse.isExceptionPresent()) { throw new ClientAbortException (coyoteResponse.getErrorException()); } } }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void realWriteBytes(byte buf[], int off, int cnt) throws IOException { if (closed) { return; } if (coyoteResponse == null) { return; } // If we really have something to write if (cnt > 0) { // real write to the adapter outputChunk.setBytes(buf, off, cnt); try { coyoteResponse.doWrite(outputChunk); } catch (IOException e) { // An IOException on a write is almost always due to // the remote client aborting the request. Wrap this // so that it can be handled better by the error dispatcher. throw new ClientAbortException(e); } } }
// in java/org/apache/catalina/connector/OutputBuffer.java
public void write(byte b[], int off, int len) throws IOException { if (suspended) { return; } writeBytes(b, off, len); }
// in java/org/apache/catalina/connector/OutputBuffer.java
private void writeBytes(byte b[], int off, int len) throws IOException { if (closed) { return; } bb.append(b, off, len); bytesWritten += len; // if called from within flush(), then immediately flush // remaining bytes if (doFlush) { bb.flushBuffer(); } }
// in java/org/apache/catalina/connector/OutputBuffer.java
public void writeByte(int b) throws IOException { if (suspended) { return; } bb.append((byte) b); bytesWritten++; }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void write(int c) throws IOException { if (suspended) { return; } conv.convert((char) c); charsWritten++; }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void write(char c[]) throws IOException { if (suspended) { return; } write(c, 0, c.length); }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void write(char c[], int off, int len) throws IOException { if (suspended) { return; } conv.convert(c, off, len); charsWritten += len; }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void write(String s, int off, int len) throws IOException { if (suspended) { return; } charsWritten += len; if (s == null) { s = "null"; } conv.convert(s, off, len); }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void write(String s) throws IOException { if (suspended) { return; } if (s == null) { s = "null"; } conv.convert(s); }
// in java/org/apache/catalina/connector/OutputBuffer.java
public void checkConverter() throws IOException { if (!gotEnc) { setConverter(); } }
// in java/org/apache/catalina/connector/OutputBuffer.java
protected void setConverter() throws IOException { if (coyoteResponse != null) { enc = coyoteResponse.getCharacterEncoding(); } gotEnc = true; if (enc == null) { enc = DEFAULT_ENCODING; } conv = encoders.get(enc); if (conv == null) { if (Globals.IS_SECURITY_ENABLED){ try{ conv = AccessController.doPrivileged( new PrivilegedExceptionAction<C2BConverter>(){ @Override public C2BConverter run() throws IOException{ return new C2BConverter(bb, enc); } } ); }catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } } } else { conv = new C2BConverter(bb, enc); } encoders.put(enc, conv); }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public C2BConverter run() throws IOException{ return new C2BConverter(bb, enc); }
// in java/org/apache/catalina/connector/Request.java
public boolean read() throws IOException { return (inputBuffer.realReadBytes(null, 0, 0) > 0); }
// in java/org/apache/catalina/connector/Request.java
public ServletInputStream createInputStream() throws IOException { if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } return inputStream; }
// in java/org/apache/catalina/connector/Request.java
public void finishRequest() throws IOException { // Optionally disable swallowing of additional request data. Context context = getContext(); if (context != null && response.getStatus() == HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE && !context.getSwallowAbortedUploads()) { coyoteRequest.action(ActionCode.DISABLE_SWALLOW_INPUT, null); } }
// in java/org/apache/catalina/connector/Request.java
Override public ServletInputStream getInputStream() throws IOException { if (usingReader) { throw new IllegalStateException (sm.getString("coyoteRequest.getInputStream.ise")); } usingInputStream = true; if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } return inputStream; }
// in java/org/apache/catalina/connector/Request.java
Override public BufferedReader getReader() throws IOException { if (usingInputStream) { throw new IllegalStateException (sm.getString("coyoteRequest.getReader.ise")); } usingReader = true; inputBuffer.checkConverter(); if (reader == null) { reader = new CoyoteReader(inputBuffer); } return reader; }
// in java/org/apache/catalina/connector/Request.java
Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { if (response.isCommitted()) { throw new IllegalStateException( sm.getString("coyoteRequest.authenticate.ise")); } return context.getAuthenticator().authenticate(this, response); }
// in java/org/apache/catalina/connector/Request.java
Override public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException { parseParts(); if (partsParseException != null) { if (partsParseException instanceof IOException) { throw (IOException) partsParseException; } else if (partsParseException instanceof IllegalStateException) { throw (IllegalStateException) partsParseException; } else if (partsParseException instanceof ServletException) { throw (ServletException) partsParseException; } } return parts; }
// in java/org/apache/catalina/connector/Request.java
Override public Part getPart(String name) throws IOException, IllegalStateException, ServletException { Collection<Part> c = getParts(); Iterator<Part> iterator = c.iterator(); while (iterator.hasNext()) { Part part = iterator.next(); if (name.equals(part.getName())) { return part; } } return null; }
// in java/org/apache/catalina/connector/Request.java
public void doUpgrade(UpgradeInbound inbound) throws IOException { coyoteRequest.action(ActionCode.UPGRADE, inbound); // Output required by RFC2616. Protocol specific headers should have // already been set. response.setStatus(HttpServletResponse.SC_SWITCHING_PROTOCOLS); response.flushBuffer(); }
// in java/org/apache/catalina/connector/Request.java
protected int readPostBody(byte body[], int len) throws IOException { int offset = 0; do { int inputLen = getStream().read(body, offset, len - offset); if (inputLen <= 0) { return offset; } offset += inputLen; } while ((len - offset) > 0); return len; }
// in java/org/apache/catalina/connector/Request.java
protected byte[] readChunkedPostBody() throws IOException { ByteChunk body = new ByteChunk(); byte[] buffer = new byte[CACHED_POST_LEN]; int len = 0; while (len > -1) { len = getStream().read(buffer, 0, CACHED_POST_LEN); if (connector.getMaxPostSize() > 0 && (body.getLength() + len) > connector.getMaxPostSize()) { // Too much data checkSwallowInput(); throw new IOException( sm.getString("coyoteRequest.chunkedPostTooLarge")); } if (len > 0) { body.append(buffer, 0, len); } } if (body.getLength() == 0) { return null; } if (body.getLength() < body.getBuffer().length) { int length = body.getLength(); byte[] result = new byte[length]; System.arraycopy(body.getBuffer(), 0, result, 0, length); return result; } return body.getBuffer(); }
// in java/org/apache/catalina/connector/CoyoteOutputStream.java
Override public void write(int i) throws IOException { ob.writeByte(i); }
// in java/org/apache/catalina/connector/CoyoteOutputStream.java
Override public void write(byte[] b) throws IOException { write(b, 0, b.length); }
// in java/org/apache/catalina/connector/CoyoteOutputStream.java
Override public void write(byte[] b, int off, int len) throws IOException { ob.write(b, off, len); }
// in java/org/apache/catalina/connector/CoyoteOutputStream.java
Override public void flush() throws IOException { ob.flush(); }
// in java/org/apache/catalina/connector/CoyoteOutputStream.java
Override public void close() throws IOException { ob.close(); }
// in java/org/apache/catalina/connector/Response.java
public void finishResponse() throws IOException { // Writing leftover bytes outputBuffer.close(); }
// in java/org/apache/catalina/connector/Response.java
public PrintWriter getReporter() throws IOException { if (outputBuffer.isNew()) { outputBuffer.checkConverter(); if (writer == null) { writer = new CoyoteWriter(outputBuffer); } return writer; } else { return null; } }
// in java/org/apache/catalina/connector/Response.java
Override public void flushBuffer() throws IOException { outputBuffer.flush(); }
// in java/org/apache/catalina/connector/Response.java
Override public ServletOutputStream getOutputStream() throws IOException { if (usingWriter) { throw new IllegalStateException (sm.getString("coyoteResponse.getOutputStream.ise")); } usingOutputStream = true; if (outputStream == null) { outputStream = new CoyoteOutputStream(outputBuffer); } return outputStream; }
// in java/org/apache/catalina/connector/Response.java
Override public PrintWriter getWriter() throws IOException { if (usingOutputStream) { throw new IllegalStateException (sm.getString("coyoteResponse.getWriter.ise")); } if (ENFORCE_ENCODING_IN_GET_WRITER) { /* * If the response's character encoding has not been specified as * described in <code>getCharacterEncoding</code> (i.e., the method * just returns the default value <code>ISO-8859-1</code>), * <code>getWriter</code> updates it to <code>ISO-8859-1</code> * (with the effect that a subsequent call to getContentType() will * include a charset=ISO-8859-1 component which will also be * reflected in the Content-Type response header, thereby satisfying * the Servlet spec requirement that containers must communicate the * character encoding used for the servlet response's writer to the * client). */ setCharacterEncoding(getCharacterEncoding()); } usingWriter = true; outputBuffer.checkConverter(); if (writer == null) { writer = new CoyoteWriter(outputBuffer); } return writer; }
// in java/org/apache/catalina/connector/Response.java
public void sendAcknowledgement() throws IOException { if (isCommitted()) { return; } // Ignore any call from an included servlet if (included) { return; } coyoteResponse.acknowledge(); }
// in java/org/apache/catalina/connector/Response.java
Override public void sendError(int status) throws IOException { sendError(status, null); }
// in java/org/apache/catalina/connector/Response.java
Override public void sendError(int status, String message) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendError.ise")); } // Ignore any call from an included servlet if (included) { return; } Wrapper wrapper = getRequest().getWrapper(); if (wrapper != null) { wrapper.incrementErrorCount(); } setError(); coyoteResponse.setStatus(status); coyoteResponse.setMessage(message); // Clear any data content that has been buffered resetBuffer(); // Cause the response to be finished (from the application perspective) setSuspended(true); }
// in java/org/apache/catalina/connector/Response.java
Override public void sendRedirect(String location) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendRedirect.ise")); } // Ignore any call from an included servlet if (included) { return; } // Clear any data content that has been buffered resetBuffer(true); // Generate a temporary redirect to the specified location try { String absolute = toAbsolute(location); setStatus(SC_FOUND); setHeader("Location", absolute); if (getContext().getSendRedirectBody()) { PrintWriter writer = getWriter(); writer.print(sm.getString("coyoteResponse.sendRedirect.note", RequestUtil.filter(absolute))); flushBuffer(); } } catch (IllegalArgumentException e) { setStatus(SC_NOT_FOUND); } // Cause the response to be finished (from the application perspective) setSuspended(true); }
// in java/org/apache/catalina/connector/Response.java
protected String toAbsolute(String location) { if (location == null) { return (location); } boolean leadingSlash = location.startsWith("/"); if (location.startsWith("//")) { // Scheme relative redirectURLCC.recycle(); // Add the scheme String scheme = request.getScheme(); try { redirectURLCC.append(scheme, 0, scheme.length()); redirectURLCC.append(':'); redirectURLCC.append(location, 0, location.length()); return redirectURLCC.toString(); } catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; } } else if (leadingSlash || !hasScheme(location)) { redirectURLCC.recycle(); String scheme = request.getScheme(); String name = request.getServerName(); int port = request.getServerPort(); try { redirectURLCC.append(scheme, 0, scheme.length()); redirectURLCC.append("://", 0, 3); redirectURLCC.append(name, 0, name.length()); if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443)) { redirectURLCC.append(':'); String portS = port + ""; redirectURLCC.append(portS, 0, portS.length()); } if (!leadingSlash) { String relativePath = request.getDecodedRequestURI(); int pos = relativePath.lastIndexOf('/'); relativePath = relativePath.substring(0, pos); String encodedURI = null; final String frelativePath = relativePath; if (SecurityUtil.isPackageProtectionEnabled() ){ try{ encodedURI = AccessController.doPrivileged( new PrivilegedExceptionAction<String>(){ @Override public String run() throws IOException{ return urlEncoder.encodeURL(frelativePath); } }); } catch (PrivilegedActionException pae){ IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(pae.getException()); throw iae; } } else { encodedURI = urlEncoder.encodeURL(relativePath); } redirectURLCC.append(encodedURI, 0, encodedURI.length()); redirectURLCC.append('/'); } redirectURLCC.append(location, 0, location.length()); normalize(redirectURLCC); } catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; } return redirectURLCC.toString(); }
// in java/org/apache/catalina/connector/Response.java
Override public String run() throws IOException{ return urlEncoder.encodeURL(frelativePath); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public ServletInputStream getInputStream() throws IOException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getInputStream(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public BufferedReader getReader() throws IOException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getReader(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { return request.authenticate(response); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Collection<Part> getParts() throws IllegalStateException, IOException, ServletException { return request.getParts(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Part getPart(String name) throws IllegalStateException, IOException, ServletException { return request.getPart(name); }
// in java/org/apache/catalina/connector/RequestFacade.java
public void doUpgrade(UpgradeInbound inbound) throws IOException { request.doUpgrade(inbound); }
// in java/org/apache/catalina/connector/CometEventImpl.java
Override public void close() throws IOException { if (request == null) { throw new IllegalStateException(sm.getString("cometEvent.nullRequest")); } request.finishRequest(); response.finishResponse(); if (request.isComet()) { request.cometClose(); } }
// in java/org/apache/catalina/connector/CometEventImpl.java
Override public void setTimeout(int timeout) throws IOException, ServletException, UnsupportedOperationException { if (request.getAttribute(Globals.COMET_TIMEOUT_SUPPORTED_ATTR) == Boolean.TRUE) { request.setAttribute(Globals.COMET_TIMEOUT_ATTR, Integer.valueOf(timeout)); if (request.isComet()) { request.setCometTimeout(timeout); } } else { throw new UnsupportedOperationException(); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int read() throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.readByte()); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.readByte()); return integer; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int available() throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.available()); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.available()); return integer; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int read(final byte[] b) throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.read(b, 0, b.length)); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage() ,e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.read(b, 0, b.length)); return integer; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int read(final byte[] b, final int off, final int len) throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.read(b, off, len)); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.read(b, off, len)); return integer; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int readLine(byte[] b, int off, int len) throws IOException { return super.readLine(b, off, len); }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public void close() throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ AccessController.doPrivileged( new PrivilegedExceptionAction<Void>(){ @Override public Void run() throws IOException{ ib.close(); return null; } }); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public Void run() throws IOException{ ib.close(); return null; }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public void close() throws IOException { closed = true; }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int realReadBytes(byte cbuf[], int off, int len) throws IOException { if (closed) { return -1; } if (coyoteRequest == null) { return -1; } if(state == INITIAL_STATE) { state = BYTE_STATE; } int result = coyoteRequest.doRead(bb); return result; }
// in java/org/apache/catalina/connector/InputBuffer.java
public int readByte() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return bb.substract(); }
// in java/org/apache/catalina/connector/InputBuffer.java
public int read(byte[] b, int off, int len) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return bb.substract(b, off, len); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public void realWriteChars(char c[], int off, int len) throws IOException { markPos = -1; cb.setOffset(0); cb.setEnd(0); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int realReadChars(char cbuf[], int off, int len) throws IOException { if (!gotEnc) { setConverter(); } if (bb.getLength() <= 0) { int nRead = realReadBytes(bb.getBytes(), 0, bb.getBytes().length); if (nRead < 0) { return -1; } } if (markPos == -1) { cb.setOffset(0); cb.setEnd(0); } int limit = bb.getLength()+cb.getStart(); if ( cb.getLimit() < limit ) { cb.setLimit(limit); } state = CHAR_STATE; conv.convert(bb, cb, bb.getLength()); bb.setOffset(bb.getEnd()); return cb.getLength(); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int read() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return cb.substract(); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int read(char[] cbuf) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return read(cbuf, 0, cbuf.length); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int read(char[] cbuf, int off, int len) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return cb.substract(cbuf, off, len); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public long skip(long n) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } if (n < 0) { throw new IllegalArgumentException(); } long nRead = 0; while (nRead < n) { if (cb.getLength() >= n) { cb.setOffset(cb.getStart() + (int) n); nRead = n; } else { nRead += cb.getLength(); cb.setOffset(cb.getEnd()); int toRead = 0; if (cb.getChars().length < (n - nRead)) { toRead = cb.getChars().length; } else { toRead = (int) (n - nRead); } int nb = realReadChars(cb.getChars(), 0, toRead); if (nb < 0) { break; } } } return nRead; }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public boolean ready() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return (available() > 0); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public void mark(int readAheadLimit) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } if (cb.getLength() <= 0) { cb.setOffset(0); cb.setEnd(0); } else { if ((cb.getBuffer().length > (2 * size)) && (cb.getLength()) < (cb.getStart())) { System.arraycopy(cb.getBuffer(), cb.getStart(), cb.getBuffer(), 0, cb.getLength()); cb.setEnd(cb.getLength()); cb.setOffset(0); } } cb.setLimit(cb.getStart() + readAheadLimit + size); markPos = cb.getStart(); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public void reset() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } if (state == CHAR_STATE) { if (markPos < 0) { cb.recycle(); markPos = -1; throw new IOException(); } else { cb.setOffset(markPos); } } else { bb.recycle(); } }
// in java/org/apache/catalina/connector/InputBuffer.java
public void checkConverter() throws IOException { if (!gotEnc) { setConverter(); } }
// in java/org/apache/catalina/connector/InputBuffer.java
protected void setConverter() throws IOException { if (coyoteRequest != null) { enc = coyoteRequest.getCharacterEncoding(); } gotEnc = true; if (enc == null) { enc = DEFAULT_ENCODING; } conv = encoders.get(enc); if (conv == null) { if (SecurityUtil.isPackageProtectionEnabled()){ try{ conv = AccessController.doPrivileged( new PrivilegedExceptionAction<B2CConverter>(){ @Override public B2CConverter run() throws IOException { return new B2CConverter(enc); } } ); }catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } } } else { conv = new B2CConverter(enc); } encoders.put(enc, conv); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public B2CConverter run() throws IOException { return new B2CConverter(enc); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public ServletOutputStream getOutputStream() throws IOException { // if (isFinished()) // throw new IllegalStateException // (/*sm.getString("responseFacade.finished")*/); ServletOutputStream sos = response.getOutputStream(); if (isFinished()) { response.setSuspended(true); } return (sos); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public PrintWriter getWriter() throws IOException { // if (isFinished()) // throw new IllegalStateException // (/*sm.getString("responseFacade.finished")*/); PrintWriter writer = response.getWriter(); if (isFinished()) { response.setSuspended(true); } return (writer); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void flushBuffer() throws IOException { if (isFinished()) { // throw new IllegalStateException // (/*sm.getString("responseFacade.finished")*/); return; } if (SecurityUtil.isPackageProtectionEnabled()){ try{ AccessController.doPrivileged( new PrivilegedExceptionAction<Void>(){ @Override public Void run() throws IOException{ response.setAppCommitted(true); response.flushBuffer(); return null; } }); } catch(PrivilegedActionException e){ Exception ex = e.getException(); if (ex instanceof IOException){ throw (IOException)ex; } } }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public Void run() throws IOException{ response.setAppCommitted(true); response.flushBuffer(); return null; }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void sendError(int sc, String msg) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendError.ise")); } response.setAppCommitted(true); response.sendError(sc, msg); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void sendError(int sc) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendError.ise")); } response.setAppCommitted(true); response.sendError(sc); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void sendRedirect(String location) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendRedirect.ise")); } response.setAppCommitted(true); response.sendRedirect(location); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public void close() throws IOException { ib.close(); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public int read() throws IOException { return ib.read(); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public int read(char[] cbuf) throws IOException { return ib.read(cbuf, 0, cbuf.length); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public int read(char[] cbuf, int off, int len) throws IOException { return ib.read(cbuf, off, len); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public long skip(long n) throws IOException { return ib.skip(n); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public boolean ready() throws IOException { return ib.ready(); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public void mark(int readAheadLimit) throws IOException { ib.mark(readAheadLimit); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public void reset() throws IOException { ib.reset(); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public String readLine() throws IOException { if (lineBuffer == null) { lineBuffer = new char[MAX_LINE_LENGTH]; } String result = null; int pos = 0; int end = -1; int skip = -1; StringBuilder aggregator = null; while (end < 0) { mark(MAX_LINE_LENGTH); while ((pos < MAX_LINE_LENGTH) && (end < 0)) { int nRead = read(lineBuffer, pos, MAX_LINE_LENGTH - pos); if (nRead < 0) { if (pos == 0 && aggregator == null) { return null; } end = pos; skip = pos; } for (int i = pos; (i < (pos + nRead)) && (end < 0); i++) { if (lineBuffer[i] == LINE_SEP[0]) { end = i; skip = i + 1; char nextchar; if (i == (pos + nRead - 1)) { nextchar = (char) read(); } else { nextchar = lineBuffer[i+1]; } if (nextchar == LINE_SEP[1]) { skip++; } } else if (lineBuffer[i] == LINE_SEP[1]) { end = i; skip = i + 1; } } if (nRead > 0) { pos += nRead; } } if (end < 0) { if (aggregator == null) { aggregator = new StringBuilder(); } aggregator.append(lineBuffer); pos = 0; } else { reset(); skip(skip); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; try { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<Void>() { @Override public Void run() throws ServletException, IOException { internalDoFilter(req,res); return null; } } ); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public Void run() throws ServletException, IOException { internalDoFilter(req,res); return null; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
private void internalDoFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { // Call the next filter if there is one if (pos < n) { ApplicationFilterConfig filterConfig = filters[pos++]; Filter filter = null; try { filter = filterConfig.getFilter(); support.fireInstanceEvent(InstanceEvent.BEFORE_FILTER_EVENT, filter, request, response); if (request.isAsyncSupported() && "false".equalsIgnoreCase( filterConfig.getFilterDef().getAsyncSupported())) { request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE); } if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; Principal principal = ((HttpServletRequest) req).getUserPrincipal(); Object[] args = new Object[]{req, res, this}; SecurityUtil.doAsPrivilege ("doFilter", filter, classType, args, principal); } else { filter.doFilter(request, response, this); } support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response); } catch (IOException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (ServletException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (RuntimeException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); } return; } // We fell off the end of the chain -- call the servlet instance try { if (ApplicationDispatcher.WRAP_SAME_OBJECT) { lastServicedRequest.set(request); lastServicedResponse.set(response); } support.fireInstanceEvent(InstanceEvent.BEFORE_SERVICE_EVENT, servlet, request, response); if (request.isAsyncSupported() && !support.getWrapper().isAsyncSupported()) { request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE); } // Use potentially wrapped request from this point if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) { if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; Principal principal = ((HttpServletRequest) req).getUserPrincipal(); Object[] args = new Object[]{req, res}; SecurityUtil.doAsPrivilege("service", servlet, classTypeUsedInService, args, principal); } else { servlet.service(request, response); } } else { servlet.service(request, response); } support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response); } catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); } finally { if (ApplicationDispatcher.WRAP_SAME_OBJECT) { lastServicedRequest.set(null); lastServicedResponse.set(null); } } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public void doFilterEvent(CometEvent event) throws IOException, ServletException { if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; try { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<Void>() { @Override public Void run() throws ServletException, IOException { internalDoFilterEvent(ev); return null; } } ); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public Void run() throws ServletException, IOException { internalDoFilterEvent(ev); return null; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
private void internalDoFilterEvent(CometEvent event) throws IOException, ServletException { // Call the next filter if there is one if (pos < n) { ApplicationFilterConfig filterConfig = filters[pos++]; CometFilter filter = null; try { filter = (CometFilter) filterConfig.getFilter(); // FIXME: No instance listener processing for events for now /* support.fireInstanceEvent(InstanceEvent.BEFORE_FILTER_EVENT, filter, event); */ if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; Principal principal = ev.getHttpServletRequest().getUserPrincipal(); Object[] args = new Object[]{ev, this}; SecurityUtil.doAsPrivilege("doFilterEvent", filter, cometClassType, args, principal); } else { filter.doFilterEvent(event, this); } /*support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event);*/ } catch (IOException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (ServletException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (RuntimeException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); } return; } // We fell off the end of the chain -- call the servlet instance try { /* support.fireInstanceEvent(InstanceEvent.BEFORE_SERVICE_EVENT, servlet, request, response); */ if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; Principal principal = ev.getHttpServletRequest().getUserPrincipal(); Object[] args = new Object[]{ ev }; SecurityUtil.doAsPrivilege("event", servlet, classTypeUsedInEvent, args, principal); } else { ((CometProcessor) servlet).event(event); } /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response);*/ } catch (IOException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (ServletException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (RuntimeException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw new ServletException (sm.getString("filterChain.servlet"), e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Initialize local variables we may need boolean unavailable = false; Throwable throwable = null; // This should be a Request attribute... long t1=System.currentTimeMillis(); requestCount++; StandardWrapper wrapper = (StandardWrapper) getContainer(); Servlet servlet = null; Context context = (Context) wrapper.getParent(); // Check for the application being marked unavailable if (!context.getAvailable()) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardContext.isUnavailable")); unavailable = true; } // Check for the servlet being marked unavailable if (!unavailable && wrapper.isUnavailable()) { container.getLogger().info(sm.getString("standardWrapper.isUnavailable", wrapper.getName())); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } unavailable = true; } // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (UnavailableException e) { container.getLogger().error( sm.getString("standardWrapper.allocateException", wrapper.getName()), e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } } catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } // Identify if the request is Comet related now that the servlet has been allocated boolean comet = false; if (servlet instanceof CometProcessor && request.getAttribute( Globals.COMET_SUPPORTED_ATTR) == Boolean.TRUE) { comet = true; request.setComet(true); } MessageBytes requestPathMB = request.getRequestPathMB(); DispatcherType dispatcherType = DispatcherType.REQUEST; if (request.getDispatcherType()==DispatcherType.ASYNC) dispatcherType = DispatcherType.ASYNC; request.setAttribute (ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, dispatcherType); request.setAttribute (ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB); // Create the filter chain for this request ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance(); ApplicationFilterChain filterChain = factory.createFilterChain(request, wrapper, servlet); // Reset comet flag value after creating the filter chain request.setComet(false); // Call the filter chain for this request // NOTE: This also calls the servlet's service() method try { if ((servlet != null) && (filterChain != null)) { // Swallow output if needed if (context.getSwallowOutput()) { try { SystemLogHandler.startCapture(); if (request.isAsyncDispatching()) { //TODO SERVLET3 - async ((AsyncContextImpl)request.getAsyncContext()).doInternalDispatch(); } else if (comet) { filterChain.doFilterEvent(request.getEvent()); request.setComet(true); } else { filterChain.doFilter(request.getRequest(), response.getResponse()); } } finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } } } else { if (request.isAsyncDispatching()) { //TODO SERVLET3 - async ((AsyncContextImpl)request.getAsyncContext()).doInternalDispatch(); } else if (comet) { request.setComet(true); filterChain.doFilterEvent(request.getEvent()); } else { filterChain.doFilter (request.getRequest(), response.getResponse()); } } } } catch (ClientAbortException e) { throwable = e; exception(request, response, e); } catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing } catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } // Release the filter chain (if any) for this request if (filterChain != null) { if (request.isComet()) { // If this is a Comet request, then the same chain will be used for the // processing of all subsequent events. filterChain.reuse(); } else { filterChain.release(); } } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } // If this servlet has been marked permanently unavailable, // unload it and release this instance try { if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) { wrapper.unload(); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } long t2=System.currentTimeMillis(); long time=t2-t1; processingTime += time; if( time > maxTime) maxTime=time; if( time < minTime) minTime=time; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
Override public void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Initialize local variables we may need Throwable throwable = null; // This should be a Request attribute... long t1=System.currentTimeMillis(); // FIXME: Add a flag to count the total amount of events processed ? requestCount++; StandardWrapper wrapper = (StandardWrapper) getContainer(); if (wrapper == null) { // Context has been shutdown. Nothing to do here. return; } Servlet servlet = null; Context context = (Context) wrapper.getParent(); // Check for the application being marked unavailable boolean unavailable = !context.getAvailable() || wrapper.isUnavailable(); // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (UnavailableException e) { // The response is already committed, so it's not possible to do anything } catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } MessageBytes requestPathMB = request.getRequestPathMB(); request.setAttribute (ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, DispatcherType.REQUEST); request.setAttribute (ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB); // Get the current (unchanged) filter chain for this request ApplicationFilterChain filterChain = (ApplicationFilterChain) request.getFilterChain(); // Call the filter chain for this request // NOTE: This also calls the servlet's event() method try { if ((servlet != null) && (filterChain != null)) { // Swallow output if needed if (context.getSwallowOutput()) { try { SystemLogHandler.startCapture(); filterChain.doFilterEvent(request.getEvent()); } finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } } } else { filterChain.doFilterEvent(request.getEvent()); } } } catch (ClientAbortException e) { throwable = e; exception(request, response, e); } catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing } catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } // Release the filter chain (if any) for this request if (filterChain != null) { filterChain.reuse(); } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } // If this servlet has been marked permanently unavailable, // unload it and release this instance try { if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) { wrapper.unload(); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } long t2=System.currentTimeMillis(); long time=t2-t1; processingTime += time; if( time > maxTime) maxTime=time; if( time < minTime) minTime=time; }
// in java/org/apache/catalina/core/ApplicationHttpResponse.java
Override public void sendError(int sc) throws IOException { if (!included) ((HttpServletResponse) getResponse()).sendError(sc); }
// in java/org/apache/catalina/core/ApplicationHttpResponse.java
Override public void sendError(int sc, String msg) throws IOException { if (!included) ((HttpServletResponse) getResponse()).sendError(sc, msg); }
// in java/org/apache/catalina/core/ApplicationHttpResponse.java
Override public void sendRedirect(String location) throws IOException { if (!included) ((HttpServletResponse) getResponse()).sendRedirect(location); }
// in java/org/apache/catalina/core/AsyncListenerWrapper.java
public void fireOnStartAsync(AsyncEvent event) throws IOException { listener.onStartAsync(event); }
// in java/org/apache/catalina/core/AsyncListenerWrapper.java
public void fireOnComplete(AsyncEvent event) throws IOException { listener.onComplete(event); }
// in java/org/apache/catalina/core/AsyncListenerWrapper.java
public void fireOnTimeout(AsyncEvent event) throws IOException { listener.onTimeout(event); }
// in java/org/apache/catalina/core/AsyncListenerWrapper.java
public void fireOnError(AsyncEvent event) throws IOException { listener.onError(event); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
public boolean timeout() throws IOException { AtomicBoolean result = new AtomicBoolean(); request.getCoyoteRequest().action(ActionCode.ASYNC_TIMEOUT, result); if (result.get()) { boolean listenerInvoked = false; List<AsyncListenerWrapper> listenersCopy = new ArrayList<AsyncListenerWrapper>(); listenersCopy.addAll(listeners); for (AsyncListenerWrapper listener : listenersCopy) { listener.fireOnTimeout(event); listenerInvoked = true; } if (listenerInvoked) { request.getCoyoteRequest().action( ActionCode.ASYNC_IS_TIMINGOUT, result); return !result.get(); } else { // No listeners, container calls complete complete(); } } return true; }
// in java/org/apache/catalina/core/AsyncContextImpl.java
protected void doInternalDispatch() throws ServletException, IOException { if (log.isDebugEnabled()) { logDebug("intDispatch"); } try { dispatch.run(); if (!request.isAsync()) { fireOnComplete(); } } catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); } }
// in java/org/apache/catalina/core/StandardContextValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Disallow any direct access to resources under WEB-INF or META-INF MessageBytes requestPathMB = request.getRequestPathMB(); if ((requestPathMB.startsWithIgnoreCase("/META-INF/", 0)) || (requestPathMB.equalsIgnoreCase("/META-INF")) || (requestPathMB.startsWithIgnoreCase("/WEB-INF/", 0)) || (requestPathMB.equalsIgnoreCase("/WEB-INF"))) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Select the Wrapper to be used for this Request Wrapper wrapper = request.getWrapper(); if (wrapper == null || wrapper.isUnavailable()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Acknowledge the request try { response.sendAcknowledgement(); } catch (IOException ioe) { container.getLogger().error(sm.getString( "standardContextValve.acknowledgeException"), ioe); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (request.isAsyncSupported()) { request.setAsyncSupported(wrapper.getPipeline().isAsyncSupported()); } wrapper.getPipeline().getFirst().invoke(request, response); }
// in java/org/apache/catalina/core/StandardContextValve.java
Override public final void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Select the Wrapper to be used for this Request Wrapper wrapper = request.getWrapper(); wrapper.getPipeline().getFirst().event(request, response, event); }
// in java/org/apache/catalina/core/StandardEngineValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Select the Host to be used for this Request Host host = request.getHost(); if (host == null) { response.sendError (HttpServletResponse.SC_BAD_REQUEST, sm.getString("standardEngine.noHost", request.getServerName())); return; } if (request.isAsyncSupported()) { request.setAsyncSupported(host.getPipeline().isAsyncSupported()); } // Ask this Host to process this request host.getPipeline().getFirst().invoke(request, response); }
// in java/org/apache/catalina/core/StandardEngineValve.java
Override public final void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Ask this Host to process this request request.getHost().getPipeline().getFirst().event(request, response, event); }
// in java/org/apache/catalina/core/StandardHostValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Select the Context to be used for this Request Context context = request.getContext(); if (context == null) { response.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, sm.getString("standardHost.noContext")); return; } // Bind the context CL to the current thread if( context.getLoader() != null ) { // Not started - it should check for availability first // This should eventually move to Engine, it's generic. if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( context.getLoader().getClassLoader()); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader (context.getLoader().getClassLoader()); } } if (request.isAsyncSupported()) { request.setAsyncSupported(context.getPipeline().isAsyncSupported()); } // Don't fire listeners during async processing // If a request init listener throws an exception, the request is // aborted boolean asyncAtStart = request.isAsync(); if (asyncAtStart || context.fireRequestInitEvent(request)) { // Ask this Context to process this request try { context.getPipeline().getFirst().invoke(request, response); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); throwable(request, response, t); } // If the request was async at the start and an error occurred then // the async error handling will kick-in and that will fire the // request destroyed event *after* the error handling has taken // place if (!(request.isAsync() || (asyncAtStart && request.getAttribute( RequestDispatcher.ERROR_EXCEPTION) != null))) { // Protect against NPEs if context was destroyed during a long // running request. if (context.getState().isAvailable()) { // Error page processing response.setSuspended(false); Throwable t = (Throwable) request.getAttribute( RequestDispatcher.ERROR_EXCEPTION); if (t != null) { throwable(request, response, t); } else { status(request, response); } context.fireRequestDestroyEvent(request); } } } // Access a session (if present) to update last accessed time, based on a // strict interpretation of the specification if (ACCESS_SESSION) { request.getSession(false); } // Restore the context classloader if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( StandardHostValve.class.getClassLoader()); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader (StandardHostValve.class.getClassLoader()); } }
// in java/org/apache/catalina/core/StandardHostValve.java
Override public final void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Select the Context to be used for this Request Context context = request.getContext(); // Bind the context CL to the current thread if( context.getLoader() != null ) { // Not started - it should check for availability first // This should eventually move to Engine, it's generic. Thread.currentThread().setContextClassLoader (context.getLoader().getClassLoader()); } // Ask this Context to process this request context.getPipeline().getFirst().event(request, response, event); // Error page processing response.setSuspended(false); Throwable t = (Throwable) request.getAttribute( RequestDispatcher.ERROR_EXCEPTION); if (t != null) { throwable(request, response, t); } else { status(request, response); } // Access a session (if present) to update last accessed time, based on a // strict interpretation of the specification if (ACCESS_SESSION) { request.getSession(false); } // Restore the context classloader Thread.currentThread().setContextClassLoader (StandardHostValve.class.getClassLoader()); }
// in java/org/apache/catalina/core/ApplicationPart.java
Override public void delete() throws IOException { fileItem.delete(); }
// in java/org/apache/catalina/core/ApplicationPart.java
Override public InputStream getInputStream() throws IOException { return fileItem.getInputStream(); }
// in java/org/apache/catalina/core/ApplicationPart.java
Override public void write(String fileName) throws IOException { File file = new File(fileName); if (!file.isAbsolute()) { file = new File(mce.getLocation(), fileName); } try { fileItem.write(file); } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
Override public Void run() throws ServletException, IOException { DispatcherType type = DispatcherType.INCLUDE; if (request.getDispatcherType()==DispatcherType.ASYNC) type = DispatcherType.ASYNC; doInclude(request,response,type); return null; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
Override public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (Globals.IS_SECURITY_ENABLED) { try { PrivilegedForward dp = new PrivilegedForward(request,response); AccessController.doPrivileged(dp); } catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; } } else { doForward(request,response); } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void doForward(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Reset any output that has been buffered, but keep headers/cookies if (response.isCommitted()) { throw new IllegalStateException (sm.getString("applicationDispatcher.forward.ise")); } try { response.resetBuffer(); } catch (IllegalStateException e) { throw e; } // Set up to handle the specified request and response State state = new State(request, response, false); if (WRAP_SAME_OBJECT) { // Check SRV.8.2 / SRV.14.2.5.1 compliance checkSameObjects(request, response); } wrapResponse(state); // Handle an HTTP named dispatcher forward if ((servletPath == null) && (pathInfo == null)) { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); HttpServletRequest hrequest = state.hrequest; wrequest.setRequestURI(hrequest.getRequestURI()); wrequest.setContextPath(hrequest.getContextPath()); wrequest.setServletPath(hrequest.getServletPath()); wrequest.setPathInfo(hrequest.getPathInfo()); wrequest.setQueryString(hrequest.getQueryString()); processRequest(request,response,state); } // Handle an HTTP path-based forward else { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); String contextPath = context.getPath(); HttpServletRequest hrequest = state.hrequest; if (hrequest.getAttribute( RequestDispatcher.FORWARD_REQUEST_URI) == null) { wrequest.setAttribute(RequestDispatcher.FORWARD_REQUEST_URI, hrequest.getRequestURI()); wrequest.setAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH, hrequest.getContextPath()); wrequest.setAttribute(RequestDispatcher.FORWARD_SERVLET_PATH, hrequest.getServletPath()); wrequest.setAttribute(RequestDispatcher.FORWARD_PATH_INFO, hrequest.getPathInfo()); wrequest.setAttribute(RequestDispatcher.FORWARD_QUERY_STRING, hrequest.getQueryString()); } wrequest.setContextPath(contextPath); wrequest.setRequestURI(requestURI); wrequest.setServletPath(servletPath); wrequest.setPathInfo(pathInfo); if (queryString != null) { wrequest.setQueryString(queryString); wrequest.setQueryParams(queryString); } processRequest(request,response,state); } // This is not a real close in order to support error processing if (wrapper.getLogger().isDebugEnabled() ) wrapper.getLogger().debug(" Disabling the response for futher output"); if (response instanceof ResponseFacade) { ((ResponseFacade) response).finish(); } else { // Servlet SRV.6.2.2. The Request/Response may have been wrapped // and may no longer be instance of RequestFacade if (wrapper.getLogger().isDebugEnabled()){ wrapper.getLogger().debug( " The Response is vehiculed using a wrapper: " + response.getClass().getName() ); } // Close anyway try { PrintWriter writer = response.getWriter(); writer.close(); } catch (IllegalStateException e) { try { ServletOutputStream stream = response.getOutputStream(); stream.close(); } catch (IllegalStateException f) { // Ignore } catch (IOException f) { // Ignore } } catch (IOException e) { // Ignore } } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void processRequest(ServletRequest request, ServletResponse response, State state) throws IOException, ServletException { DispatcherType disInt = (DispatcherType) request.getAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR); if (disInt != null) { boolean doInvoke = true; if (context.getFireRequestListenersOnForwards() && !context.fireRequestInitEvent(request)) { doInvoke = false; } if (doInvoke) { if (disInt != DispatcherType.ERROR) { state.outerRequest.setAttribute (ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); state.outerRequest.setAttribute (ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, DispatcherType.FORWARD); invoke(state.outerRequest, response, state); } else { invoke(state.outerRequest, response, state); } if (context.getFireRequestListenersOnForwards()) { context.fireRequestDestroyEvent(request); } } } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
Override public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (Globals.IS_SECURITY_ENABLED) { try { PrivilegedInclude dp = new PrivilegedInclude(request,response); AccessController.doPrivileged(dp); } catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; } } else { DispatcherType type = DispatcherType.INCLUDE; if (request.getDispatcherType()==DispatcherType.ASYNC) type = DispatcherType.ASYNC; doInclude(request,response,type); } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void doInclude(ServletRequest request, ServletResponse response, DispatcherType type) throws ServletException, IOException { // Set up to handle the specified request and response State state = new State(request, response, true); if (WRAP_SAME_OBJECT) { // Check SRV.8.2 / SRV.14.2.5.1 compliance checkSameObjects(request, response); } // Create a wrapped response to use for this request wrapResponse(state); // Handle an HTTP named dispatcher include if (name != null) { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); wrequest.setAttribute(Globals.NAMED_DISPATCHER_ATTR, name); if (servletPath != null) wrequest.setServletPath(servletPath); wrequest.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, type); wrequest.setAttribute( ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); invoke(state.outerRequest, state.outerResponse, state); } // Handle an HTTP path based include else { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); String contextPath = context.getPath(); if (requestURI != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_REQUEST_URI, requestURI); if (contextPath != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH, contextPath); if (servletPath != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH, servletPath); if (pathInfo != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_PATH_INFO, pathInfo); if (queryString != null) { wrequest.setAttribute(RequestDispatcher.INCLUDE_QUERY_STRING, queryString); wrequest.setQueryParams(queryString); } wrequest.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, type); wrequest.setAttribute( ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); invoke(state.outerRequest, state.outerResponse, state); } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void invoke(ServletRequest request, ServletResponse response, State state) throws IOException, ServletException { // Checking to see if the context classloader is the current context // classloader. If it's not, we're saving it, and setting the context // classloader to the Context classloader ClassLoader oldCCL = Thread.currentThread().getContextClassLoader(); ClassLoader contextClassLoader = context.getLoader().getClassLoader(); if (oldCCL != contextClassLoader) { Thread.currentThread().setContextClassLoader(contextClassLoader); } else { oldCCL = null; } // Initialize local variables we may need HttpServletResponse hresponse = state.hresponse; Servlet servlet = null; IOException ioException = null; ServletException servletException = null; RuntimeException runtimeException = null; boolean unavailable = false; // Check for the servlet being marked unavailable if (wrapper.isUnavailable()) { wrapper.getLogger().warn( sm.getString("applicationDispatcher.isUnavailable", wrapper.getName())); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) hresponse.setDateHeader("Retry-After", available); hresponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm .getString("applicationDispatcher.isUnavailable", wrapper .getName())); unavailable = true; } // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); servletException = e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servlet = null; } // Get the FilterChain Here ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance(); ApplicationFilterChain filterChain = factory.createFilterChain(request, wrapper,servlet); // Call the service() method for the allocated servlet instance try { support.fireInstanceEvent(InstanceEvent.BEFORE_DISPATCH_EVENT, servlet, request, response); // for includes/forwards if ((servlet != null) && (filterChain != null)) { filterChain.doFilter(request, response); } // Servlet Service Method is called by the FilterChain support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); } catch (ClientAbortException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); ioException = e; } catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); ioException = e; } catch (UnavailableException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); servletException = e; wrapper.unavailable(e); } catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause); } servletException = e; } catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); runtimeException = e; } // Release the filter chain (if any) for this request try { if (filterChain != null) filterChain.release(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e); // FIXME: Exception handling needs to be similar to what is in the StandardWrapperValue } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); } // Reset the old context class loader if (oldCCL != null) Thread.currentThread().setContextClassLoader(oldCCL); // Unwrap request/response if needed // See Bugzilla 30949 unwrapRequest(state); unwrapResponse(state); // Recycle request if necessary (also BZ 30949) recycleRequestWrapper(state); // Rethrow an exception if one was thrown by the invoked servlet if (ioException != null) throw ioException; if (servletException != null) throw servletException; if (runtimeException != null) throw runtimeException; }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
Override public Class<?> resolveClass(ObjectStreamClass classDesc) throws ClassNotFoundException, IOException { try { return Class.forName(classDesc.getName(), false, classLoader); } catch (ClassNotFoundException e) { try { // Try also the superclass because of primitive types return super.resolveClass(classDesc); } catch (ClassNotFoundException e2) { // Rethrow original exception, as it can have more information // about why the class was not found. BZ 48007 throw e; } } }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
Override protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { Class<?>[] cinterfaces = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) cinterfaces[i] = classLoader.loadClass(interfaces[i]); try { return Proxy.getProxyClass(classLoader, cinterfaces); } catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); } }
// in java/org/apache/catalina/util/XMLWriter.java
public void sendData() throws IOException { if (writer != null) { writer.write(buffer.toString()); buffer = new StringBuilder(); } }
// in java/org/apache/catalina/util/Conversions.java
public static long byteArrayToLong(byte[] input) throws IOException { if (input.length > 8) { // TODO: Better message throw new IOException(); } int shift = 0; long result = 0; for (int i = input.length - 1; i >= 0; i--) { result = result + ((input[i] & 0xFF) << shift); shift += 8; } return result; }
// in java/org/apache/catalina/util/IOTools.java
public static void flow( Reader reader, Writer writer, char[] buf ) throws IOException { int numRead; while ( (numRead = reader.read(buf) ) >= 0) { writer.write(buf, 0, numRead); } }
// in java/org/apache/catalina/util/IOTools.java
public static void flow( Reader reader, Writer writer ) throws IOException { char[] buf = new char[DEFAULT_BUFFER_SIZE]; flow( reader, writer, buf ); }
// in java/org/apache/catalina/util/IOTools.java
public static void flow( InputStream is, OutputStream os, byte[] buf ) throws IOException { int numRead; while ( (numRead = is.read(buf) ) >= 0) { os.write(buf, 0, numRead); } }
// in java/org/apache/catalina/util/IOTools.java
public static void flow( InputStream is, OutputStream os ) throws IOException { byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; flow( is, os, buf ); }
// in java/org/apache/catalina/util/ExtensionValidator.java
public static synchronized boolean validateApplication( DirContext dirContext, Context context) throws IOException { String appName = context.getName(); ArrayList<ManifestResource> appManifestResources = new ArrayList<ManifestResource>(); // If the application context is null it does not exist and // therefore is not valid if (dirContext == null) return false; // Find the Manifest for the Web Application InputStream inputStream = null; try { NamingEnumeration<Binding> wne = dirContext.listBindings("/META-INF/"); Binding binding = wne.nextElement(); if (binding.getName().toUpperCase(Locale.ENGLISH).equals("MANIFEST.MF")) { Resource resource = (Resource)dirContext.lookup ("/META-INF/" + binding.getName()); inputStream = resource.streamContent(); Manifest manifest = new Manifest(inputStream); inputStream.close(); inputStream = null; ManifestResource mre = new ManifestResource (sm.getString("extensionValidator.web-application-manifest"), manifest, ManifestResource.WAR); appManifestResources.add(mre); } } catch (NamingException nex) { // Application does not contain a MANIFEST.MF file } catch (NoSuchElementException nse) { // Application does not contain a MANIFEST.MF file } finally { if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } // Locate the Manifests for all bundled JARs NamingEnumeration<Binding> ne = null; try { ne = dirContext.listBindings("WEB-INF/lib/"); while ((ne != null) && ne.hasMoreElements()) { Binding binding = ne.nextElement(); if (!binding.getName().toLowerCase(Locale.ENGLISH).endsWith(".jar")) { continue; } Object obj = dirContext.lookup("/WEB-INF/lib/" + binding.getName()); if (!(obj instanceof Resource)) { // Probably a directory named xxx.jar - ignore it continue; } Resource resource = (Resource) obj; inputStream = resource.streamContent(); Manifest jmanifest = getManifest(inputStream); if (jmanifest != null) { ManifestResource mre = new ManifestResource( binding.getName(), jmanifest, ManifestResource.APPLICATION); appManifestResources.add(mre); } } } catch (NamingException nex) { // Jump out of the check for this application because it // has no resources } finally { if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } return validateManifestResources(appName, appManifestResources); }
// in java/org/apache/catalina/util/ExtensionValidator.java
public static void addSystemResource(File jarFile) throws IOException { Manifest manifest = getManifest(new FileInputStream(jarFile)); if (manifest != null) { ManifestResource mre = new ManifestResource(jarFile.getAbsolutePath(), manifest, ManifestResource.SYSTEM); containerManifestResources.add(mre); } }
// in java/org/apache/catalina/util/ExtensionValidator.java
private static Manifest getManifest(InputStream inStream) throws IOException { Manifest manifest = null; JarInputStream jin = null; try { jin = new JarInputStream(inStream); manifest = jin.getManifest(); jin.close(); jin = null; } finally { if (jin != null) { try { jin.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } return manifest; }
// in java/javax/servlet/jsp/tagext/SimpleTagSupport.java
Override public void doTag() throws JspException, IOException { // NOOP by default }
// in java/javax/servlet/jsp/tagext/BodyContent.java
Override public void flush() throws IOException { throw new IOException("Illegal to flush within a custom tag"); }
// in java/javax/servlet/ServletInputStream.java
public int readLine(byte[] b, int off, int len) throws IOException { if (len <= 0) { return 0; } int count = 0, c; while ((c = read()) != -1) { b[off++] = (byte) c; count++; if (c == '\n' || count == len) { break; } } return count > 0 ? count : -1; }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { return this._getHttpServletRequest().authenticate(response); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public Collection<Part> getParts() throws IllegalStateException, IOException, ServletException { return this._getHttpServletRequest().getParts(); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public Part getPart(String name) throws IllegalStateException, IOException, ServletException { return this._getHttpServletRequest().getPart(name); }
// in java/javax/servlet/http/HttpServletResponseWrapper.java
Override public void sendError(int sc, String msg) throws IOException { this._getHttpServletResponse().sendError(sc, msg); }
// in java/javax/servlet/http/HttpServletResponseWrapper.java
Override public void sendError(int sc) throws IOException { this._getHttpServletResponse().sendError(sc); }
// in java/javax/servlet/http/HttpServletResponseWrapper.java
Override public void sendRedirect(String location) throws IOException { this._getHttpServletResponse().sendRedirect(location); }
// in java/javax/servlet/http/HttpServlet.java
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_get_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { NoBodyResponse response = new NoBodyResponse(resp); doGet(req, response); response.setContentLength(); }
// in java/javax/servlet/http/HttpServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_post_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_put_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_delete_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Method[] methods = getAllDeclaredMethods(this.getClass()); boolean ALLOW_GET = false; boolean ALLOW_HEAD = false; boolean ALLOW_POST = false; boolean ALLOW_PUT = false; boolean ALLOW_DELETE = false; boolean ALLOW_TRACE = true; boolean ALLOW_OPTIONS = true; for (int i=0; i<methods.length; i++) { Method m = methods[i]; if (m.getName().equals("doGet")) { ALLOW_GET = true; ALLOW_HEAD = true; } if (m.getName().equals("doPost")) ALLOW_POST = true; if (m.getName().equals("doPut")) ALLOW_PUT = true; if (m.getName().equals("doDelete")) ALLOW_DELETE = true; } String allow = null; if (ALLOW_GET) allow=METHOD_GET; if (ALLOW_HEAD) if (allow==null) allow=METHOD_HEAD; else allow += ", " + METHOD_HEAD; if (ALLOW_POST) if (allow==null) allow=METHOD_POST; else allow += ", " + METHOD_POST; if (ALLOW_PUT) if (allow==null) allow=METHOD_PUT; else allow += ", " + METHOD_PUT; if (ALLOW_DELETE) if (allow==null) allow=METHOD_DELETE; else allow += ", " + METHOD_DELETE; if (ALLOW_TRACE) if (allow==null) allow=METHOD_TRACE; else allow += ", " + METHOD_TRACE; if (ALLOW_OPTIONS) if (allow==null) allow=METHOD_OPTIONS; else allow += ", " + METHOD_OPTIONS; resp.setHeader("Allow", allow); }
// in java/javax/servlet/http/HttpServlet.java
protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int responseLength; String CRLF = "\r\n"; StringBuilder buffer = new StringBuilder("TRACE ").append(req.getRequestURI()) .append(" ").append(req.getProtocol()); Enumeration<String> reqHeaderEnum = req.getHeaderNames(); while( reqHeaderEnum.hasMoreElements() ) { String headerName = reqHeaderEnum.nextElement(); buffer.append(CRLF).append(headerName).append(": ") .append(req.getHeader(headerName)); } buffer.append(CRLF); responseLength = buffer.length(); resp.setContentType("message/http"); resp.setContentLength(responseLength); ServletOutputStream out = resp.getOutputStream(); out.print(buffer.toString()); out.close(); return; }
// in java/javax/servlet/http/HttpServlet.java
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod(); if (method.equals(METHOD_GET)) { long lastModified = getLastModified(req); if (lastModified == -1) { // servlet doesn't support if-modified-since, no reason // to go through further expensive logic doGet(req, resp); } else { long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE); if (ifModifiedSince < (lastModified / 1000 * 1000)) { // If the servlet mod time is later, call doGet() // Round down to the nearest second for a proper compare // A ifModifiedSince of -1 will always be less maybeSetLastModified(resp, lastModified); doGet(req, resp); } else { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } } } else if (method.equals(METHOD_HEAD)) { long lastModified = getLastModified(req); maybeSetLastModified(resp, lastModified); doHead(req, resp); } else if (method.equals(METHOD_POST)) { doPost(req, resp); } else if (method.equals(METHOD_PUT)) { doPut(req, resp); } else if (method.equals(METHOD_DELETE)) { doDelete(req, resp); } else if (method.equals(METHOD_OPTIONS)) { doOptions(req,resp); } else if (method.equals(METHOD_TRACE)) { doTrace(req,resp); } else { // // Note that this means NO servlet supports whatever // method was requested, anywhere on this server. // String errMsg = lStrings.getString("http.method_not_implemented"); Object[] errArgs = new Object[1]; errArgs[0] = method; errMsg = MessageFormat.format(errMsg, errArgs); resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg); } }
// in java/javax/servlet/http/HttpServlet.java
Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request; HttpServletResponse response; try { request = (HttpServletRequest) req; response = (HttpServletResponse) res; } catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); } service(request, response); }
// in java/javax/servlet/http/HttpServlet.java
Override public ServletOutputStream getOutputStream() throws IOException { return noBody; }
// in java/javax/servlet/http/HttpServlet.java
Override public void write(byte buf[], int offset, int len) throws IOException { if (len >= 0) { contentLength += len; } else { // XXX // isn't this really an IllegalArgumentException? String msg = lStrings.getString("err.io.negativelength"); throw new IOException(msg); } }
// in java/javax/servlet/ServletResponseWrapper.java
Override public ServletOutputStream getOutputStream() throws IOException { return this.response.getOutputStream(); }
// in java/javax/servlet/ServletResponseWrapper.java
Override public PrintWriter getWriter() throws IOException { return this.response.getWriter(); }
// in java/javax/servlet/ServletResponseWrapper.java
Override public void flushBuffer() throws IOException { this.response.flushBuffer(); }
// in java/javax/servlet/ServletOutputStream.java
public void print(String s) throws IOException { if (s == null) s = "null"; int len = s.length(); for (int i = 0; i < len; i++) { char c = s.charAt(i); // // XXX NOTE: This is clearly incorrect for many strings, // but is the only consistent approach within the current // servlet framework. It must suffice until servlet output // streams properly encode their output. // if ((c & 0xff00) != 0) { // high order byte must be zero String errMsg = lStrings.getString("err.not_iso8859_1"); Object[] errArgs = new Object[1]; errArgs[0] = Character.valueOf(c); errMsg = MessageFormat.format(errMsg, errArgs); throw new CharConversionException(errMsg); } write(c); } }
// in java/javax/servlet/ServletOutputStream.java
public void print(boolean b) throws IOException { String msg; if (b) { msg = lStrings.getString("value.true"); } else { msg = lStrings.getString("value.false"); } print(msg); }
// in java/javax/servlet/ServletOutputStream.java
public void print(char c) throws IOException { print(String.valueOf(c)); }
// in java/javax/servlet/ServletOutputStream.java
public void print(int i) throws IOException { print(String.valueOf(i)); }
// in java/javax/servlet/ServletOutputStream.java
public void print(long l) throws IOException { print(String.valueOf(l)); }
// in java/javax/servlet/ServletOutputStream.java
public void print(float f) throws IOException { print(String.valueOf(f)); }
// in java/javax/servlet/ServletOutputStream.java
public void print(double d) throws IOException { print(String.valueOf(d)); }
// in java/javax/servlet/ServletOutputStream.java
public void println() throws IOException { print("\r\n"); }
// in java/javax/servlet/ServletOutputStream.java
public void println(String s) throws IOException { print(s); println(); }
// in java/javax/servlet/ServletOutputStream.java
public void println(boolean b) throws IOException { print(b); println(); }
// in java/javax/servlet/ServletOutputStream.java
public void println(char c) throws IOException { print(c); println(); }
// in java/javax/servlet/ServletOutputStream.java
public void println(int i) throws IOException { print(i); println(); }
// in java/javax/servlet/ServletOutputStream.java
public void println(long l) throws IOException { print(l); println(); }
// in java/javax/servlet/ServletOutputStream.java
public void println(float f) throws IOException { print(f); println(); }
// in java/javax/servlet/ServletOutputStream.java
public void println(double d) throws IOException { print(d); println(); }
// in java/javax/servlet/ServletRequestWrapper.java
Override public ServletInputStream getInputStream() throws IOException { return this.request.getInputStream(); }
// in java/javax/servlet/ServletRequestWrapper.java
Override public BufferedReader getReader() throws IOException { return this.request.getReader(); }
(Lib) IllegalStateException 196
              
// in java/org/apache/jasper/tagplugins/jstl/Util.java
Override public PrintWriter getWriter() { if (isStreamUsed) throw new IllegalStateException("Unexpected internal error during &lt;import&gt: " + "Target servlet called getWriter(), then getOutputStream()"); isWriterUsed = true; return new PrintWriter(sw); }
// in java/org/apache/jasper/tagplugins/jstl/Util.java
Override public ServletOutputStream getOutputStream() { if (isWriterUsed) throw new IllegalStateException("Unexpected internal error during &lt;import&gt: " + "Target servlet called getOutputStream(), then getWriter()"); isStreamUsed = true; return sos; }
// in java/org/apache/jasper/runtime/ServletResponseWrapperInclude.java
Override public ServletOutputStream getOutputStream() throws IOException { throw new IllegalStateException(); }
// in java/org/apache/jasper/runtime/InstanceManagerFactory.java
public static InstanceManager getInstanceManager(ServletConfig config) { InstanceManager instanceManager = (InstanceManager) config.getServletContext().getAttribute(InstanceManager.class.getName()); if (instanceManager == null) { throw new IllegalStateException("No org.apache.tomcat.InstanceManager set in ServletContext"); } return instanceManager; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void _initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) { // initialize state this.servlet = servlet; this.config = servlet.getServletConfig(); this.context = config.getServletContext(); this.errorPageURL = errorPageURL; this.request = request; this.response = response; // initialize application context this.applicationContext = JspApplicationContextImpl.getInstance(context); // Setup session (if required) if (request instanceof HttpServletRequest && needsSession) this.session = ((HttpServletRequest) request).getSession(); if (needsSession && session == null) throw new IllegalStateException( "Page needs a session and none is available"); // initialize the initial out ... depth = -1; if (this.baseOut == null) { this.baseOut = new JspWriterImpl(response, bufferSize, autoFlush); } else { this.baseOut.init(response, bufferSize, autoFlush); } this.out = baseOut; // register names/values as per spec setAttribute(OUT, this.out); setAttribute(REQUEST, request); setAttribute(RESPONSE, response); if (session != null) setAttribute(SESSION, session); setAttribute(PAGE, servlet); setAttribute(CONFIG, config); setAttribute(PAGECONTEXT, this); setAttribute(APPLICATION, context); isIncluded = request.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH) != null; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private Object doGetAttribute(String name, int scope) { switch (scope) { case PAGE_SCOPE: return attributes.get(name); case REQUEST_SCOPE: return request.getAttribute(name); case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } return session.getAttribute(name); case APPLICATION_SCOPE: return context.getAttribute(name); default: throw new IllegalArgumentException("Invalid scope"); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doSetAttribute(String name, Object o, int scope) { if (o != null) { switch (scope) { case PAGE_SCOPE: attributes.put(name, o); break; case REQUEST_SCOPE: request.setAttribute(name, o); break; case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } session.setAttribute(name, o); break; case APPLICATION_SCOPE: context.setAttribute(name, o); break; default: throw new IllegalArgumentException("Invalid scope"); } } else { removeAttribute(name, scope); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doRemoveAttribute(String name, int scope) { switch (scope) { case PAGE_SCOPE: attributes.remove(name); break; case REQUEST_SCOPE: request.removeAttribute(name); break; case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } session.removeAttribute(name); break; case APPLICATION_SCOPE: context.removeAttribute(name); break; default: throw new IllegalArgumentException("Invalid scope"); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private Enumeration<String> doGetAttributeNamesInScope(int scope) { switch (scope) { case PAGE_SCOPE: return Collections.enumeration(attributes.keySet()); case REQUEST_SCOPE: return request.getAttributeNames(); case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } return session.getAttributeNames(); case APPLICATION_SCOPE: return context.getAttributeNames(); default: throw new IllegalArgumentException("Invalid scope"); } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public final void clear() throws IOException { if ((bufferSize == 0) && (out != null)) // clear() is illegal after any unbuffered output (JSP.5.5) throw new IllegalStateException( getLocalizeMessage("jsp.error.ise_on_clear")); if (flushed) throw new IOException( getLocalizeMessage("jsp.error.attempt_to_clear_flushed_buffer")); ensureOpen(); nextChar = 0; }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void clearBuffer() throws IOException { if (bufferSize == 0) throw new IllegalStateException( getLocalizeMessage("jsp.error.ise_on_clear")); ensureOpen(); nextChar = 0; }
// in java/org/apache/jasper/runtime/JspApplicationContextImpl.java
Override public void addELResolver(ELResolver resolver) throws IllegalStateException { if (resolver == null) { throw new IllegalArgumentException("ELResolver was null"); } if (this.instantiated) { throw new IllegalStateException( "cannot call addELResolver after the first request has been made"); } this.resolvers.add(resolver); }
// in java/org/apache/jasper/compiler/SmapGenerator.java
public synchronized String getString() { // check state and initialize buffer if (outputFileName == null) throw new IllegalStateException(); StringBuilder out = new StringBuilder(); // start the SMAP out.append("SMAP\n"); out.append(outputFileName + '\n'); out.append(defaultStratum + '\n'); // include embedded SMAPs if (doEmbedded) { int nEmbedded = embedded.size(); for (int i = 0; i < nEmbedded; i++) { out.append(embedded.get(i)); } } // print our StratumSections, FileSections, and LineSections int nStrata = strata.size(); for (int i = 0; i < nStrata; i++) { SmapStratum s = strata.get(i); out.append(s.getString()); } // end the SMAP out.append("*E\n"); return out.toString(); }
// in java/org/apache/jasper/compiler/SmapStratum.java
public String getString() { if (inputStartLine == -1 || outputStartLine == -1) throw new IllegalStateException(); StringBuilder out = new StringBuilder(); out.append(inputStartLine); if (lineFileIDSet) out.append("#" + lineFileID); if (inputLineCount != 1) out.append("," + inputLineCount); out.append(":" + outputStartLine); if (outputLineIncrement != 1) out.append("," + outputLineIncrement); out.append('\n'); return out.toString(); }
// in java/org/apache/jasper/JspCompilationContext.java
public Compiler createCompiler() { if (jspCompiler != null ) { return jspCompiler; } jspCompiler = null; if (options.getCompilerClassName() != null) { jspCompiler = createCompiler(options.getCompilerClassName()); } else { if (options.getCompiler() == null) { jspCompiler = createCompiler("org.apache.jasper.compiler.JDTCompiler"); if (jspCompiler == null) { jspCompiler = createCompiler("org.apache.jasper.compiler.AntCompiler"); } } else { jspCompiler = createCompiler("org.apache.jasper.compiler.AntCompiler"); if (jspCompiler == null) { jspCompiler = createCompiler("org.apache.jasper.compiler.JDTCompiler"); } } } if (jspCompiler == null) { throw new IllegalStateException(Localizer.getMessage("jsp.error.compiler")); } jspCompiler.init(this, jsw); return jspCompiler; }
// in java/org/apache/jasper/JspCompilationContext.java
protected void createOutputDir() { String path = null; if (isTagFile()) { String tagName = tagInfo.getTagClassName(); path = tagName.replace('.', File.separatorChar); path = path.substring(0, path.lastIndexOf(File.separatorChar)); } else { path = getServletPackageName().replace('.',File.separatorChar); } // Append servlet or tag handler path to scratch dir try { File base = options.getScratchDir(); baseUrl = base.toURI().toURL(); outputDir = base.getAbsolutePath() + File.separator + path + File.separator; if (!makeOutputDir()) { throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder")); } } catch (MalformedURLException e) { throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"), e); } }
// in java/org/apache/naming/resources/DirContextURLStreamHandler.java
public static DirContext get() { DirContext result = null; Thread currentThread = Thread.currentThread(); ClassLoader currentCL = currentThread.getContextClassLoader(); // Checking CL binding result = clBindings.get(currentCL); if (result != null) return result; // Checking thread biding result = threadBindings.get(currentThread); // Checking parent CL binding currentCL = currentCL.getParent(); while (currentCL != null) { result = clBindings.get(currentCL); if (result != null) return result; currentCL = currentCL.getParent(); } if (result == null) throw new IllegalStateException("Illegal class loader binding"); return result; }
// in java/org/apache/coyote/Response.java
public void reset() throws IllegalStateException { // Reset the headers only if this is the main request, // not for included contentType = null; locale = DEFAULT_LOCALE; contentLanguage = null; characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; contentLength = -1; charsetSet = false; status = 200; message = null; headers.clear(); // Force the PrintWriter to flush its data to the output // stream before resetting the output stream // // Reset the stream if (commited) { //String msg = sm.getString("servletOutputStreamImpl.reset.ise"); throw new IllegalStateException(); } action(ActionCode.RESET, this); }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public void setSslSupport(SSLSupport sslSupport) { // Should never reach this code but in case we do... throw new IllegalStateException( sm.getString("ajpprocessor.ssl.notsupported")); }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public UpgradeInbound getUpgradeInbound() { // Should never reach this code but in case we do... throw new IllegalStateException( sm.getString("ajpprocessor.httpupgrade.notsupported")); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableDataOnly) throws IOException { //check state if ( !parsingRequestLine ) return true; // // Skipping blank lines // if ( parsingRequestLinePhase == 0 ) { byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (useAvailableDataOnly) { return false; } // Ignore bytes that were read pos = lastValid = 0; // Do a simple read with a short timeout if ( readSocket(true, false)==0 ) return false; } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; if (pos >= skipBlankLinesSize) { // Move data, to have enough space for further reading // of headers and body System.arraycopy(buf, pos, buf, 0, lastValid - pos); lastValid -= pos; pos = 0; } skipBlankLinesBytes = pos; parsingRequestLineStart = pos; parsingRequestLinePhase = 2; if (log.isDebugEnabled()) { log.debug("Received [" + new String(buf, pos, lastValid - pos, DEFAULT_CHARSET) + "]"); } } if ( parsingRequestLinePhase == 2 ) { // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, parsingRequestLineStart, pos - parsingRequestLineStart); } pos++; } parsingRequestLinePhase = 3; } if ( parsingRequestLinePhase == 3 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 4; } if (parsingRequestLinePhase == 4) { // Mark the current buffer position int end = 0; // // Reading the URI // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request parsingRequestLineEol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (parsingRequestLineQPos == -1)) { parsingRequestLineQPos = pos; } pos++; } request.unparsedURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); if (parsingRequestLineQPos >= 0) { request.queryString().setBytes(buf, parsingRequestLineQPos + 1, end - parsingRequestLineQPos - 1); request.requestURI().setBytes(buf, parsingRequestLineStart, parsingRequestLineQPos - parsingRequestLineStart); } else { request.requestURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } parsingRequestLinePhase = 5; } if ( parsingRequestLinePhase == 5 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 6; } if (parsingRequestLinePhase == 6) { // Mark the current buffer position end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!parsingRequestLineEol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; parsingRequestLineEol = true; } pos++; } if ( (end - parsingRequestLineStart) > 0) { request.protocol().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } else { request.protocol().setString(""); } parsingRequestLine = false; parsingRequestLinePhase = 0; parsingRequestLineEol = false; parsingRequestLineStart = 0; return true; } throw new IllegalStateException("Invalid request line parse phase:"+parsingRequestLinePhase); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } HeaderParseStatus status = HeaderParseStatus.HAVE_MORE_HEADERS; do { status = parseHeader(); } while ( status == HeaderParseStatus.HAVE_MORE_HEADERS ); if (status == HeaderParseStatus.DONE) { parsingHeader = false; end = pos; // Checking that // (1) Headers plus request line size does not exceed its limit // (2) There are enough bytes to avoid expanding the buffer when // reading body // Technically, (2) is technical limitation, (1) is logical // limitation to enforce the meaning of headerBufferSize // From the way how buf is allocated and how blank lines are being // read, it should be enough to check (1) only. if (end - skipBlankLinesBytes > headerBufferSize || buf.length - end < socketReadBufferSize) { throw new IllegalArgumentException( sm.getString("iib.requestheadertoolarge.error")); } return true; } else { return false; } }
// in java/org/apache/coyote/http11/filters/BufferedInputFilter.java
Override public void setRequest(Request request) { // save off the Request body try { while (buffer.doRead(tempRead, request) >= 0) { buffered.append(tempRead); tempRead.recycle(); } } catch(IOException ioe) { // No need for i18n - this isn't going to get logged anywhere throw new IllegalStateException( "Request body too large for buffer"); } }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } while (parseHeader()) { // Loop until we run out of headers } parsingHeader = false; end = pos; return true; }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } while (parseHeader()) { // Loop until there are no more headers } parsingHeader = false; end = pos; return true; }
// in java/org/apache/coyote/http11/AbstractOutputBuffer.java
public void reset() { if (committed) throw new IllegalStateException(/*FIXME:Put an error message*/); // Recycle Request object response.recycle(); }
// in java/org/apache/coyote/http11/AbstractOutputBuffer.java
private void checkLengthBeforeWrite(int length) throws IllegalStateException { if (pos + length > buf.length) { throw new IllegalStateException( sm.getString("iob.responseheadertoolarge.error")); } }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized void asyncStart(AsyncContextCallback asyncCtxt) { if (state == AsyncState.DISPATCHED) { state = AsyncState.STARTING; this.asyncCtxt = asyncCtxt; } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncStart()", state)); } }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized SocketState asyncPostProcess() { if (state == AsyncState.STARTING) { state = AsyncState.STARTED; return SocketState.LONG; } else if (state == AsyncState.MUST_COMPLETE) { asyncCtxt.fireOnComplete(); state = AsyncState.DISPATCHED; return SocketState.ASYNC_END; } else if (state == AsyncState.COMPLETING) { asyncCtxt.fireOnComplete(); state = AsyncState.DISPATCHED; return SocketState.ASYNC_END; } else if (state == AsyncState.MUST_DISPATCH) { state = AsyncState.DISPATCHING; return SocketState.ASYNC_END; } else if (state == AsyncState.DISPATCHING) { state = AsyncState.DISPATCHED; return SocketState.ASYNC_END; } else if (state == AsyncState.ERROR) { asyncCtxt.fireOnComplete(); state = AsyncState.DISPATCHED; return SocketState.ASYNC_END; //} else if (state == AsyncState.DISPATCHED) { // // No state change // return SocketState.OPEN; } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncPostProcess()", state)); } }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized boolean asyncComplete() { boolean doComplete = false; if (state == AsyncState.STARTING) { state = AsyncState.MUST_COMPLETE; } else if (state == AsyncState.STARTED) { state = AsyncState.COMPLETING; doComplete = true; } else if (state == AsyncState.TIMING_OUT || state == AsyncState.ERROR) { state = AsyncState.MUST_COMPLETE; } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncComplete()", state)); } return doComplete; }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized boolean asyncTimeout() { if (state == AsyncState.STARTED) { state = AsyncState.TIMING_OUT; return true; } else if (state == AsyncState.COMPLETING || state == AsyncState.DISPATCHED) { // NOOP - App called complete between the the timeout firing and // execution reaching this point return false; } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncTimeout()", state)); } }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized boolean asyncDispatch() { boolean doDispatch = false; if (state == AsyncState.STARTING) { state = AsyncState.MUST_DISPATCH; } else if (state == AsyncState.STARTED || state == AsyncState.TIMING_OUT) { state = AsyncState.DISPATCHING; doDispatch = true; } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncDispatch()", state)); } return doDispatch; }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized void asyncDispatched() { if (state == AsyncState.DISPATCHING) { state = AsyncState.DISPATCHED; } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncDispatched()", state)); } }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized void asyncError() { if (state == AsyncState.DISPATCHED || state == AsyncState.TIMING_OUT) { state = AsyncState.ERROR; } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncError()", state)); } }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized void asyncRun(Runnable runnable) { if (state == AsyncState.STARTING || state == AsyncState.STARTED) { // Execute the runnable using a container thread from the // Connector's thread pool. Use a wrapper to prevent a memory leak ClassLoader oldCL; if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<ClassLoader> pa = new PrivilegedGetTccl(); oldCL = AccessController.doPrivileged(pa); } else { oldCL = Thread.currentThread().getContextClassLoader(); } try { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( this.getClass().getClassLoader()); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader( this.getClass().getClassLoader()); } processor.getExecutor().execute(runnable); } finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( oldCL); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldCL); } } } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncRun()", state)); } }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int handshake(boolean read, boolean write) throws IOException { if ( handshakeComplete ) return 0; //we have done our initial handshake if (!flush(netOutBuffer)) return SelectionKey.OP_WRITE; //we still have data to write SSLEngineResult handshake = null; while (!handshakeComplete) { switch ( handshakeStatus ) { case NOT_HANDSHAKING: { //should never happen throw new IOException("NOT_HANDSHAKING during handshake"); } case FINISHED: { //we are complete if we have delivered the last package handshakeComplete = !netOutBuffer.hasRemaining(); //return 0 if we are complete, otherwise we still have data to write return handshakeComplete?0:SelectionKey.OP_WRITE; } case NEED_WRAP: { //perform the wrap function handshake = handshakeWrap(write); if ( handshake.getStatus() == Status.OK ){ if (handshakeStatus == HandshakeStatus.NEED_TASK) handshakeStatus = tasks(); } else { //wrap should always work with our buffers throw new IOException("Unexpected status:" + handshake.getStatus() + " during handshake WRAP."); } if ( handshakeStatus != HandshakeStatus.NEED_UNWRAP || (!flush(netOutBuffer)) ) { //should actually return OP_READ if we have NEED_UNWRAP return SelectionKey.OP_WRITE; } //fall down to NEED_UNWRAP on the same call, will result in a //BUFFER_UNDERFLOW if it needs data } //$FALL-THROUGH$ case NEED_UNWRAP: { //perform the unwrap function handshake = handshakeUnwrap(read); if ( handshake.getStatus() == Status.OK ) { if (handshakeStatus == HandshakeStatus.NEED_TASK) handshakeStatus = tasks(); } else if ( handshake.getStatus() == Status.BUFFER_UNDERFLOW ){ //read more data, reregister for OP_READ return SelectionKey.OP_READ; } else { throw new IOException("Invalid handshake status:"+handshakeStatus+" during handshake UNWRAP."); }//switch break; } case NEED_TASK: { handshakeStatus = tasks(); break; } default: throw new IllegalStateException("Invalid handshake status:"+handshakeStatus); }//switch }//while //return 0 if we are complete, otherwise reregister for any activity that //would cause this method to be called again. return handshakeComplete?0:(SelectionKey.OP_WRITE|SelectionKey.OP_READ); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int read(ByteBuffer dst) throws IOException { //if we want to take advantage of the expand function, make sure we only use the ApplicationBufferHandler's buffers if ( dst != bufHandler.getReadBuffer() ) throw new IllegalArgumentException("You can only read using the application read buffer provided by the handler."); //are we in the middle of closing or closed? if ( closing || closed) return -1; //did we finish our handshake? if (!handshakeComplete) throw new IllegalStateException("Handshake incomplete, you must complete handshake before reading data."); //read from the network int netread = sc.read(netInBuffer); //did we reach EOF? if so send EOF up one layer. if (netread == -1) return -1; //the data read int read = 0; //the SSL engine result SSLEngineResult unwrap; do { //prepare the buffer netInBuffer.flip(); //unwrap the data unwrap = sslEngine.unwrap(netInBuffer, dst); //compact the buffer netInBuffer.compact(); if ( unwrap.getStatus()==Status.OK || unwrap.getStatus()==Status.BUFFER_UNDERFLOW ) { //we did receive some data, add it to our total read += unwrap.bytesProduced(); //perform any tasks if needed if (unwrap.getHandshakeStatus() == HandshakeStatus.NEED_TASK) tasks(); //if we need more network data, then bail out for now. if ( unwrap.getStatus() == Status.BUFFER_UNDERFLOW ) break; }else if ( unwrap.getStatus()==Status.BUFFER_OVERFLOW && read>0 ) { //buffer overflow can happen, if we have read data, then //empty out the dst buffer before we do another read break; }else { //here we should trap BUFFER_OVERFLOW and call expand on the buffer //for now, throw an exception, as we initialized the buffers //in the constructor throw new IOException("Unable to unwrap data, invalid status: " + unwrap.getStatus()); } } while ( (netInBuffer.position() != 0)); //continue to unwrapping as long as the input buffer has stuff return (read); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
protected CountDownLatch resetLatch(CountDownLatch latch) { if ( latch==null || latch.getCount() == 0 ) return null; else throw new IllegalStateException("Latch must be at count 0"); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
protected CountDownLatch startLatch(CountDownLatch latch, int cnt) { if ( latch == null || latch.getCount() == 0 ) { return new CountDownLatch(cnt); } else throw new IllegalStateException("Latch must be at count 0 or null."); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
protected void awaitLatch(CountDownLatch latch, long timeout, TimeUnit unit) throws InterruptedException { if ( latch == null ) throw new IllegalStateException("Latch cannot be null"); latch.await(timeout,unit); }
// in java/org/apache/tomcat/util/http/Parameters.java
public void addParameter( String key, String value ) throws IllegalStateException { if( key==null ) { return; } parameterCount ++; if (limit > -1 && parameterCount > limit) { // Processing this parameter will push us over the limit. ISE is // what Request.parseParts() uses for requests that are too big parseFailed = true; throw new IllegalStateException(sm.getString( "parameters.maxCountFail", Integer.valueOf(limit))); } ArrayList<String> values = paramHashValues.get(key); if (values == null) { values = new ArrayList<String>(1); paramHashValues.put(key, values); } values.add(value); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
private int parseEndOfLine(String headerPart, int end) { int index = end; for (;;) { int offset = headerPart.indexOf('\r', index); if (offset == -1 || offset + 1 >= headerPart.length()) { throw new IllegalStateException( "Expected headers to be terminated by an empty line."); } if (headerPart.charAt(offset + 1) == '\n') { return offset; } index = offset + 1; } }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public InputStream openStream() throws IOException { if (opened) { throw new IllegalStateException( "The stream was already opened."); } if (((Closeable) stream).isClosed()) { throw new FileItemStream.ItemSkippedException(); } return stream; }
// in java/org/apache/tomcat/util/http/fileupload/FileCleaningTracker.java
private synchronized void addTracker(String path, Object marker, FileDeleteStrategy deleteStrategy) { // synchronized block protects reaper if (exitWhenFinished) { throw new IllegalStateException("No new trackers can be added once exitWhenFinished() is called"); } if (reaper == null) { reaper = new Reaper(); reaper.start(); } trackers.add(new Tracker(path, deleteStrategy, marker, q)); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantValue.java
Override public final String toString() { Constant c = constant_pool.getConstant(constantvalue_index); String buf; int i; // Print constant to string depending on its type switch (c.getTag()) { case Constants.CONSTANT_Long: buf = String.valueOf(((ConstantLong) c).getBytes()); break; case Constants.CONSTANT_Float: buf = String.valueOf(((ConstantFloat) c).getBytes()); break; case Constants.CONSTANT_Double: buf = String.valueOf(((ConstantDouble) c).getBytes()); break; case Constants.CONSTANT_Integer: buf = String.valueOf(((ConstantInteger) c).getBytes()); break; case Constants.CONSTANT_String: i = ((ConstantString) c).getStringIndex(); c = constant_pool.getConstant(i, Constants.CONSTANT_Utf8); buf = "\"" + Utility.convertString(((ConstantUtf8) c).getBytes()) + "\""; break; default: throw new IllegalStateException("Type of ConstValue invalid: " + c); } return buf; }
// in java/org/apache/tomcat/util/bcel/classfile/Attribute.java
public static final Attribute readAttribute(DataInputStream file, ConstantPool constant_pool) throws IOException, ClassFormatException { ConstantUtf8 c; String name; int name_index; int length; byte tag = Constants.ATTR_UNKNOWN; // Unknown attribute // Get class name from constant pool via `name_index' indirection name_index = file.readUnsignedShort(); c = (ConstantUtf8) constant_pool.getConstant(name_index, Constants.CONSTANT_Utf8); name = c.getBytes(); // Length of data in bytes length = file.readInt(); // Compare strings to find known attribute // System.out.println(name); for (byte i = 0; i < Constants.KNOWN_ATTRIBUTES; i++) { if (name.equals(Constants.ATTRIBUTE_NAMES[i])) { tag = i; // found! break; } } // Call proper constructor, depending on `tag' switch (tag) { case Constants.ATTR_UNKNOWN: AttributeReader r = readers.get(name); if (r != null) { return r.createAttribute(name_index, length, file, constant_pool); } return new Unknown(name_index, length, file, constant_pool); case Constants.ATTR_CONSTANT_VALUE: return new ConstantValue(name_index, length, file, constant_pool); case Constants.ATTR_SOURCE_FILE: return new SourceFile(name_index, length, file, constant_pool); case Constants.ATTR_CODE: return new Code(name_index, length, file, constant_pool); case Constants.ATTR_EXCEPTIONS: return new ExceptionTable(name_index, length, file, constant_pool); case Constants.ATTR_LINE_NUMBER_TABLE: return new LineNumberTable(name_index, length, file, constant_pool); case Constants.ATTR_LOCAL_VARIABLE_TABLE: return new LocalVariableTable(name_index, length, file, constant_pool); case Constants.ATTR_INNER_CLASSES: return new InnerClasses(name_index, length, file, constant_pool); case Constants.ATTR_SYNTHETIC: return new Synthetic(name_index, length, file, constant_pool); case Constants.ATTR_DEPRECATED: return new Deprecated(name_index, length, file, constant_pool); case Constants.ATTR_PMG: return new PMGClass(name_index, length, file, constant_pool); case Constants.ATTR_SIGNATURE: return new Signature(name_index, length, file, constant_pool); case Constants.ATTR_STACK_MAP: return new StackMap(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIME_VISIBLE_ANNOTATIONS: return new RuntimeVisibleAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIMEIN_VISIBLE_ANNOTATIONS: return new RuntimeInvisibleAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS: return new RuntimeVisibleParameterAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIMEIN_VISIBLE_PARAMETER_ANNOTATIONS: return new RuntimeInvisibleParameterAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_ANNOTATION_DEFAULT: return new AnnotationDefault(name_index, length, file, constant_pool); case Constants.ATTR_LOCAL_VARIABLE_TYPE_TABLE: return new LocalVariableTypeTable(name_index, length, file, constant_pool); case Constants.ATTR_ENCLOSING_METHOD: return new EnclosingMethod(name_index, length, file, constant_pool); case Constants.ATTR_STACK_MAP_TABLE: return new StackMapTable(name_index, length, file, constant_pool); default: // Never reached throw new IllegalStateException("Unrecognized attribute type tag parsed: " + tag); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (log.isDebugEnabled()) log.debug("loadClass(" + name + ", " + resolve + ")"); Class<?> clazz = null; // Log access to stopped classloader if (!started) { try { throw new IllegalStateException(); } catch (IllegalStateException e) { log.info(sm.getString("webappClassLoader.stopped", name), e); } } // (0) Check our previously loaded local class cache clazz = findLoadedClass0(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.1) Check our previously loaded class cache clazz = findLoadedClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.2) Try loading the class with the system class loader, to prevent // the webapp from overriding J2SE classes try { clazz = system.loadClass(name); if (clazz != null) { if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (0.5) Permission to access this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { securityManager.checkPackageAccess(name.substring(0,i)); } catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); } } } boolean delegateLoad = delegate || filter(name); // (1) Delegate to our parent if requested if (delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader1 " + parent); ClassLoader loader = parent; if (loader == null) loader = system; try { clazz = Class.forName(name, false, loader); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } // (2) Search local repositories if (log.isDebugEnabled()) log.debug(" Searching local repositories"); try { clazz = findClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from local repository"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (3) Delegate to parent unconditionally if (!delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader at end: " + parent); ClassLoader loader = parent; if (loader == null) loader = system; try { clazz = Class.forName(name, false, loader); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } throw new ClassNotFoundException(name); }
// in java/org/apache/catalina/realm/RealmBase.java
protected String getDigest(String username, String realmName) { if (md5Helper == null) { try { md5Helper = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("Couldn't get MD5 digest: ", e); throw new IllegalStateException(e.getMessage()); } } if (hasMessageDigest()) { // Use pre-generated digest return getPassword(username); } String digestValue = username + ":" + realmName + ":" + getPassword(username); byte[] valueBytes = null; try { valueBytes = digestValue.getBytes(getDigestCharset()); } catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); } byte[] digest = null; // Bugzilla 32137 synchronized(md5Helper) { digest = md5Helper.digest(valueBytes); } return md5Encoder.encode(digest); }
// in java/org/apache/catalina/realm/RealmBase.java
static AllRolesMode toMode(String name) { AllRolesMode mode; if( name.equalsIgnoreCase(STRICT_MODE.name) ) mode = STRICT_MODE; else if( name.equalsIgnoreCase(AUTH_ONLY_MODE.name) ) mode = AUTH_ONLY_MODE; else if( name.equalsIgnoreCase(STRICT_AUTH_ONLY_MODE.name) ) mode = STRICT_AUTH_ONLY_MODE; else throw new IllegalStateException("Unknown mode, must be one of: strict, authOnly, strictAuthOnly"); return mode; }
// in java/org/apache/catalina/filters/ExpiresFilter.java
protected Date getExpirationDate(ExpiresConfiguration configuration, XHttpServletResponse response) { Calendar calendar; switch (configuration.getStartingPoint()) { case ACCESS_TIME: calendar = Calendar.getInstance(); break; case LAST_MODIFICATION_TIME: if (response.isLastModifiedHeaderSet()) { try { long lastModified = response.getLastModifiedHeader(); calendar = Calendar.getInstance(); calendar.setTimeInMillis(lastModified); } catch (NumberFormatException e) { // default to now calendar = Calendar.getInstance(); } } else { // Last-Modified header not found, use now calendar = Calendar.getInstance(); } break; default: throw new IllegalStateException(sm.getString( "expiresFilter.unsupportedStartingPoint", configuration.getStartingPoint())); } for (Duration duration : configuration.getDurations()) { calendar.add(duration.getUnit().getCalendardField(), duration.getAmount()); } return calendar.getTime(); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
protected ExpiresConfiguration parseExpiresConfiguration(String inputLine) { String line = inputLine.trim(); StringTokenizer tokenizer = new StringTokenizer(line, " "); String currentToken; try { currentToken = tokenizer.nextToken(); } catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "expiresFilter.startingPointNotFound", line)); } StartingPoint startingPoint; if ("access".equalsIgnoreCase(currentToken) || "now".equalsIgnoreCase(currentToken)) { startingPoint = StartingPoint.ACCESS_TIME; } else if ("modification".equalsIgnoreCase(currentToken)) { startingPoint = StartingPoint.LAST_MODIFICATION_TIME; } else if (!tokenizer.hasMoreTokens() && startsWithIgnoreCase(currentToken, "a")) { startingPoint = StartingPoint.ACCESS_TIME; // trick : convert duration configuration from old to new style tokenizer = new StringTokenizer(currentToken.substring(1) + " seconds", " "); } else if (!tokenizer.hasMoreTokens() && startsWithIgnoreCase(currentToken, "m")) { startingPoint = StartingPoint.LAST_MODIFICATION_TIME; // trick : convert duration configuration from old to new style tokenizer = new StringTokenizer(currentToken.substring(1) + " seconds", " "); } else { throw new IllegalStateException(sm.getString( "expiresFilter.startingPointInvalid", currentToken, line)); } try { currentToken = tokenizer.nextToken(); } catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); } if ("plus".equalsIgnoreCase(currentToken)) { // skip try { currentToken = tokenizer.nextToken(); } catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); } } List<Duration> durations = new ArrayList<Duration>(); while (currentToken != null) { int amount; try { amount = Integer.parseInt(currentToken); } catch (NumberFormatException e) { throw new IllegalStateException(sm.getString( "Invalid duration (number) '{}' in directive '{}'", currentToken, line)); } try { currentToken = tokenizer.nextToken(); } catch (NoSuchElementException e) { throw new IllegalStateException( sm.getString( "Duration unit not found after amount {} in directive '{}'", Integer.valueOf(amount), line)); } DurationUnit durationUnit; if ("years".equalsIgnoreCase(currentToken)) { durationUnit = DurationUnit.YEAR; } else if ("month".equalsIgnoreCase(currentToken) || "months".equalsIgnoreCase(currentToken)) { durationUnit = DurationUnit.MONTH; } else if ("week".equalsIgnoreCase(currentToken) || "weeks".equalsIgnoreCase(currentToken)) { durationUnit = DurationUnit.WEEK; } else if ("day".equalsIgnoreCase(currentToken) || "days".equalsIgnoreCase(currentToken)) { durationUnit = DurationUnit.DAY; } else if ("hour".equalsIgnoreCase(currentToken) || "hours".equalsIgnoreCase(currentToken)) { durationUnit = DurationUnit.HOUR; } else if ("minute".equalsIgnoreCase(currentToken) || "minutes".equalsIgnoreCase(currentToken)) { durationUnit = DurationUnit.MINUTE; } else if ("second".equalsIgnoreCase(currentToken) || "seconds".equalsIgnoreCase(currentToken)) { durationUnit = DurationUnit.SECOND; } else { throw new IllegalStateException( sm.getString( "Invalid duration unit (years|months|weeks|days|hours|minutes|seconds) '{}' in directive '{}'", currentToken, line)); } Duration duration = new Duration(amount, durationUnit); durations.add(duration); if (tokenizer.hasMoreTokens()) { currentToken = tokenizer.nextToken(); } else { currentToken = null; } } return new ExpiresConfiguration(startingPoint, durations); }
// in java/org/apache/catalina/tribes/group/interceptors/FragmentationInterceptor.java
public ChannelMessage assemble() { if ( !complete() ) throw new IllegalStateException("Fragments are missing."); int buffersize = 0; for (int i=0; i<frags.length; i++ ) buffersize += frags[i].getLength(); XByteBuffer buf = new XByteBuffer(buffersize,false); msg.setMessage(buf); for ( int i=0; i<frags.length; i++ ) { msg.getMessage().append(frags[i].getBytesDirect(),0,frags[i].getLength()); } return msg; }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public XByteBuffer extractDataPackage(boolean clearFromBuffer) { int psize = countPackages(true); if (psize == 0) { throw new java.lang.IllegalStateException("No package exists in XByteBuffer"); } int size = toInt(buf, START_DATA.length); XByteBuffer xbuf = BufferPool.getBufferPool().getBuffer(size,false); xbuf.setLength(size); System.arraycopy(buf, START_DATA.length + 4, xbuf.getBytesDirect(), 0, size); if (clearFromBuffer) { int totalsize = START_DATA.length + 4 + size + END_DATA.length; bufSize = bufSize - totalsize; System.arraycopy(buf, totalsize, buf, 0, bufSize); } return xbuf; }
// in java/org/apache/catalina/tribes/transport/PooledSender.java
public synchronized DataSender getSender(long timeout) { long start = System.currentTimeMillis(); while ( true ) { if (!isOpen)throw new IllegalStateException("Queue is closed"); DataSender sender = null; if (notinuse.size() == 0 && inuse.size() < limit) { sender = parent.getNewDataSender(); } else if (notinuse.size() > 0) { sender = notinuse.remove(0); } if (sender != null) { inuse.add(sender); return sender; }//end if long delta = System.currentTimeMillis() - start; if ( delta > timeout && timeout>0) return null; else { try { wait(Math.max(timeout - delta,1)); }catch (InterruptedException x){} }//end if } }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public synchronized void start(int level) throws IOException { boolean valid = false; if ( (level & Channel.MBR_RX_SEQ)==Channel.MBR_RX_SEQ ) { if ( receiver != null ) throw new IllegalStateException("McastService.receive already running."); try { if ( sender == null ) socket.joinGroup(address); }catch (IOException iox) { log.error("Unable to join multicast group, make sure your system has multicasting enabled."); throw iox; } doRunReceiver = true; receiver = new ReceiverThread(); receiver.setDaemon(true); receiver.start(); valid = true; } if ( (level & Channel.MBR_TX_SEQ)==Channel.MBR_TX_SEQ ) { if ( sender != null ) throw new IllegalStateException("McastService.send already running."); if ( receiver == null ) socket.joinGroup(address); //make sure at least one packet gets out there send(false); doRunSender = true; sender = new SenderThread(sendFrequency); sender.setDaemon(true); sender.start(); //we have started the receiver, but not yet waited for membership to establish valid = true; } if (!valid) { throw new IllegalArgumentException("Invalid start level. Only acceptable levels are Channel.MBR_RX_SEQ and Channel.MBR_TX_SEQ"); } //pause, once or twice waitForMembers(level); startLevel = (startLevel | level); }
// in java/org/apache/catalina/session/ManagerBase.java
Override public Session createSession(String sessionId) { if ((maxActiveSessions >= 0) && (getActiveSessions() >= maxActiveSessions)) { rejectedSessions++; throw new IllegalStateException( sm.getString("managerBase.createSession.ise")); } // Recycle or create a Session instance Session session = createEmptySession(); // Initialize the properties of the new session and return it session.setNew(true); session.setValid(true); session.setCreationTime(System.currentTimeMillis()); session.setMaxInactiveInterval(this.maxInactiveInterval); String id = sessionId; if (id == null) { id = generateSessionId(); } session.setId(id); sessionCounter++; SessionTiming timing = new SessionTiming(session.getCreationTime(), 0); synchronized (sessionCreationTiming) { sessionCreationTiming.add(timing); sessionCreationTiming.poll(); } return (session); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
protected Session swapIn(String id) throws IOException { if (store == null) return null; Object swapInLock = null; /* * The purpose of this sync and these locks is to make sure that a * session is only loaded once. It doesn't matter if the lock is removed * and then another thread enters this method and tries to load the same * session. That thread will re-create a swapIn lock for that session, * quickly find that the session is already in sessions, use it and * carry on. */ synchronized (this) { swapInLock = sessionSwapInLocks.get(id); if (swapInLock == null) { swapInLock = new Object(); sessionSwapInLocks.put(id, swapInLock); } } Session session = null; synchronized (swapInLock) { // First check to see if another thread has loaded the session into // the manager session = sessions.get(id); if (session == null) { try { if (SecurityUtil.isPackageProtectionEnabled()){ try { session = AccessController.doPrivileged( new PrivilegedStoreLoad(id)); } catch (PrivilegedActionException ex) { Exception e = ex.getException(); log.error(sm.getString( "persistentManager.swapInException", id), e); if (e instanceof IOException){ throw (IOException)e; } else if (e instanceof ClassNotFoundException) { throw (ClassNotFoundException)e; } } } else { session = store.load(id); } } catch (ClassNotFoundException e) { String msg = sm.getString( "persistentManager.deserializeError", id); log.error(msg, e); throw new IllegalStateException(msg, e); } if (session != null && !session.isValid()) { log.error(sm.getString( "persistentManager.swapInInvalid", id)); session.expire(); removeSession(id); session = null; } if (session != null) { if(log.isDebugEnabled()) log.debug(sm.getString("persistentManager.swapIn", id)); session.setManager(this); // make sure the listeners know about it. ((StandardSession)session).tellNew(); add(session); ((StandardSession)session).activate(); // endAccess() to ensure timeouts happen correctly. // access() to keep access count correct or it will end up // negative session.access(); session.endAccess(); } } } // Make sure the lock is removed synchronized (this) { sessionSwapInLocks.remove(id); } return (session); }
// in java/org/apache/catalina/session/StandardSession.java
Override public long getThisAccessedTime() { if (!isValidInternal()) { throw new IllegalStateException (sm.getString("standardSession.getThisAccessedTime.ise")); } return (this.thisAccessedTime); }
// in java/org/apache/catalina/session/StandardSession.java
Override public long getLastAccessedTime() { if (!isValidInternal()) { throw new IllegalStateException (sm.getString("standardSession.getLastAccessedTime.ise")); } return (this.lastAccessedTime); }
// in java/org/apache/catalina/session/StandardSession.java
Override public long getCreationTime() { if (!isValidInternal()) throw new IllegalStateException (sm.getString("standardSession.getCreationTime.ise")); return (this.creationTime); }
// in java/org/apache/catalina/session/StandardSession.java
Override public Object getAttribute(String name) { if (!isValidInternal()) throw new IllegalStateException (sm.getString("standardSession.getAttribute.ise")); if (name == null) return null; return (attributes.get(name)); }
// in java/org/apache/catalina/session/StandardSession.java
Override public Enumeration<String> getAttributeNames() { if (!isValidInternal()) throw new IllegalStateException (sm.getString("standardSession.getAttributeNames.ise")); Set<String> names = new HashSet<String>(); names.addAll(attributes.keySet()); return Collections.enumeration(names); }
// in java/org/apache/catalina/session/StandardSession.java
Override public void invalidate() { if (!isValidInternal()) throw new IllegalStateException (sm.getString("standardSession.invalidate.ise")); // Cause this session to expire expire(); }
// in java/org/apache/catalina/session/StandardSession.java
Override public boolean isNew() { if (!isValidInternal()) throw new IllegalStateException (sm.getString("standardSession.isNew.ise")); return (this.isNew); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException { boolean serveContent = content; // Identify the requested resource path String path = getRelativePath(request); if (debug > 0) { if (serveContent) log("DefaultServlet.serveResource: Serving resource '" + path + "' headers and data"); else log("DefaultServlet.serveResource: Serving resource '" + path + "' headers only"); } CacheEntry cacheEntry = resources.lookupCache(path); if (!cacheEntry.exists) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } else { // We're included // SRV.9.3 says we must throw a FNFE throw new FileNotFoundException( sm.getString("defaultServlet.missingResource", requestUri)); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } // If the resource is not a collection, and the resource path // ends with "/" or "\", return NOT FOUND if (cacheEntry.context == null) { if (path.endsWith("/") || (path.endsWith("\\"))) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } } boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST; // Check if the conditions specified in the optional If headers are // satisfied. if (cacheEntry.context == null) { // Checking If headers boolean included = (request.getAttribute( RequestDispatcher.INCLUDE_CONTEXT_PATH) != null); if (!included && !isError && !checkIfHeaders(request, response, cacheEntry.attributes)) { return; } } // Find content type. String contentType = cacheEntry.attributes.getMimeType(); if (contentType == null) { contentType = getServletContext().getMimeType(cacheEntry.name); cacheEntry.attributes.setMimeType(contentType); } ArrayList<Range> ranges = null; long contentLength = -1L; if (cacheEntry.context != null) { // Skip directory listings if we have been configured to // suppress them if (!listings) { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); return; } contentType = "text/html;charset=UTF-8"; } else { if (!isError) { if (useAcceptRanges) { // Accept ranges header response.setHeader("Accept-Ranges", "bytes"); } // Parse range specifier ranges = parseRange(request, response, cacheEntry.attributes); // ETag header response.setHeader("ETag", cacheEntry.attributes.getETag()); // Last-Modified header response.setHeader("Last-Modified", cacheEntry.attributes.getLastModifiedHttp()); } // Get content length contentLength = cacheEntry.attributes.getContentLength(); // Special case for zero length files, which would cause a // (silent) ISE when setting the output buffer size if (contentLength == 0L) { serveContent = false; } } ServletOutputStream ostream = null; PrintWriter writer = null; if (serveContent) { // Trying to retrieve the servlet output stream try { ostream = response.getOutputStream(); } catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } } } // Check to see if a Filter, Valve of wrapper has written some content. // If it has, disable range requests and setting of a content length // since neither can be done reliably. ServletResponse r = response; long contentWritten = 0; while (r instanceof ServletResponseWrapper) { r = ((ServletResponseWrapper) r).getResponse(); } if (r instanceof ResponseFacade) { contentWritten = ((ResponseFacade) r).getContentWritten(); } if (contentWritten > 0) { ranges = FULL; } if ( (cacheEntry.context != null) || isError || ( ((ranges == null) || (ranges.isEmpty())) && (request.getHeader("Range") == null) ) || (ranges == FULL) ) { // Set the appropriate output headers if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if ((cacheEntry.resource != null) && (contentLength >= 0) && (!serveContent || ostream != null)) { if (debug > 0) log("DefaultServlet.serveFile: contentLength=" + contentLength); // Don't set a content length if something else has already // written to the response. if (contentWritten == 0) { if (contentLength < Integer.MAX_VALUE) { response.setContentLength((int) contentLength); } else { // Set the content-length as String to be able to use a // long response.setHeader("content-length", "" + contentLength); } } } InputStream renderResult = null; if (cacheEntry.context != null) { if (serveContent) { // Serve the directory browser renderResult = render(getPathPrefix(request), cacheEntry); } } // Copy the input stream to our output stream (if requested) if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, contentLength, null)) copy(cacheEntry, renderResult, ostream); } else { copy(cacheEntry, renderResult, writer); } } } else { if ((ranges == null) || (ranges.isEmpty())) return; // Partial content response. response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); if (ranges.size() == 1) { Range range = ranges.get(0); response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; if (length < Integer.MAX_VALUE) { response.setContentLength((int) length); } else { // Set the content-length as String to be able to use a long response.setHeader("content-length", "" + length); } if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, range.end - range.start + 1, range)) copy(cacheEntry, ostream, range); } else { // we should not get here throw new IllegalStateException(); } } } else { response.setContentType("multipart/byteranges; boundary=" + mimeSeparation); if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { copy(cacheEntry, ostream, ranges.iterator(), contentType); } else { // we should not get here throw new IllegalStateException(); } } } } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
public void removeAttribute(String name, boolean notify,boolean addDeltaRequest) { // Validate our current state if (!isValid()) throw new IllegalStateException(sm.getString("standardSession.removeAttribute.ise")); removeAttributeInternal(name, notify, addDeltaRequest); }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
Override public PrintWriter getWriter() throws java.io.IOException { if (servletOutputStream == null) { if (printWriter == null) { setCharacterEncoding(getCharacterEncoding()); printWriter = new PrintWriter( new OutputStreamWriter(captureServletOutputStream, getCharacterEncoding())); } return printWriter; } throw new IllegalStateException(); }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
Override public ServletOutputStream getOutputStream() throws java.io.IOException { if (printWriter == null) { if (servletOutputStream == null) { servletOutputStream = captureServletOutputStream; } return servletOutputStream; } throw new IllegalStateException(); }
// in java/org/apache/catalina/connector/Request.java
Override public ServletInputStream getInputStream() throws IOException { if (usingReader) { throw new IllegalStateException (sm.getString("coyoteRequest.getInputStream.ise")); } usingInputStream = true; if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } return inputStream; }
// in java/org/apache/catalina/connector/Request.java
Override public BufferedReader getReader() throws IOException { if (usingInputStream) { throw new IllegalStateException (sm.getString("coyoteRequest.getReader.ise")); } usingReader = true; inputBuffer.checkConverter(); if (reader == null) { reader = new CoyoteReader(inputBuffer); } return reader; }
// in java/org/apache/catalina/connector/Request.java
Override public AsyncContext startAsync(ServletRequest request, ServletResponse response) { if (!isAsyncSupported()) { throw new IllegalStateException("Not supported."); } if (asyncContext == null) { asyncContext = new AsyncContextImpl(this); } asyncContext.setStarted(getContext(), request, response, request==getRequest() && response==getResponse().getResponse()); asyncContext.setTimeout(getConnector().getAsyncTimeout()); return asyncContext; }
// in java/org/apache/catalina/connector/Request.java
Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { if (response.isCommitted()) { throw new IllegalStateException( sm.getString("coyoteRequest.authenticate.ise")); } return context.getAuthenticator().authenticate(this, response); }
// in java/org/apache/catalina/connector/Request.java
private void parseParts() { // Return immediately if the parts have already been parsed if (parts != null || partsParseException != null) { return; } MultipartConfigElement mce = getWrapper().getMultipartConfigElement(); if (mce == null) { if(getContext().getAllowCasualMultipartParsing()) { mce = new MultipartConfigElement(null, connector.getMaxPostSize(), connector.getMaxPostSize(), connector.getMaxPostSize()); } else { parts = Collections.emptyList(); return; } } Parameters parameters = coyoteRequest.getParameters(); parameters.setLimit(getConnector().getMaxParameterCount()); boolean success = false; try { File location; String locationStr = mce.getLocation(); if (locationStr == null || locationStr.length() == 0) { location = ((File) context.getServletContext().getAttribute( ServletContext.TEMPDIR)); } else { // If relative, it is relative to TEMPDIR location = new File(locationStr); if (!location.isAbsolute()) { location = new File( (File) context.getServletContext().getAttribute( ServletContext.TEMPDIR), locationStr).getAbsoluteFile(); } } if (!location.isDirectory()) { partsParseException = new IOException( sm.getString("coyoteRequest.uploadLocationInvalid", location)); return; } // Create a new file upload handler DiskFileItemFactory factory = new DiskFileItemFactory(); try { factory.setRepository(location.getCanonicalFile()); } catch (IOException ioe) { partsParseException = ioe; return; } factory.setSizeThreshold(mce.getFileSizeThreshold()); ServletFileUpload upload = new ServletFileUpload(); upload.setFileItemFactory(factory); upload.setFileSizeMax(mce.getMaxFileSize()); upload.setSizeMax(mce.getMaxRequestSize()); parts = new ArrayList<Part>(); try { List<FileItem> items = upload.parseRequest(this); int maxPostSize = getConnector().getMaxPostSize(); int postSize = 0; String enc = getCharacterEncoding(); Charset charset = null; if (enc != null) { try { charset = B2CConverter.getCharset(enc); } catch (UnsupportedEncodingException e) { // Ignore } } for (FileItem item : items) { ApplicationPart part = new ApplicationPart(item, mce); parts.add(part); if (part.getFilename() == null) { String name = part.getName(); String value = null; try { String encoding = parameters.getEncoding(); if (encoding == null) { encoding = Parameters.DEFAULT_ENCODING; } value = part.getString(encoding); } catch (UnsupportedEncodingException uee) { try { value = part.getString(Parameters.DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { // Should not be possible } } if (maxPostSize > 0) { // Have to calculate equivalent size. Not completely // accurate but close enough. if (charset == null) { // Name length postSize += name.getBytes().length; } else { postSize += name.getBytes(charset).length; } if (value != null) { // Equals sign postSize++; // Value length postSize += part.getSize(); } // Value separator postSize++; if (postSize > maxPostSize) { throw new IllegalStateException(sm.getString( "coyoteRequest.maxPostSizeExceeded")); } } parameters.addParameter(name, value); } } success = true; } catch (InvalidContentTypeException e) { partsParseException = new ServletException(e); } catch (FileUploadBase.SizeException e) { checkSwallowInput(); partsParseException = new IllegalStateException(e); } catch (FileUploadException e) { partsParseException = new IOException(e); } catch (IllegalStateException e) { checkSwallowInput(); partsParseException = e; } } finally { if (partsParseException != null || !success) { parameters.setParseFailed(true); } } }
// in java/org/apache/catalina/connector/Request.java
protected Session doGetSession(boolean create) { // There cannot be a session if no context has been assigned yet if (context == null) { return (null); } // Return the current session if it exists and is valid if ((session != null) && !session.isValid()) { session = null; } if (session != null) { return (session); } // Return the requested session if it exists and is valid Manager manager = null; if (context != null) { manager = context.getManager(); } if (manager == null) { return (null); // Sessions are not supported } if (requestedSessionId != null) { try { session = manager.findSession(requestedSessionId); } catch (IOException e) { session = null; } if ((session != null) && !session.isValid()) { session = null; } if (session != null) { session.access(); return (session); } } // Create a new session if requested and the response is not committed if (!create) { return (null); } if ((context != null) && (response != null) && context.getServletContext().getEffectiveSessionTrackingModes(). contains(SessionTrackingMode.COOKIE) && response.getResponse().isCommitted()) { throw new IllegalStateException (sm.getString("coyoteRequest.sessionCreateCommitted")); } // Attempt to reuse session id if one was submitted in a cookie // Do not reuse the session id if it is from a URL, to prevent possible // phishing attacks // Use the SSL session ID if one is present. if (("/".equals(context.getSessionCookiePath()) && isRequestedSessionIdFromCookie()) || requestedSessionSSL ) { session = manager.createSession(getRequestedSessionId()); } else { session = manager.createSession(null); } // Creating a new session cookie based on that session if ((session != null) && (getContext() != null) && getContext().getServletContext(). getEffectiveSessionTrackingModes().contains( SessionTrackingMode.COOKIE)) { Cookie cookie = ApplicationSessionCookieConfig.createSessionCookie( context, session.getIdInternal(), isSecure()); response.addSessionCookieInternal(cookie); } if (session == null) { return null; } session.access(); return session; }
// in java/org/apache/catalina/connector/Response.java
Override public ServletOutputStream getOutputStream() throws IOException { if (usingWriter) { throw new IllegalStateException (sm.getString("coyoteResponse.getOutputStream.ise")); } usingOutputStream = true; if (outputStream == null) { outputStream = new CoyoteOutputStream(outputBuffer); } return outputStream; }
// in java/org/apache/catalina/connector/Response.java
Override public PrintWriter getWriter() throws IOException { if (usingOutputStream) { throw new IllegalStateException (sm.getString("coyoteResponse.getWriter.ise")); } if (ENFORCE_ENCODING_IN_GET_WRITER) { /* * If the response's character encoding has not been specified as * described in <code>getCharacterEncoding</code> (i.e., the method * just returns the default value <code>ISO-8859-1</code>), * <code>getWriter</code> updates it to <code>ISO-8859-1</code> * (with the effect that a subsequent call to getContentType() will * include a charset=ISO-8859-1 component which will also be * reflected in the Content-Type response header, thereby satisfying * the Servlet spec requirement that containers must communicate the * character encoding used for the servlet response's writer to the * client). */ setCharacterEncoding(getCharacterEncoding()); } usingWriter = true; outputBuffer.checkConverter(); if (writer == null) { writer = new CoyoteWriter(outputBuffer); } return writer; }
// in java/org/apache/catalina/connector/Response.java
public void resetBuffer(boolean resetWriterStreamFlags) { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.resetBuffer.ise")); } outputBuffer.reset(resetWriterStreamFlags); if(resetWriterStreamFlags) { usingOutputStream = false; usingWriter = false; isCharacterEncodingSet = false; } }
// in java/org/apache/catalina/connector/Response.java
Override public void setBufferSize(int size) { if (isCommitted() || !outputBuffer.isNew()) { throw new IllegalStateException (sm.getString("coyoteResponse.setBufferSize.ise")); } outputBuffer.setBufferSize(size); }
// in java/org/apache/catalina/connector/Response.java
Override public void sendError(int status, String message) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendError.ise")); } // Ignore any call from an included servlet if (included) { return; } Wrapper wrapper = getRequest().getWrapper(); if (wrapper != null) { wrapper.incrementErrorCount(); } setError(); coyoteResponse.setStatus(status); coyoteResponse.setMessage(message); // Clear any data content that has been buffered resetBuffer(); // Cause the response to be finished (from the application perspective) setSuspended(true); }
// in java/org/apache/catalina/connector/Response.java
Override public void sendRedirect(String location) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendRedirect.ise")); } // Ignore any call from an included servlet if (included) { return; } // Clear any data content that has been buffered resetBuffer(true); // Generate a temporary redirect to the specified location try { String absolute = toAbsolute(location); setStatus(SC_FOUND); setHeader("Location", absolute); if (getContext().getSendRedirectBody()) { PrintWriter writer = getWriter(); writer.print(sm.getString("coyoteResponse.sendRedirect.note", RequestUtil.filter(absolute))); flushBuffer(); } } catch (IllegalArgumentException e) { setStatus(SC_NOT_FOUND); } // Cause the response to be finished (from the application perspective) setSuspended(true); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Object getAttribute(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getAttribute(name); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Enumeration<String> getAttributeNames() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetAttributePrivilegedAction()); } else { return request.getAttributeNames(); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getCharacterEncoding() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetCharacterEncodingPrivilegedAction()); } else { return request.getCharacterEncoding(); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public void setCharacterEncoding(String env) throws java.io.UnsupportedEncodingException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } request.setCharacterEncoding(env); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public int getContentLength() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getContentLength(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getContentType() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getContentType(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public ServletInputStream getInputStream() throws IOException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getInputStream(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getParameter(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetParameterPrivilegedAction(name)); } else { return request.getParameter(name); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Enumeration<String> getParameterNames() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetParameterNamesPrivilegedAction()); } else { return request.getParameterNames(); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String[] getParameterValues(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } String[] ret = null; /* * Clone the returned array only if there is a security manager * in place, so that performance won't suffer in the non-secure case */ if (SecurityUtil.isPackageProtectionEnabled()){ ret = AccessController.doPrivileged( new GetParameterValuePrivilegedAction(name)); if (ret != null) { ret = ret.clone(); } } else { ret = request.getParameterValues(name); } return ret; }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Map<String,String[]> getParameterMap() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetParameterMapPrivilegedAction()); } else { return request.getParameterMap(); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getProtocol() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getProtocol(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getScheme() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getScheme(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getServerName() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getServerName(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public int getServerPort() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getServerPort(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public BufferedReader getReader() throws IOException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getReader(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getRemoteAddr() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRemoteAddr(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getRemoteHost() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRemoteHost(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public void setAttribute(String name, Object o) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } request.setAttribute(name, o); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public void removeAttribute(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } request.removeAttribute(name); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Locale getLocale() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetLocalePrivilegedAction()); } else { return request.getLocale(); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Enumeration<Locale> getLocales() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetLocalesPrivilegedAction()); } else { return request.getLocales(); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean isSecure() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isSecure(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public RequestDispatcher getRequestDispatcher(String path) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetRequestDispatcherPrivilegedAction(path)); } else { return request.getRequestDispatcher(path); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getRealPath(String path) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRealPath(path); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getAuthType() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getAuthType(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Cookie[] getCookies() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } Cookie[] ret = null; /* * Clone the returned array only if there is a security manager * in place, so that performance won't suffer in the non-secure case */ if (SecurityUtil.isPackageProtectionEnabled()){ ret = AccessController.doPrivileged( new GetCookiesPrivilegedAction()); if (ret != null) { ret = ret.clone(); } } else { ret = request.getCookies(); } return ret; }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public long getDateHeader(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getDateHeader(name); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getHeader(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getHeader(name); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Enumeration<String> getHeaders(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetHeadersPrivilegedAction(name)); } else { return request.getHeaders(name); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Enumeration<String> getHeaderNames() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetHeaderNamesPrivilegedAction()); } else { return request.getHeaderNames(); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public int getIntHeader(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getIntHeader(name); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getMethod() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getMethod(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getPathInfo() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getPathInfo(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getPathTranslated() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getPathTranslated(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getContextPath() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getContextPath(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getQueryString() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getQueryString(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getRemoteUser() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRemoteUser(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean isUserInRole(String role) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isUserInRole(role); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public java.security.Principal getUserPrincipal() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getUserPrincipal(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getRequestedSessionId() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRequestedSessionId(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getRequestURI() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRequestURI(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public StringBuffer getRequestURL() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRequestURL(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getServletPath() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getServletPath(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public HttpSession getSession(boolean create) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (SecurityUtil.isPackageProtectionEnabled()){ return AccessController. doPrivileged(new GetSessionPrivilegedAction(create)); } else { return request.getSession(create); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public HttpSession getSession() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return getSession(true); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean isRequestedSessionIdValid() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isRequestedSessionIdValid(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean isRequestedSessionIdFromCookie() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isRequestedSessionIdFromCookie(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean isRequestedSessionIdFromURL() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isRequestedSessionIdFromURL(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean isRequestedSessionIdFromUrl() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isRequestedSessionIdFromURL(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getLocalAddr() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getLocalAddr(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getLocalName() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getLocalName(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public int getLocalPort() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getLocalPort(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public int getRemotePort() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRemotePort(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public ServletContext getServletContext() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getServletContext(); }
// in java/org/apache/catalina/connector/CometEventImpl.java
Override public void close() throws IOException { if (request == null) { throw new IllegalStateException(sm.getString("cometEvent.nullRequest")); } request.finishRequest(); response.finishResponse(); if (request.isComet()) { request.cometClose(); } }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
Override public boolean asyncDispatch(org.apache.coyote.Request req, org.apache.coyote.Response res, SocketStatus status) throws Exception { Request request = (Request) req.getNote(ADAPTER_NOTES); Response response = (Response) res.getNote(ADAPTER_NOTES); if (request == null) { throw new IllegalStateException( "Dispatch may only happen on an existing request."); } boolean comet = false; boolean success = true; AsyncContextImpl asyncConImpl = (AsyncContextImpl)request.getAsyncContext(); req.getRequestProcessor().setWorkerThreadName(Thread.currentThread().getName()); try { if (!request.isAsync() && !comet) { // Error or timeout - need to tell listeners the request is over // Have to test this first since state may change while in this // method and this is only required if entering this method in // this state Context ctxt = (Context) request.getMappingData().context; if (ctxt != null) { ctxt.fireRequestDestroyEvent(request); } // Lift any suspension (e.g. if sendError() was used by an async // request) to allow the response to be written to the client response.setSuspended(false); } if (status==SocketStatus.TIMEOUT) { success = true; if (!asyncConImpl.timeout()) { asyncConImpl.setErrorState(null); } } if (request.isAsyncDispatching()) { success = true; connector.getService().getContainer().getPipeline().getFirst().invoke(request, response); Throwable t = (Throwable) request.getAttribute( RequestDispatcher.ERROR_EXCEPTION); if (t != null) { asyncConImpl.setErrorState(t); } } if (request.isComet()) { if (!response.isClosed() && !response.isError()) { if (request.getAvailable() || (request.getContentLength() > 0 && (!request.isParametersParsed()))) { // Invoke a read event right away if there are available bytes if (event(req, res, SocketStatus.OPEN)) { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { // Clear the filter chain, as otherwise it will not be reset elsewhere // since this is a Comet request request.setFilterChain(null); } } if (!request.isAsync() && !comet) { request.finishRequest(); response.finishResponse(); req.action(ActionCode.POST_REQUEST , null); ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); } } catch (IOException e) { success = false; // Ignore } catch (Throwable t) { ExceptionUtils.handleThrowable(t); success = false; log.error(sm.getString("coyoteAdapter.service"), t); } finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!success || (!comet && !request.isAsync())) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } } return success; }
// in java/org/apache/catalina/connector/ResponseFacade.java
public void finish() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } response.setSuspended(true); }
// in java/org/apache/catalina/connector/ResponseFacade.java
public boolean isFinished() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.isSuspended(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
public long getContentWritten() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.getContentWritten(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public String getCharacterEncoding() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.getCharacterEncoding(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void setBufferSize(int size) { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.setBufferSize.ise")); } response.setBufferSize(size); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public int getBufferSize() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.getBufferSize(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void resetBuffer() { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.resetBuffer.ise")); } response.resetBuffer(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public boolean isCommitted() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return (response.isAppCommitted()); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void reset() { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.reset.ise")); } response.reset(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public Locale getLocale() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.getLocale(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public boolean containsHeader(String name) { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.containsHeader(name); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public String encodeURL(String url) { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.encodeURL(url); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public String encodeRedirectURL(String url) { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.encodeRedirectURL(url); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public String encodeUrl(String url) { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.encodeURL(url); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public String encodeRedirectUrl(String url) { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.encodeRedirectURL(url); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void sendError(int sc, String msg) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendError.ise")); } response.setAppCommitted(true); response.sendError(sc, msg); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void sendError(int sc) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendError.ise")); } response.setAppCommitted(true); response.sendError(sc); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void sendRedirect(String location) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendRedirect.ise")); } response.setAppCommitted(true); response.sendRedirect(location); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public String getContentType() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.getContentType(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void setCharacterEncoding(String arg0) { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } response.setCharacterEncoding(arg0); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
private static void initializeSSL() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { if ("off".equalsIgnoreCase(SSLEngine)) { return; } if (sslInitialized) { //only once per VM return; } sslInitialized = true; String methodName = "randSet"; Class<?> paramTypes[] = new Class[1]; paramTypes[0] = String.class; Object paramValues[] = new Object[1]; paramValues[0] = SSLRandomSeed; Class<?> clazz = Class.forName("org.apache.tomcat.jni.SSL"); Method method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); methodName = "initialize"; paramValues[0] = "on".equalsIgnoreCase(SSLEngine)?null:SSLEngine; method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); if("on".equalsIgnoreCase(FIPSMode)) { log.info(sm.getString("aprListener.initializingFIPS")); int result = SSL.fipsModeSet(1); // success is defined as return value = 1 if(1 == result) { fipsModeActive = true; log.info(sm.getString("aprListener.initializeFIPSSuccess")); } else { // This case should be handled by the native method, // but we'll make absolutely sure, here. String message = sm.getString("aprListener.initializeFIPSFailed"); log.error(message); throw new IllegalStateException(message); } } log.info(sm.getString("aprListener.initializedOpenSSL", SSL.versionString())); sslAvailable = true; }
// in java/org/apache/catalina/core/AprLifecycleListener.java
public void setSSLEngine(String SSLEngine) { if (!SSLEngine.equals(AprLifecycleListener.SSLEngine)) { // Ensure that the SSLEngine is consistent with that used for SSL init if (sslInitialized) { throw new IllegalStateException( sm.getString("aprListener.tooLateForSSLEngine")); } AprLifecycleListener.SSLEngine = SSLEngine; } }
// in java/org/apache/catalina/core/AprLifecycleListener.java
public void setSSLRandomSeed(String SSLRandomSeed) { if (!SSLRandomSeed.equals(AprLifecycleListener.SSLRandomSeed)) { // Ensure that the random seed is consistent with that used for SSL init if (sslInitialized) { throw new IllegalStateException( sm.getString("aprListener.tooLateForSSLRandomSeed")); } AprLifecycleListener.SSLRandomSeed = SSLRandomSeed; } }
// in java/org/apache/catalina/core/AprLifecycleListener.java
public void setFIPSMode(String FIPSMode) { if (!FIPSMode.equals(AprLifecycleListener.FIPSMode)) { // Ensure that the FIPS mode is consistent with that used for SSL init if (sslInitialized) { throw new IllegalStateException( sm.getString("aprListener.tooLateForFIPSMode")); } AprLifecycleListener.FIPSMode = FIPSMode; } }
// in java/org/apache/catalina/core/ApplicationContext.java
private FilterRegistration.Dynamic addFilter(String filterName, String filterClass, Filter filter) throws IllegalStateException { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addFilter.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. FilterDef filterDef = context.findFilterDef(filterName); // Assume a 'complete' FilterRegistration is one that has a class and // a name if (filterDef == null) { filterDef = new FilterDef(); filterDef.setFilterName(filterName); context.addFilterDef(filterDef); } else { if (filterDef.getFilterName() != null && filterDef.getFilterClass() != null) { return null; } } if (filter == null) { filterDef.setFilterClass(filterClass); } else { filterDef.setFilterClass(filter.getClass().getName()); filterDef.setFilter(filter); } return new ApplicationFilterRegistration(filterDef, context); }
// in java/org/apache/catalina/core/ApplicationContext.java
private ServletRegistration.Dynamic addServlet(String servletName, String servletClass, Servlet servlet) throws IllegalStateException { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addServlet.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. Wrapper wrapper = (Wrapper) context.findChild(servletName); // Assume a 'complete' ServletRegistration is one that has a class and // a name if (wrapper == null) { wrapper = context.createWrapper(); wrapper.setName(servletName); context.addChild(wrapper); } else { if (wrapper.getName() != null && wrapper.getServletClass() != null) { if (wrapper.isOverridable()) { wrapper.setOverridable(false); } else { return null; } } } if (servlet == null) { wrapper.setServletClass(servletClass); } else { wrapper.setServletClass(servlet.getClass().getName()); wrapper.setServlet(servlet); } return context.dynamicServletAdded(wrapper); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public void setSessionTrackingModes( Set<SessionTrackingMode> sessionTrackingModes) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException( sm.getString("applicationContext.setSessionTracking.ise", getContextPath())); } // Check that only supported tracking modes have been requested for (SessionTrackingMode sessionTrackingMode : sessionTrackingModes) { if (!supportedSessionTrackingModes.contains(sessionTrackingMode)) { throw new IllegalArgumentException(sm.getString( "applicationContext.setSessionTracking.iae.invalid", sessionTrackingMode.toString(), getContextPath())); } } // Check SSL has not be configured with anything else if (sessionTrackingModes.contains(SessionTrackingMode.SSL)) { if (sessionTrackingModes.size() > 1) { throw new IllegalArgumentException(sm.getString( "applicationContext.setSessionTracking.iae.ssl", getContextPath())); } } this.sessionTrackingModes = sessionTrackingModes; }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends EventListener> void addListener(T t) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException( sm.getString("applicationContext.addListener.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. boolean match = false; if (t instanceof ServletContextAttributeListener || t instanceof ServletRequestListener || t instanceof ServletRequestAttributeListener || t instanceof HttpSessionAttributeListener) { context.addApplicationEventListener(t); match = true; } if (t instanceof HttpSessionListener || (t instanceof ServletContextListener && newServletContextListenerAllowed)) { context.addApplicationLifecycleListener(t); match = true; } if (match) return; if (t instanceof ServletContextListener) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.sclNotAllowed", t.getClass().getName())); } else { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", t.getClass().getName())); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public void declareRoles(String... roleNames) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addRole.ise", getContextPath())); } if (roleNames == null) { throw new IllegalArgumentException( sm.getString("applicationContext.roles.iae", getContextPath())); } for (String role : roleNames) { if (role == null || "".equals(role)) { throw new IllegalArgumentException( sm.getString("applicationContext.role.iae", getContextPath())); } context.addSecurityRole(role); } }
// in java/org/apache/catalina/core/ContainerBase.java
private void addChildInternal(Container child) { if( log.isDebugEnabled() ) log.debug("Add child " + child + " " + this); synchronized(children) { if (children.get(child.getName()) != null) throw new IllegalArgumentException("addChild: Child name '" + child.getName() + "' is not unique"); child.setParent(this); // May throw IAE children.put(child.getName(), child); } // Start child // Don't do this inside sync block - start can be a slow process and // locking the children object can cause problems elsewhere if ((getState().isAvailable() || LifecycleState.STARTING_PREP.equals(getState())) && startChildren) { try { child.start(); } catch (LifecycleException e) { log.error("ContainerBase.addChild: start: ", e); throw new IllegalStateException ("ContainerBase.addChild: start: " + e); } } fireContainerEvent(ADD_CHILD_EVENT, child); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
private void check() { if (request == null) { // AsyncContext has been recycled and should not be being used throw new IllegalStateException(sm.getString( "asyncContextImpl.requestEnded")); } }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
Override public void execute(Runnable command, long timeout, TimeUnit unit) { if ( executor != null ) { executor.execute(command,timeout,unit); } else { throw new IllegalStateException("StandardThreadExecutor not started."); } }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
Override public void execute(Runnable command) { if ( executor != null ) { try { executor.execute(command); } catch (RejectedExecutionException rx) { //there could have been contention around the queue if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException("Work queue full."); } } else throw new IllegalStateException("StandardThreadPool not started."); }
// in java/org/apache/catalina/core/StandardContext.java
Override public synchronized void setResources(DirContext resources) { if (getState().isAvailable()) { throw new IllegalStateException (sm.getString("standardContext.resources.started")); } DirContext oldResources = this.webappResources; if (oldResources == resources) return; if (resources instanceof BaseDirContext) { // Caching ((BaseDirContext) resources).setCached(isCachingAllowed()); ((BaseDirContext) resources).setCacheTTL(getCacheTTL()); ((BaseDirContext) resources).setCacheMaxSize(getCacheMaxSize()); ((BaseDirContext) resources).setCacheObjectMaxSize( getCacheObjectMaxSize()); // Alias support ((BaseDirContext) resources).setAliases(getAliases()); } if (resources instanceof FileDirContext) { ((FileDirContext) resources).setAllowLinking(isAllowLinking()); } this.webappResources = resources; // The proxied resources will be refreshed on start this.resources = null; support.firePropertyChange("resources", oldResources, this.webappResources); }
// in java/org/apache/catalina/core/StandardContext.java
Override public synchronized void reload() { // Validate our current component state if (!getState().isAvailable()) throw new IllegalStateException (sm.getString("standardContext.notStarted", getName())); if(log.isInfoEnabled()) log.info(sm.getString("standardContext.reloadingStarted", getName())); // Stop accepting requests temporarily. setPaused(true); try { stop(); } catch (LifecycleException e) { log.error( sm.getString("standardContext.stoppingContext", getName()), e); } try { start(); } catch (LifecycleException e) { log.error( sm.getString("standardContext.startingContext", getName()), e); } setPaused(false); if(log.isInfoEnabled()) log.info(sm.getString("standardContext.reloadingCompleted", getName())); }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public void addChild(Container child) { throw new IllegalStateException (sm.getString("standardWrapper.notChild")); }
// in java/org/apache/catalina/core/ApplicationServletRegistration.java
Override public Set<String> setServletSecurity(ServletSecurityElement constraint) { if (constraint == null) { throw new IllegalArgumentException(sm.getString( "applicationServletRegistration.setServletSecurity.iae", getName(), context.getName())); } if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException(sm.getString( "applicationServletRegistration.setServletSecurity.ise", getName(), context.getName())); } return context.addServletSecurity(this, constraint); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void doForward(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Reset any output that has been buffered, but keep headers/cookies if (response.isCommitted()) { throw new IllegalStateException (sm.getString("applicationDispatcher.forward.ise")); } try { response.resetBuffer(); } catch (IllegalStateException e) { throw e; } // Set up to handle the specified request and response State state = new State(request, response, false); if (WRAP_SAME_OBJECT) { // Check SRV.8.2 / SRV.14.2.5.1 compliance checkSameObjects(request, response); } wrapResponse(state); // Handle an HTTP named dispatcher forward if ((servletPath == null) && (pathInfo == null)) { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); HttpServletRequest hrequest = state.hrequest; wrequest.setRequestURI(hrequest.getRequestURI()); wrequest.setContextPath(hrequest.getContextPath()); wrequest.setServletPath(hrequest.getServletPath()); wrequest.setPathInfo(hrequest.getPathInfo()); wrequest.setQueryString(hrequest.getQueryString()); processRequest(request,response,state); } // Handle an HTTP path-based forward else { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); String contextPath = context.getPath(); HttpServletRequest hrequest = state.hrequest; if (hrequest.getAttribute( RequestDispatcher.FORWARD_REQUEST_URI) == null) { wrequest.setAttribute(RequestDispatcher.FORWARD_REQUEST_URI, hrequest.getRequestURI()); wrequest.setAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH, hrequest.getContextPath()); wrequest.setAttribute(RequestDispatcher.FORWARD_SERVLET_PATH, hrequest.getServletPath()); wrequest.setAttribute(RequestDispatcher.FORWARD_PATH_INFO, hrequest.getPathInfo()); wrequest.setAttribute(RequestDispatcher.FORWARD_QUERY_STRING, hrequest.getQueryString()); } wrequest.setContextPath(contextPath); wrequest.setRequestURI(requestURI); wrequest.setServletPath(servletPath); wrequest.setPathInfo(pathInfo); if (queryString != null) { wrequest.setQueryString(queryString); wrequest.setQueryParams(queryString); } processRequest(request,response,state); } // This is not a real close in order to support error processing if (wrapper.getLogger().isDebugEnabled() ) wrapper.getLogger().debug(" Disabling the response for futher output"); if (response instanceof ResponseFacade) { ((ResponseFacade) response).finish(); } else { // Servlet SRV.6.2.2. The Request/Response may have been wrapped // and may no longer be instance of RequestFacade if (wrapper.getLogger().isDebugEnabled()){ wrapper.getLogger().debug( " The Response is vehiculed using a wrapper: " + response.getClass().getName() ); } // Close anyway try { PrintWriter writer = response.getWriter(); writer.close(); } catch (IllegalStateException e) { try { ServletOutputStream stream = response.getOutputStream(); stream.close(); } catch (IllegalStateException f) { // Ignore } catch (IOException f) { // Ignore } } catch (IOException e) { // Ignore } } }
// in java/org/apache/catalina/util/ParameterMap.java
Override public void clear() { if (locked) throw new IllegalStateException (sm.getString("parameterMap.locked")); super.clear(); }
// in java/org/apache/catalina/util/ParameterMap.java
Override public V put(K key, V value) { if (locked) throw new IllegalStateException (sm.getString("parameterMap.locked")); return (super.put(key, value)); }
// in java/org/apache/catalina/util/ParameterMap.java
Override public void putAll(Map<? extends K,? extends V> map) { if (locked) throw new IllegalStateException (sm.getString("parameterMap.locked")); super.putAll(map); }
// in java/org/apache/catalina/util/ParameterMap.java
Override public V remove(Object key) { if (locked) throw new IllegalStateException (sm.getString("parameterMap.locked")); return (super.remove(key)); }
// in java/org/apache/catalina/util/ResourceSet.java
Override public boolean add(T o) { if (locked) throw new IllegalStateException (sm.getString("resourceSet.locked")); return (super.add(o)); }
// in java/org/apache/catalina/util/ResourceSet.java
Override public void clear() { if (locked) throw new IllegalStateException (sm.getString("resourceSet.locked")); super.clear(); }
// in java/org/apache/catalina/util/ResourceSet.java
Override public boolean remove(Object o) { if (locked) throw new IllegalStateException (sm.getString("resourceSet.locked")); return (super.remove(o)); }
12
              
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch (ClassNotFoundException ex) { throw new IllegalStateException(ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (MalformedURLException e) { throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"), e); }
// in java/org/apache/coyote/http11/filters/BufferedInputFilter.java
catch(IOException ioe) { // No need for i18n - this isn't going to get logged anywhere throw new IllegalStateException( "Request body too large for buffer"); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { log.error("Couldn't get MD5 digest: ", e); throw new IllegalStateException(e.getMessage()); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "expiresFilter.startingPointNotFound", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { throw new IllegalStateException(sm.getString( "Invalid duration (number) '{}' in directive '{}'", currentToken, line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException( sm.getString( "Duration unit not found after amount {} in directive '{}'", Integer.valueOf(amount), line)); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (ClassNotFoundException e) { String msg = sm.getString( "persistentManager.deserializeError", id); log.error(msg, e); throw new IllegalStateException(msg, e); }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new IllegalStateException(); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.addChild: start: ", e); throw new IllegalStateException ("ContainerBase.addChild: start: " + e); }
22
              
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) throws IOException, IllegalStateException, IllegalArgumentException { }
// in java/org/apache/jasper/runtime/JspApplicationContextImpl.java
Override public void addELResolver(ELResolver resolver) throws IllegalStateException { if (resolver == null) { throw new IllegalArgumentException("ELResolver was null"); } if (this.instantiated) { throw new IllegalStateException( "cannot call addELResolver after the first request has been made"); } this.resolvers.add(resolver); }
// in java/org/apache/coyote/Response.java
public void reset() throws IllegalStateException { // Reset the headers only if this is the main request, // not for included contentType = null; locale = DEFAULT_LOCALE; contentLanguage = null; characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; contentLength = -1; charsetSet = false; status = 200; message = null; headers.clear(); // Force the PrintWriter to flush its data to the output // stream before resetting the output stream // // Reset the stream if (commited) { //String msg = sm.getString("servletOutputStreamImpl.reset.ise"); throw new IllegalStateException(); } action(ActionCode.RESET, this); }
// in java/org/apache/coyote/http11/AbstractOutputBuffer.java
private void checkLengthBeforeWrite(int length) throws IllegalStateException { if (pos + length > buf.length) { throw new IllegalStateException( sm.getString("iob.responseheadertoolarge.error")); } }
// in java/org/apache/tomcat/util/http/Parameters.java
public void addParameter( String key, String value ) throws IllegalStateException { if( key==null ) { return; } parameterCount ++; if (limit > -1 && parameterCount > limit) { // Processing this parameter will push us over the limit. ISE is // what Request.parseParts() uses for requests that are too big parseFailed = true; throw new IllegalStateException(sm.getString( "parameters.maxCountFail", Integer.valueOf(limit))); } ArrayList<String> values = paramHashValues.get(key); if (values == null) { values = new ArrayList<String>(1); paramHashValues.put(key, values); } values.add(value); }
// in java/org/apache/catalina/connector/Request.java
Override public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException { parseParts(); if (partsParseException != null) { if (partsParseException instanceof IOException) { throw (IOException) partsParseException; } else if (partsParseException instanceof IllegalStateException) { throw (IllegalStateException) partsParseException; } else if (partsParseException instanceof ServletException) { throw (ServletException) partsParseException; } } return parts; }
// in java/org/apache/catalina/connector/Request.java
Override public Part getPart(String name) throws IOException, IllegalStateException, ServletException { Collection<Part> c = getParts(); Iterator<Part> iterator = c.iterator(); while (iterator.hasNext()) { Part part = iterator.next(); if (name.equals(part.getName())) { return part; } } return null; }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public AsyncContext startAsync() throws IllegalStateException { return request.startAsync(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public AsyncContext startAsync(ServletRequest request, ServletResponse response) throws IllegalStateException { return this.request.startAsync(request, response); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Collection<Part> getParts() throws IllegalStateException, IOException, ServletException { return request.getParts(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Part getPart(String name) throws IllegalStateException, IOException, ServletException { return request.getPart(name); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public FilterRegistration.Dynamic addFilter(String filterName, String filterClass) throws IllegalStateException { return addFilter(filterName, filterClass, null); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) throws IllegalStateException { return addFilter(filterName, null, filter); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) throws IllegalStateException { return addFilter(filterName, filterClass.getName(), null); }
// in java/org/apache/catalina/core/ApplicationContext.java
private FilterRegistration.Dynamic addFilter(String filterName, String filterClass, Filter filter) throws IllegalStateException { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addFilter.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. FilterDef filterDef = context.findFilterDef(filterName); // Assume a 'complete' FilterRegistration is one that has a class and // a name if (filterDef == null) { filterDef = new FilterDef(); filterDef.setFilterName(filterName); context.addFilterDef(filterDef); } else { if (filterDef.getFilterName() != null && filterDef.getFilterClass() != null) { return null; } } if (filter == null) { filterDef.setFilterClass(filterClass); } else { filterDef.setFilterClass(filter.getClass().getName()); filterDef.setFilter(filter); } return new ApplicationFilterRegistration(filterDef, context); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public ServletRegistration.Dynamic addServlet(String servletName, String servletClass) throws IllegalStateException { return addServlet(servletName, servletClass, null); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) throws IllegalStateException { return addServlet(servletName, null, servlet); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) throws IllegalStateException { return addServlet(servletName, servletClass.getName(), null); }
// in java/org/apache/catalina/core/ApplicationContext.java
private ServletRegistration.Dynamic addServlet(String servletName, String servletClass, Servlet servlet) throws IllegalStateException { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addServlet.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. Wrapper wrapper = (Wrapper) context.findChild(servletName); // Assume a 'complete' ServletRegistration is one that has a class and // a name if (wrapper == null) { wrapper = context.createWrapper(); wrapper.setName(servletName); context.addChild(wrapper); } else { if (wrapper.getName() != null && wrapper.getServletClass() != null) { if (wrapper.isOverridable()) { wrapper.setOverridable(false); } else { return null; } } } if (servlet == null) { wrapper.setServletClass(servletClass); } else { wrapper.setServletClass(servlet.getClass().getName()); wrapper.setServlet(servlet); } return context.dynamicServletAdded(wrapper); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public Collection<Part> getParts() throws IllegalStateException, IOException, ServletException { return this._getHttpServletRequest().getParts(); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public Part getPart(String name) throws IllegalStateException, IOException, ServletException { return this._getHttpServletRequest().getPart(name); }
// in java/javax/servlet/ServletRequestWrapper.java
Override public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { return request.startAsync(servletRequest, servletResponse); }
(Lib) MBeanException 109
              
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public DynamicMBean createMBean(Object instance) throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { BaseModelMBean mbean = null; // Load the ModelMBean implementation class if(getClassName().equals(BASE_MBEAN)) { // Skip introspection mbean = new BaseModelMBean(); } else { Class<?> clazz = null; Exception ex = null; try { clazz = Class.forName(getClassName()); } catch (Exception e) { } if( clazz==null ) { try { ClassLoader cl= Thread.currentThread().getContextClassLoader(); if ( cl != null) clazz= cl.loadClass(getClassName()); } catch (Exception e) { ex=e; } } if( clazz==null) { throw new MBeanException (ex, "Cannot load ModelMBean class " + getClassName()); } try { // Stupid - this will set the default minfo first.... mbean = (BaseModelMBean) clazz.newInstance(); } catch (RuntimeOperationsException e) { throw e; } catch (Exception e) { throw new MBeanException (e, "Cannot instantiate ModelMBean of class " + getClassName()); } } mbean.setManagedBean(this); // Set the managed resource (if any) try { if (instance != null) mbean.setManagedResource(instance, "ObjectReference"); } catch (InstanceNotFoundException e) { throw e; } return (mbean); }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getInvoke(String aname, Object[] params, String[] signature, BaseModelMBean bean, Object resource) throws MBeanException, ReflectionException { Method method = null; if (params == null) params = new Object[0]; if (signature == null) signature = new String[0]; if (params.length != signature.length) throw new RuntimeOperationsException( new IllegalArgumentException( "Inconsistent arguments and signature"), "Inconsistent arguments and signature"); // Acquire the ModelMBeanOperationInfo information for // the requested operation OperationInfo opInfo = operations.get(aname); if (opInfo == null) throw new MBeanException(new ServiceNotFoundException( "Cannot find operation " + aname), "Cannot find operation " + aname); // Prepare the signature required by Java reflection APIs // FIXME - should we use the signature from opInfo? Class<?> types[] = new Class[signature.length]; for (int i = 0; i < signature.length; i++) { types[i] = BaseModelMBean.getAttributeClass(signature[i]); } // Locate the method to be invoked, either in this MBean itself // or in the corresponding managed resource // FIXME - Accessible methods in superinterfaces? Object object = null; Exception exception = null; try { object = bean; method = object.getClass().getMethod(aname, types); } catch (NoSuchMethodException e) { exception = e; } try { if ((method == null) && (resource != null)) { object = resource; method = object.getClass().getMethod(aname, types); } } catch (NoSuchMethodException e) { exception = e; } if (method == null) { throw new ReflectionException(exception, "Cannot find method " + aname + " with this signature"); } return method; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).getAttribute(name); } Method m=managedBean.getGetter(name, this, resource); Object result = null; try { Class<?> declaring = m.getDeclaringClass(); // workaround for catalina weird mbeans - the declaring class is BaseModelMBean. // but this is the catalina class. if( declaring.isAssignableFrom(this.getClass()) ) { result = m.invoke(this, NO_ARGS_PARAM ); } else { result = m.invoke(resource, NO_ARGS_PARAM ); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object invoke(String name, Object params[], String signature[]) throws MBeanException, ReflectionException { if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).invoke(name, params, signature); } // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Method name is null"), "Method name is null"); if( log.isDebugEnabled()) log.debug("Invoke " + name); Method method= managedBean.getInvoke(name, params, signature, this, resource); // Invoke the selected method on the appropriate object Object result = null; try { if( method.getDeclaringClass().isAssignableFrom( this.getClass()) ) { result = method.invoke(this, params ); } else { result = method.invoke(resource, params); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if( log.isDebugEnabled() ) log.debug("Setting attribute " + this + " " + attribute ); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { try { ((DynamicMBean)resource).setAttribute(attribute); } catch (InvalidAttributeValueException e) { throw new MBeanException(e); } return; } // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); Object oldValue=null; //if( getAttMap.get(name) != null ) // oldValue=getAttribute( name ); Method m=managedBean.getSetter(name,this,resource); try { if( m.getDeclaringClass().isAssignableFrom( this.getClass()) ) { m.invoke(this, new Object[] { value }); } else { m.invoke(resource, new Object[] { value }); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } try { sendAttributeChangeNotification(new Attribute( name, oldValue), attribute); } catch(Exception ex) { log.error("Error sending notification " + name, ex); } //attributes.put( name, value ); // if( source != null ) { // // this mbean is associated with a source - maybe we want to persist // source.updateField(oname, name, value); // } }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public void addConnector(String address, int port, boolean isAjp, boolean isSSL) throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Connector connector = new Connector(); if ((address!=null) && (address.length()>0)) { connector.setProperty("address", address); } connector.setPort(port); connector.setProtocol(isAjp ? "AJP/1.3" : "HTTP/1.1"); connector.setSecure(isSSL); connector.setScheme(isSSL ? "https" : "http"); service.addConnector(connector); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public void addExecutor(String type) throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Executor executor; try { executor = (Executor)Class.forName(type).newInstance(); } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } service.addExecutor(executor); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public String[] findConnectors() throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Connector[] connectors = service.findConnectors(); String[] str = new String[connectors.length]; for(int i=0; i< connectors.length; i++){ str[i] = connectors[i].toString(); } return str; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public String[] findExecutors() throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Executor[] executors = service.findExecutors(); String[] str = new String[executors.length]; for(int i=0; i< executors.length; i++){ str[i] = executors[i].toString(); } return str; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public String getExecutor(String name) throws MBeanException{ Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Executor executor = service.getExecutor(name); return executor.toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findApplicationParameters() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ApplicationParameter[] params = context.findApplicationParameters(); String[] stringParams = new String[params.length]; for(int counter=0; counter < params.length; counter++){ stringParams[counter]=params[counter].toString(); } return stringParams; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findConstraints() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } SecurityConstraint[] constraints = context.findConstraints(); String[] stringConstraints = new String[constraints.length]; for(int counter=0; counter < constraints.length; counter++){ stringConstraints[counter]=constraints[counter].toString(); } return stringConstraints; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String findErrorPage(int errorCode) throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return context.findErrorPage(errorCode).toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String findErrorPage(String exceptionType) throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return context.findErrorPage(exceptionType).toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findErrorPages() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ErrorPage[] pages = context.findErrorPages(); String[] stringPages = new String[pages.length]; for(int counter=0; counter < pages.length; counter++){ stringPages[counter]=pages[counter].toString(); } return stringPages; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String findFilterDef(String name) throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } FilterDef filterDef = context.findFilterDef(name); return filterDef.toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findFilterDefs() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } FilterDef[] filterDefs = context.findFilterDefs(); String[] stringFilters = new String[filterDefs.length]; for(int counter=0; counter < filterDefs.length; counter++){ stringFilters[counter]=filterDefs[counter].toString(); } return stringFilters; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findFilterMaps() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } FilterMap[] maps = context.findFilterMaps(); String[] stringMaps = new String[maps.length]; for(int counter=0; counter < maps.length; counter++){ stringMaps[counter]=maps[counter].toString(); } return stringMaps; }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); Object result = null; try { Connector connector = (Connector) getManagedResource(); result = IntrospectionUtils.getProperty(connector, name); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return result; }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); try { Connector connector = (Connector) getManagedResource(); IntrospectionUtils.setProperty(connector, name, String.valueOf(value)); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("auth".equals(name)) { return (cr.getAuth()); } else if ("description".equals(name)) { return (cr.getDescription()); } else if ("name".equals(name)) { return (cr.getName()); } else if ("scope".equals(name)) { return (cr.getScope()); } else if ("type".equals(name)) { return (cr.getType()); } else { value = (String) cr.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("auth".equals(name)) { cr.setAuth((String)value); } else if ("description".equals(name)) { cr.setDescription((String)value); } else if ("name".equals(name)) { cr.setName((String)value); } else if ("scope".equals(name)) { cr.setScope((String)value); } else if ("type".equals(name)) { cr.setType((String)value); } else { cr.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = cr.getNamingResources(); nr.removeResource(cr.getName()); nr.addResource(cr); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void addChild(String type, String name) throws MBeanException{ Container contained = null; try { contained = (Container)Class.forName(type).newInstance(); contained.setName(name); if(contained instanceof StandardHost){ HostConfig config = new HostConfig(); contained.addLifecycleListener(config); } else if(contained instanceof StandardContext){ ContextConfig config = new ContextConfig(); contained.addLifecycleListener(config); } } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } boolean oldValue= true; ContainerBase container = null; try { container = (ContainerBase)getManagedResource(); oldValue = container.getStartChildren(); container.setStartChildren(false); container.addChild(contained); contained.init(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } catch (LifecycleException e){ throw new MBeanException(e); } finally { if(container != null) { container.setStartChildren(oldValue); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void removeChild(String name) throws MBeanException{ if(name != null){ try { Container container = (Container)getManagedResource(); Container contained = container.findChild(name); container.removeChild(contained); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public String addValve(String valveType) throws MBeanException{ Valve valve = null; try { valve = (Valve)Class.forName(valveType).newInstance(); } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } if (valve == null) { return null; } try { Container container = (Container)getManagedResource(); container.getPipeline().addValve(valve); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if (valve instanceof JmxEnabled) { return ((JmxEnabled)valve).getObjectName().toString(); } else { return null; } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void removeValve(String valveName) throws MBeanException{ Container container=null; try { container = (Container)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ObjectName oname; try { oname = new ObjectName(valveName); } catch (MalformedObjectNameException e) { throw new MBeanException(e); } catch (NullPointerException e) { throw new MBeanException(e); } if(container != null){ Valve[] valves = container.getPipeline().getValves(); for (int i = 0; i < valves.length; i++) { if (valves[i] instanceof JmxEnabled) { ObjectName voname = ((JmxEnabled) valves[i]).getObjectName(); if (voname.equals(oname)) { container.getPipeline().removeValve(valves[i]); } } } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void addLifeCycleListener(String type) throws MBeanException{ LifecycleListener listener = null; try { listener = (LifecycleListener)Class.forName(type).newInstance(); } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } if(listener != null){ try { Container container = (Container)getManagedResource(); container.addLifecycleListener(listener); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void removeLifeCycleListeners(String type) throws MBeanException{ Container container=null; try { container = (Container)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } LifecycleListener[] listeners = container.findLifecycleListeners(); for(LifecycleListener listener: listeners){ if(listener.getClass().getName().equals(type)){ container.removeLifecycleListener(listener); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public String[] findLifecycleListenerNames() throws MBeanException { Container container = null; List<String> result = new ArrayList<String>(); try { container = (Container) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } LifecycleListener[] listeners = container.findLifecycleListeners(); for(LifecycleListener listener: listeners){ result.add(listener.getClass().getName()); } return result.toArray(new String[result.size()]); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public String[] findContainerListenerNames() throws MBeanException { Container container = null; List<String> result = new ArrayList<String>(); try { container = (Container) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ContainerListener[] listeners = container.findContainerListeners(); for(ContainerListener listener: listeners){ result.add(listener.getClass().getName()); } return result.toArray(new String[result.size()]); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink cl = null; try { cl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("global".equals(name)) { return (cl.getGlobal()); } else if ("description".equals(name)) { return (cl.getDescription()); } else if ("name".equals(name)) { return (cl.getName()); } else if ("type".equals(name)) { return (cl.getType()); } else { value = (String) cl.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink crl = null; try { crl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("global".equals(name)) { crl.setGlobal((String)value); } else if ("description".equals(name)) { crl.setDescription((String)value); } else if ("name".equals(name)) { crl.setName((String)value); } else if ("type".equals(name)) { crl.setType((String)value); } else { crl.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = crl.getNamingResources(); nr.removeResourceLink(crl.getName()); nr.addResourceLink(crl); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static DynamicMBean createMBean(ContextEnvironment environment) throws Exception { String mname = createManagedName(environment); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(environment); ObjectName oname = createObjectName(domain, environment); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static DynamicMBean createMBean(ContextResource resource) throws Exception { String mname = createManagedName(resource); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(resource); ObjectName oname = createObjectName(domain, resource); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static DynamicMBean createMBean(ContextResourceLink resourceLink) throws Exception { String mname = createManagedName(resourceLink); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(resourceLink); ObjectName oname = createObjectName(domain, resourceLink); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(Group group) throws Exception { String mname = createManagedName(group); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(group); ObjectName oname = createObjectName(domain, group); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(Role role) throws Exception { String mname = createManagedName(role); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(role); ObjectName oname = createObjectName(domain, role); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(User user) throws Exception { String mname = createManagedName(user); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(user); ObjectName oname = createObjectName(domain, user); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(UserDatabase userDatabase) throws Exception { String mname = createManagedName(userDatabase); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(userDatabase); ObjectName oname = createObjectName(domain, userDatabase); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { super.setAttribute(attribute); ContextEnvironment ce = null; try { ce = (ContextEnvironment) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = ce.getNamingResources(); nr.removeEnvironment(ce.getName()); nr.addEnvironment(ce); }
100
              
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (Exception e) { throw new MBeanException (e, "Cannot instantiate ModelMBean of class " + getClassName()); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvalidAttributeValueException e) { throw new MBeanException(e); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (LifecycleException e){ throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (MalformedObjectNameException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (NullPointerException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
54
              
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public DynamicMBean createMBean() throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { return (createMBean(null)); }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public DynamicMBean createMBean(Object instance) throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { BaseModelMBean mbean = null; // Load the ModelMBean implementation class if(getClassName().equals(BASE_MBEAN)) { // Skip introspection mbean = new BaseModelMBean(); } else { Class<?> clazz = null; Exception ex = null; try { clazz = Class.forName(getClassName()); } catch (Exception e) { } if( clazz==null ) { try { ClassLoader cl= Thread.currentThread().getContextClassLoader(); if ( cl != null) clazz= cl.loadClass(getClassName()); } catch (Exception e) { ex=e; } } if( clazz==null) { throw new MBeanException (ex, "Cannot load ModelMBean class " + getClassName()); } try { // Stupid - this will set the default minfo first.... mbean = (BaseModelMBean) clazz.newInstance(); } catch (RuntimeOperationsException e) { throw e; } catch (Exception e) { throw new MBeanException (e, "Cannot instantiate ModelMBean of class " + getClassName()); } } mbean.setManagedBean(this); // Set the managed resource (if any) try { if (instance != null) mbean.setManagedResource(instance, "ObjectReference"); } catch (InstanceNotFoundException e) { throw e; } return (mbean); }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getInvoke(String aname, Object[] params, String[] signature, BaseModelMBean bean, Object resource) throws MBeanException, ReflectionException { Method method = null; if (params == null) params = new Object[0]; if (signature == null) signature = new String[0]; if (params.length != signature.length) throw new RuntimeOperationsException( new IllegalArgumentException( "Inconsistent arguments and signature"), "Inconsistent arguments and signature"); // Acquire the ModelMBeanOperationInfo information for // the requested operation OperationInfo opInfo = operations.get(aname); if (opInfo == null) throw new MBeanException(new ServiceNotFoundException( "Cannot find operation " + aname), "Cannot find operation " + aname); // Prepare the signature required by Java reflection APIs // FIXME - should we use the signature from opInfo? Class<?> types[] = new Class[signature.length]; for (int i = 0; i < signature.length; i++) { types[i] = BaseModelMBean.getAttributeClass(signature[i]); } // Locate the method to be invoked, either in this MBean itself // or in the corresponding managed resource // FIXME - Accessible methods in superinterfaces? Object object = null; Exception exception = null; try { object = bean; method = object.getClass().getMethod(aname, types); } catch (NoSuchMethodException e) { exception = e; } try { if ((method == null) && (resource != null)) { object = resource; method = object.getClass().getMethod(aname, types); } } catch (NoSuchMethodException e) { exception = e; } if (method == null) { throw new ReflectionException(exception, "Cannot find method " + aname + " with this signature"); } return method; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).getAttribute(name); } Method m=managedBean.getGetter(name, this, resource); Object result = null; try { Class<?> declaring = m.getDeclaringClass(); // workaround for catalina weird mbeans - the declaring class is BaseModelMBean. // but this is the catalina class. if( declaring.isAssignableFrom(this.getClass()) ) { result = m.invoke(this, NO_ARGS_PARAM ); } else { result = m.invoke(resource, NO_ARGS_PARAM ); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object invoke(String name, Object params[], String signature[]) throws MBeanException, ReflectionException { if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).invoke(name, params, signature); } // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Method name is null"), "Method name is null"); if( log.isDebugEnabled()) log.debug("Invoke " + name); Method method= managedBean.getInvoke(name, params, signature, this, resource); // Invoke the selected method on the appropriate object Object result = null; try { if( method.getDeclaringClass().isAssignableFrom( this.getClass()) ) { result = method.invoke(this, params ); } else { result = method.invoke(resource, params); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if( log.isDebugEnabled() ) log.debug("Setting attribute " + this + " " + attribute ); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { try { ((DynamicMBean)resource).setAttribute(attribute); } catch (InvalidAttributeValueException e) { throw new MBeanException(e); } return; } // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); Object oldValue=null; //if( getAttMap.get(name) != null ) // oldValue=getAttribute( name ); Method m=managedBean.getSetter(name,this,resource); try { if( m.getDeclaringClass().isAssignableFrom( this.getClass()) ) { m.invoke(this, new Object[] { value }); } else { m.invoke(resource, new Object[] { value }); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } try { sendAttributeChangeNotification(new Attribute( name, oldValue), attribute); } catch(Exception ex) { log.error("Error sending notification " + name, ex); } //attributes.put( name, value ); // if( source != null ) { // // this mbean is associated with a source - maybe we want to persist // source.updateField(oname, name, value); // } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
public Object getManagedResource() throws InstanceNotFoundException, InvalidTargetObjectTypeException, MBeanException, RuntimeOperationsException { if (resource == null) throw new RuntimeOperationsException (new IllegalArgumentException("Managed resource is null"), "Managed resource is null"); return resource; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
public void setManagedResource(Object resource, String type) throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { if (resource == null) throw new RuntimeOperationsException (new IllegalArgumentException("Managed resource is null"), "Managed resource is null"); // if (!"objectreference".equalsIgnoreCase(type)) // throw new InvalidTargetObjectTypeException(type); this.resource = resource; this.resourceType = resource.getClass().getName(); // // Make the resource aware of the model mbean. // try { // Method m=resource.getClass().getMethod("setModelMBean", // new Class[] {ModelMBean.class}); // if( m!= null ) { // m.invoke(resource, new Object[] {this}); // } // } catch( NoSuchMethodException t ) { // // ignore // } catch( Throwable t ) { // log.error( "Can't set model mbean ", t ); // } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendAttributeChangeNotification (AttributeChangeNotification notification) throws MBeanException, RuntimeOperationsException { if (notification == null) throw new RuntimeOperationsException (new IllegalArgumentException("Notification is null"), "Notification is null"); if (attributeBroadcaster == null) return; // This means there are no registered listeners if( log.isDebugEnabled() ) log.debug( "AttributeChangeNotification " + notification ); attributeBroadcaster.sendNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendAttributeChangeNotification (Attribute oldValue, Attribute newValue) throws MBeanException, RuntimeOperationsException { // Calculate the class name for the change notification String type = null; if (newValue.getValue() != null) type = newValue.getValue().getClass().getName(); else if (oldValue.getValue() != null) type = oldValue.getValue().getClass().getName(); else return; // Old and new are both null == no change AttributeChangeNotification notification = new AttributeChangeNotification (this, 1, System.currentTimeMillis(), "Attribute value has changed", oldValue.getName(), type, oldValue.getValue(), newValue.getValue()); sendAttributeChangeNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendNotification(Notification notification) throws MBeanException, RuntimeOperationsException { if (notification == null) throw new RuntimeOperationsException (new IllegalArgumentException("Notification is null"), "Notification is null"); if (generalBroadcaster == null) return; // This means there are no registered listeners generalBroadcaster.sendNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendNotification(String message) throws MBeanException, RuntimeOperationsException { if (message == null) throw new RuntimeOperationsException (new IllegalArgumentException("Message is null"), "Message is null"); Notification notification = new Notification ("jmx.modelmbean.generic", this, 1, message); sendNotification(notification); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public void addConnector(String address, int port, boolean isAjp, boolean isSSL) throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Connector connector = new Connector(); if ((address!=null) && (address.length()>0)) { connector.setProperty("address", address); } connector.setPort(port); connector.setProtocol(isAjp ? "AJP/1.3" : "HTTP/1.1"); connector.setSecure(isSSL); connector.setScheme(isSSL ? "https" : "http"); service.addConnector(connector); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public void addExecutor(String type) throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Executor executor; try { executor = (Executor)Class.forName(type).newInstance(); } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } service.addExecutor(executor); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public String[] findConnectors() throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Connector[] connectors = service.findConnectors(); String[] str = new String[connectors.length]; for(int i=0; i< connectors.length; i++){ str[i] = connectors[i].toString(); } return str; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public String[] findExecutors() throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Executor[] executors = service.findExecutors(); String[] str = new String[executors.length]; for(int i=0; i< executors.length; i++){ str[i] = executors[i].toString(); } return str; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public String getExecutor(String name) throws MBeanException{ Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Executor executor = service.getExecutor(name); return executor.toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findApplicationParameters() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ApplicationParameter[] params = context.findApplicationParameters(); String[] stringParams = new String[params.length]; for(int counter=0; counter < params.length; counter++){ stringParams[counter]=params[counter].toString(); } return stringParams; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findConstraints() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } SecurityConstraint[] constraints = context.findConstraints(); String[] stringConstraints = new String[constraints.length]; for(int counter=0; counter < constraints.length; counter++){ stringConstraints[counter]=constraints[counter].toString(); } return stringConstraints; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String findErrorPage(int errorCode) throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return context.findErrorPage(errorCode).toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String findErrorPage(String exceptionType) throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return context.findErrorPage(exceptionType).toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findErrorPages() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ErrorPage[] pages = context.findErrorPages(); String[] stringPages = new String[pages.length]; for(int counter=0; counter < pages.length; counter++){ stringPages[counter]=pages[counter].toString(); } return stringPages; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String findFilterDef(String name) throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } FilterDef filterDef = context.findFilterDef(name); return filterDef.toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findFilterDefs() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } FilterDef[] filterDefs = context.findFilterDefs(); String[] stringFilters = new String[filterDefs.length]; for(int counter=0; counter < filterDefs.length; counter++){ stringFilters[counter]=filterDefs[counter].toString(); } return stringFilters; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findFilterMaps() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } FilterMap[] maps = context.findFilterMaps(); String[] stringMaps = new String[maps.length]; for(int counter=0; counter < maps.length; counter++){ stringMaps[counter]=maps[counter].toString(); } return stringMaps; }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); Object result = null; try { Connector connector = (Connector) getManagedResource(); result = IntrospectionUtils.getProperty(connector, name); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return result; }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); try { Connector connector = (Connector) getManagedResource(); IntrospectionUtils.setProperty(connector, name, String.valueOf(value)); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("auth".equals(name)) { return (cr.getAuth()); } else if ("description".equals(name)) { return (cr.getDescription()); } else if ("name".equals(name)) { return (cr.getName()); } else if ("scope".equals(name)) { return (cr.getScope()); } else if ("type".equals(name)) { return (cr.getType()); } else { value = (String) cr.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("auth".equals(name)) { cr.setAuth((String)value); } else if ("description".equals(name)) { cr.setDescription((String)value); } else if ("name".equals(name)) { cr.setName((String)value); } else if ("scope".equals(name)) { cr.setScope((String)value); } else if ("type".equals(name)) { cr.setType((String)value); } else { cr.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = cr.getNamingResources(); nr.removeResource(cr.getName()); nr.addResource(cr); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void addChild(String type, String name) throws MBeanException{ Container contained = null; try { contained = (Container)Class.forName(type).newInstance(); contained.setName(name); if(contained instanceof StandardHost){ HostConfig config = new HostConfig(); contained.addLifecycleListener(config); } else if(contained instanceof StandardContext){ ContextConfig config = new ContextConfig(); contained.addLifecycleListener(config); } } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } boolean oldValue= true; ContainerBase container = null; try { container = (ContainerBase)getManagedResource(); oldValue = container.getStartChildren(); container.setStartChildren(false); container.addChild(contained); contained.init(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } catch (LifecycleException e){ throw new MBeanException(e); } finally { if(container != null) { container.setStartChildren(oldValue); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void removeChild(String name) throws MBeanException{ if(name != null){ try { Container container = (Container)getManagedResource(); Container contained = container.findChild(name); container.removeChild(contained); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public String addValve(String valveType) throws MBeanException{ Valve valve = null; try { valve = (Valve)Class.forName(valveType).newInstance(); } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } if (valve == null) { return null; } try { Container container = (Container)getManagedResource(); container.getPipeline().addValve(valve); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if (valve instanceof JmxEnabled) { return ((JmxEnabled)valve).getObjectName().toString(); } else { return null; } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void removeValve(String valveName) throws MBeanException{ Container container=null; try { container = (Container)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ObjectName oname; try { oname = new ObjectName(valveName); } catch (MalformedObjectNameException e) { throw new MBeanException(e); } catch (NullPointerException e) { throw new MBeanException(e); } if(container != null){ Valve[] valves = container.getPipeline().getValves(); for (int i = 0; i < valves.length; i++) { if (valves[i] instanceof JmxEnabled) { ObjectName voname = ((JmxEnabled) valves[i]).getObjectName(); if (voname.equals(oname)) { container.getPipeline().removeValve(valves[i]); } } } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void addLifeCycleListener(String type) throws MBeanException{ LifecycleListener listener = null; try { listener = (LifecycleListener)Class.forName(type).newInstance(); } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } if(listener != null){ try { Container container = (Container)getManagedResource(); container.addLifecycleListener(listener); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void removeLifeCycleListeners(String type) throws MBeanException{ Container container=null; try { container = (Container)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } LifecycleListener[] listeners = container.findLifecycleListeners(); for(LifecycleListener listener: listeners){ if(listener.getClass().getName().equals(type)){ container.removeLifecycleListener(listener); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public String[] findLifecycleListenerNames() throws MBeanException { Container container = null; List<String> result = new ArrayList<String>(); try { container = (Container) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } LifecycleListener[] listeners = container.findLifecycleListeners(); for(LifecycleListener listener: listeners){ result.add(listener.getClass().getName()); } return result.toArray(new String[result.size()]); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public String[] findContainerListenerNames() throws MBeanException { Container container = null; List<String> result = new ArrayList<String>(); try { container = (Container) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ContainerListener[] listeners = container.findContainerListeners(); for(ContainerListener listener: listeners){ result.add(listener.getClass().getName()); } return result.toArray(new String[result.size()]); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink cl = null; try { cl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("global".equals(name)) { return (cl.getGlobal()); } else if ("description".equals(name)) { return (cl.getDescription()); } else if ("name".equals(name)) { return (cl.getName()); } else if ("type".equals(name)) { return (cl.getType()); } else { value = (String) cl.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink crl = null; try { crl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("global".equals(name)) { crl.setGlobal((String)value); } else if ("description".equals(name)) { crl.setDescription((String)value); } else if ("name".equals(name)) { crl.setName((String)value); } else if ("type".equals(name)) { crl.setType((String)value); } else { crl.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = crl.getNamingResources(); nr.removeResourceLink(crl.getName()); nr.addResourceLink(crl); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { super.setAttribute(attribute); ContextEnvironment ce = null; try { ce = (ContextEnvironment) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = ce.getNamingResources(); nr.removeEnvironment(ce.getName()); nr.addEnvironment(ce); }
(Lib) NullPointerException 73
              
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public Object getAttribute(String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } return pageAttributes.get(name); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public Object getAttribute(String name, int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (scope == PAGE_SCOPE) { return pageAttributes.get(name); } return invokingJspCtxt.getAttribute(name, scope); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void setAttribute(String name, Object value) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (value != null) { pageAttributes.put(name, value); } else { removeAttribute(name, PAGE_SCOPE); } }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void setAttribute(String name, Object value, int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (scope == PAGE_SCOPE) { if (value != null) { pageAttributes.put(name, value); } else { removeAttribute(name, PAGE_SCOPE); } } else { invokingJspCtxt.setAttribute(name, value, scope); } }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public Object findAttribute(String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } Object o = pageAttributes.get(name); if (o == null) { o = invokingJspCtxt.getAttribute(name, REQUEST_SCOPE); if (o == null) { if (getSession() != null) { o = invokingJspCtxt.getAttribute(name, SESSION_SCOPE); } if (o == null) { o = invokingJspCtxt.getAttribute(name, APPLICATION_SCOPE); } } } return o; }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void removeAttribute(String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } pageAttributes.remove(name); invokingJspCtxt.removeAttribute(name, REQUEST_SCOPE); if (getSession() != null) { invokingJspCtxt.removeAttribute(name, SESSION_SCOPE); } invokingJspCtxt.removeAttribute(name, APPLICATION_SCOPE); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void removeAttribute(String name, int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (scope == PAGE_SCOPE) { pageAttributes.remove(name); } else { invokingJspCtxt.removeAttribute(name, scope); } }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public int getAttributesScope(String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (pageAttributes.get(name) != null) { return PAGE_SCOPE; } else { return invokingJspCtxt.getAttributesScope(name); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public Object getAttribute(final String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { return AccessController.doPrivileged( new PrivilegedAction<Object>() { @Override public Object run() { return doGetAttribute(name); } }); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public Object getAttribute(final String name, final int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { return AccessController.doPrivileged( new PrivilegedAction<Object>() { @Override public Object run() { return doGetAttribute(name, scope); } }); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void setAttribute(final String name, final Object attribute) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { doSetAttribute(name, attribute); return null; } }); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void setAttribute(final String name, final Object o, final int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { doSetAttribute(name, o, scope); return null; } }); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void removeAttribute(final String name, final int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { doRemoveAttribute(name, scope); return null; } }); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public int getAttributesScope(final String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { return (AccessController .doPrivileged(new PrivilegedAction<Integer>() { @Override public Integer run() { return Integer.valueOf(doGetAttributeScope(name)); } })).intValue();
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public Object run() { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } return doFindAttribute(name); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void removeAttribute(final String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { doRemoveAttribute(name); return null; } }); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void handlePageException(final Throwable t) throws IOException, ServletException { if (t == null) throw new NullPointerException("null Throwable"); if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doHandlePageException(t); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { return this.variableResolver.resolveVariable(property .toString()); } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getValue(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { Object obj = this.variableResolver.resolveVariable(property .toString()); return (obj != null) ? obj.getClass() : null; } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getType(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); throw new PropertyNotWritableException( "Legacy VariableResolver wrapped, not writable"); } if (!context.isPropertyResolved()) { elResolver.setValue(context, base, property, value); } }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return true; } return elResolver.isReadOnly(context, base, property); }
// in java/org/apache/tomcat/util/collections/ManagedConcurrentWeakHashMap.java
private static void checkNotNull(Object value) { if (value == null) { throw new NullPointerException(); } }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
public List<FileItem> parseRequest(RequestContext ctx) throws FileUploadException { List<FileItem> items = new ArrayList<FileItem>(); boolean successful = false; try { FileItemIterator iter = getItemIterator(ctx); FileItemFactory fac = getFileItemFactory(); if (fac == null) { throw new NullPointerException( "No FileItemFactory has been set."); } while (iter.hasNext()) { final FileItemStream item = iter.next(); // Don't use getName() here to prevent an InvalidFileNameException. final String fileName = ((org.apache.tomcat.util.http.fileupload.FileUploadBase.FileItemIteratorImpl.FileItemStreamImpl) item).name; FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), fileName); items.add(fileItem); try { Streams.copy(item.openStream(), fileItem.getOutputStream(), true); } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); } if (fileItem instanceof FileItemHeadersSupport) { final FileItemHeaders fih = item.getHeaders(); ((FileItemHeadersSupport) fileItem).setHeaders(fih); } } successful = true; return items; } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new FileUploadException(e.getMessage(), e); } finally { if (!successful) { for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) { FileItem fileItem = iterator.next(); try { fileItem.delete(); } catch (Exception e) { // ignore it } } } } }
// in java/org/apache/tomcat/util/http/fileupload/FileCleaningTracker.java
public void track(File file, Object marker, FileDeleteStrategy deleteStrategy) { if (file == null) { throw new NullPointerException("The file must not be null"); } addTracker(file.getPath(), marker, deleteStrategy); }
// in java/org/apache/tomcat/util/http/fileupload/FileCleaningTracker.java
public void track(String path, Object marker, FileDeleteStrategy deleteStrategy) { if (path == null) { throw new NullPointerException("The path must not be null"); } addTracker(path, marker, deleteStrategy); }
// in java/org/apache/tomcat/util/digester/ObjectCreateRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { // Identify the name of the class to instantiate String realClassName = className; if (attributeName != null) { String value = attributes.getValue(attributeName); if (value != null) { realClassName = value; } } if (digester.log.isDebugEnabled()) { digester.log.debug("[ObjectCreateRule]{" + digester.match + "}New " + realClassName); } if (realClassName == null) { throw new NullPointerException("No class name specified for " + namespace + " " + name); } // Instantiate the new object and push it on the context stack Class<?> clazz = digester.getClassLoader().loadClass(realClassName); Object instance = clazz.newInstance(); digester.push(instance); }
// in java/org/apache/el/lang/ExpressionBuilder.java
public MethodExpression createMethodExpression(Class<?> expectedReturnType, Class<?>[] expectedParamTypes) throws ELException { Node n = this.build(); if (!n.isParametersProvided() && expectedParamTypes == null) { throw new NullPointerException(MessageFactory .get("error.method.nullParms")); } if (n instanceof AstValue || n instanceof AstIdentifier) { return new MethodExpressionImpl(expression, n, this.fnMapper, this.varMapper, expectedReturnType, expectedParamTypes); } else if (n instanceof AstLiteralExpression) { return new MethodExpressionLiteral(expression, expectedReturnType, expectedParamTypes); } else { throw new ELException("Not a Valid Method Expression: " + expression); } }
// in java/org/apache/el/ExpressionFactoryImpl.java
Override public ValueExpression createValueExpression(ELContext context, String expression, Class<?> expectedType) { if (expectedType == null) { throw new NullPointerException(MessageFactory .get("error.value.expectedType")); } ExpressionBuilder builder = new ExpressionBuilder(expression, context); return builder.createValueExpression(expectedType); }
// in java/org/apache/el/ExpressionFactoryImpl.java
Override public ValueExpression createValueExpression(Object instance, Class<?> expectedType) { if (expectedType == null) { throw new NullPointerException(MessageFactory .get("error.value.expectedType")); } return new ValueExpressionLiteral(instance, expectedType); }
// in java/org/apache/catalina/core/AccessLogAdapter.java
public void add(AccessLog log) { if (log == null) { throw new NullPointerException(); } AccessLog newArray[] = Arrays.copyOf(logs, logs.length + 1); newArray[newArray.length - 1] = log; logs = newArray; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { PageContext page = (PageContext) context .getContext(JspContext.class); context.setPropertyResolved(true); switch (idx) { case APPLICATIONSCOPE: return ScopeManager.get(page).getApplicationScope(); case COOKIE: return ScopeManager.get(page).getCookie(); case HEADER: return ScopeManager.get(page).getHeader(); case HEADERVALUES: return ScopeManager.get(page).getHeaderValues(); case INITPARAM: return ScopeManager.get(page).getInitParam(); case PAGECONTEXT: return ScopeManager.get(page).getPageContext(); case PAGESCOPE: return ScopeManager.get(page).getPageScope(); case PARAM: return ScopeManager.get(page).getParam(); case PARAM_VALUES: return ScopeManager.get(page).getParamValues(); case REQUEST_SCOPE: return ScopeManager.get(page).getRequestScope(); case SESSION_SCOPE: return ScopeManager.get(page).getSessionScope(); } } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
public Class getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); throw new PropertyNotWritableException(); } } }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); return true; } } return false; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public final V put(String key, V value) { if (key == null) { throw new NullPointerException(); } if (value == null) { this.removeAttribute(key); } else { this.setAttribute(key, value); } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public final V remove(Object key) { if (key == null) { throw new NullPointerException(); } this.removeAttribute((String) key); return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); return page.findAttribute(key); } } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Class<Object> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); int scope = page.getAttributesScope(key); if (scope != 0) { page.setAttribute(key, value, scope); } else { page.setAttribute(key, value); } } } }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); } return false; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); if (property != null) { try { return ((ResourceBundle) base).getObject(property .toString()); } catch (MissingResourceException mre) { return "???" + property.toString() + "???"; } } } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } }
// in java/javax/el/ResourceBundleELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return true; }
// in java/javax/el/CompositeELResolver.java
public void add(ELResolver elResolver) { if (elResolver == null) { throw new NullPointerException(); } if (this.size >= this.resolvers.length) { ELResolver[] nr = new ELResolver[this.size * 2]; System.arraycopy(this.resolvers, 0, nr, 0, this.size); this.resolvers = nr; } this.resolvers[this.size++] = elResolver; }
// in java/javax/el/ArrayELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); if (idx < 0 || idx >= Array.getLength(base)) { return null; } return Array.get(base, idx); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); return base.getClass().getComponentType(); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); checkBounds(base, idx); if (value != null && !base.getClass().getComponentType().isAssignableFrom( value.getClass())) { throw new ClassCastException(message(context, "objectNotAssignable", new Object[] {value.getClass().getName(), base.getClass().getComponentType().getName()})); } Array.set(base, idx, value); } }
// in java/javax/el/ArrayELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); } return this.readOnly; }
// in java/javax/el/MapELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return ((Map<?,?>) base).get(property); } return null; }
// in java/javax/el/MapELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/el/MapELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } try { @SuppressWarnings("unchecked") // Must be OK Map<Object, Object> map = ((Map<Object, Object>) base); map.put(property, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } } }
// in java/javax/el/MapELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); return this.readOnly || UNMODIFIABLE.equals(base.getClass()); } return this.readOnly; }
// in java/javax/el/BeanELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); Method m = this.property(context, base, property).read(context); try { return m.invoke(base, (Object[]) null); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); return this.property(context, base, property).getPropertyType(); }
// in java/javax/el/BeanELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return; } context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } Method m = this.property(context, base, property).write(context); try { m.invoke(base, value); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return false; } context.setPropertyResolved(true); return this.readOnly || this.property(context, base, property).isReadOnly(); }
// in java/javax/el/BeanELResolver.java
Override public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) { if (context == null) { throw new NullPointerException(); } if (base == null) { return null; } try { BeanInfo info = Introspector.getBeanInfo(base.getClass()); PropertyDescriptor[] pds = info.getPropertyDescriptors(); for (int i = 0; i < pds.length; i++) { pds[i].setValue(RESOLVABLE_AT_DESIGN_TIME, Boolean.TRUE); pds[i].setValue(TYPE, pds[i].getPropertyType()); } return Arrays.asList((FeatureDescriptor[]) pds).iterator(); } catch (IntrospectionException e) { // } return null; }
// in java/javax/el/BeanELResolver.java
Override public Class<?> getCommonPropertyType(ELContext context, Object base) { if (context == null) { throw new NullPointerException(); } if (base != null) { return Object.class; } return null; }
// in java/javax/el/BeanELResolver.java
Override public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { if (context == null) { throw new NullPointerException(); } if (base == null || method == null) { return null; } ExpressionFactory factory = ExpressionFactory.newInstance(); String methodName = (String) factory.coerceToType(method, String.class); // Find the matching method Method matchingMethod = null; Class<?> clazz = base.getClass(); if (paramTypes != null) { try { matchingMethod = getMethod(clazz, clazz.getMethod(methodName, paramTypes)); } catch (NoSuchMethodException e) { throw new MethodNotFoundException(e); } } else { int paramCount = 0; if (params != null) { paramCount = params.length; } Method[] methods = clazz.getMethods(); for (Method m : methods) { if (methodName.equals(m.getName())) { if (m.getParameterTypes().length == paramCount) { // Same number of parameters - use the first match matchingMethod = getMethod(clazz, m); break; } if (m.isVarArgs() && paramCount > m.getParameterTypes().length - 2) { matchingMethod = getMethod(clazz, m); } } } if (matchingMethod == null) { throw new MethodNotFoundException( "Unable to find method [" + methodName + "] with [" + paramCount + "] parameters"); } } Class<?>[] parameterTypes = matchingMethod.getParameterTypes(); Object[] parameters = null; if (parameterTypes.length > 0) { parameters = new Object[parameterTypes.length]; @SuppressWarnings("null") // params.length >= parameterTypes.length int paramCount = params.length; if (matchingMethod.isVarArgs()) { int varArgIndex = parameterTypes.length - 1; // First argCount-1 parameters are standard for (int i = 0; (i < varArgIndex); i++) { parameters[i] = factory.coerceToType(params[i], parameterTypes[i]); } // Last parameter is the varargs Class<?> varArgClass = parameterTypes[varArgIndex].getComponentType(); final Object varargs = Array.newInstance( varArgClass, (paramCount - varArgIndex)); for (int i = (varArgIndex); i < paramCount; i++) { Array.set(varargs, i - varArgIndex, factory.coerceToType(params[i], varArgClass)); } parameters[varArgIndex] = varargs; } else { parameters = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { parameters[i] = factory.coerceToType(params[i], parameterTypes[i]); } } }
// in java/javax/el/ListELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { return null; } return list.get(idx); } return null; }
// in java/javax/el/ListELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return Object.class; } return null; }
// in java/javax/el/ListELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); @SuppressWarnings("unchecked") // Must be OK to cast to Object List<Object> list = (List<Object>) base; if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); try { list.set(idx, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); } } }
// in java/javax/el/ListELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return this.readOnly || UNMODIFIABLE.equals(list.getClass()); } return this.readOnly; }
0 43
              
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { return this.variableResolver.resolveVariable(property .toString()); } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getValue(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { Object obj = this.variableResolver.resolveVariable(property .toString()); return (obj != null) ? obj.getClass() : null; } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getType(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); throw new PropertyNotWritableException( "Legacy VariableResolver wrapped, not writable"); } if (!context.isPropertyResolved()) { elResolver.setValue(context, base, property, value); } }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return true; } return elResolver.isReadOnly(context, base, property); }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public MethodInfo getMethodInfo(ELContext context) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.getMethodInfo(context); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public Object invoke(ELContext context, Object[] params) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.invoke(context, params); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Class<?> getType(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getType(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public boolean isReadOnly(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.isReadOnly(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void setValue(ELContext context, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { try { this.target.setValue(context, value); } catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Object getValue(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getValue(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/catalina/servlets/CGIServlet.java
protected String[] hashToStringArray(Hashtable<String,?> h) throws NullPointerException { Vector<String> v = new Vector<String>(); Enumeration<String> e = h.keys(); while (e.hasMoreElements()) { String k = e.nextElement(); v.add(k + "=" + h.get(k).toString()); } String[] strArr = new String[v.size()]; v.copyInto(strArr); return strArr; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { PageContext page = (PageContext) context .getContext(JspContext.class); context.setPropertyResolved(true); switch (idx) { case APPLICATIONSCOPE: return ScopeManager.get(page).getApplicationScope(); case COOKIE: return ScopeManager.get(page).getCookie(); case HEADER: return ScopeManager.get(page).getHeader(); case HEADERVALUES: return ScopeManager.get(page).getHeaderValues(); case INITPARAM: return ScopeManager.get(page).getInitParam(); case PAGECONTEXT: return ScopeManager.get(page).getPageContext(); case PAGESCOPE: return ScopeManager.get(page).getPageScope(); case PARAM: return ScopeManager.get(page).getParam(); case PARAM_VALUES: return ScopeManager.get(page).getParamValues(); case REQUEST_SCOPE: return ScopeManager.get(page).getRequestScope(); case SESSION_SCOPE: return ScopeManager.get(page).getSessionScope(); } } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
public Class getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); throw new PropertyNotWritableException(); } } }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); return true; } } return false; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); return page.findAttribute(key); } } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Class<Object> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); int scope = page.getAttributesScope(key); if (scope != 0) { page.setAttribute(key, value, scope); } else { page.setAttribute(key, value); } } } }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); } return false; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); if (property != null) { try { return ((ResourceBundle) base).getObject(property .toString()); } catch (MissingResourceException mre) { return "???" + property.toString() + "???"; } } } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } }
// in java/javax/el/ResourceBundleELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return true; }
// in java/javax/el/CompositeELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; Object result = null; for (int i = 0; i < sz; i++) { result = this.resolvers[i].getValue(context, base, property); if (context.isPropertyResolved()) { return result; } } return null; }
// in java/javax/el/CompositeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { context.setPropertyResolved(false); int sz = this.size; for (int i = 0; i < sz; i++) { this.resolvers[i].setValue(context, base, property, value); if (context.isPropertyResolved()) { return; } } }
// in java/javax/el/CompositeELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; boolean readOnly = false; for (int i = 0; i < sz; i++) { readOnly = this.resolvers[i].isReadOnly(context, base, property); if (context.isPropertyResolved()) { return readOnly; } } return false; }
// in java/javax/el/CompositeELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; Class<?> type; for (int i = 0; i < sz; i++) { type = this.resolvers[i].getType(context, base, property); if (context.isPropertyResolved()) { if (SCOPED_ATTRIBUTE_EL_RESOLVER != null && SCOPED_ATTRIBUTE_EL_RESOLVER.isAssignableFrom( resolvers[i].getClass())) { // Special case since // javax.servlet.jsp.el.ScopedAttributeELResolver will // always return Object.class for type Object value = resolvers[i].getValue(context, base, property); if (value != null) { return value.getClass(); } } return type; } } return null; }
// in java/javax/el/ArrayELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); if (idx < 0 || idx >= Array.getLength(base)) { return null; } return Array.get(base, idx); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); return base.getClass().getComponentType(); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); checkBounds(base, idx); if (value != null && !base.getClass().getComponentType().isAssignableFrom( value.getClass())) { throw new ClassCastException(message(context, "objectNotAssignable", new Object[] {value.getClass().getName(), base.getClass().getComponentType().getName()})); } Array.set(base, idx, value); } }
// in java/javax/el/ArrayELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); } return this.readOnly; }
// in java/javax/el/MapELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return ((Map<?,?>) base).get(property); } return null; }
// in java/javax/el/MapELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/el/MapELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } try { @SuppressWarnings("unchecked") // Must be OK Map<Object, Object> map = ((Map<Object, Object>) base); map.put(property, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } } }
// in java/javax/el/MapELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); return this.readOnly || UNMODIFIABLE.equals(base.getClass()); } return this.readOnly; }
// in java/javax/el/BeanELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); Method m = this.property(context, base, property).read(context); try { return m.invoke(base, (Object[]) null); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); return this.property(context, base, property).getPropertyType(); }
// in java/javax/el/BeanELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return; } context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } Method m = this.property(context, base, property).write(context); try { m.invoke(base, value); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return false; } context.setPropertyResolved(true); return this.readOnly || this.property(context, base, property).isReadOnly(); }
// in java/javax/el/ListELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { return null; } return list.get(idx); } return null; }
// in java/javax/el/ListELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return Object.class; } return null; }
// in java/javax/el/ListELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); @SuppressWarnings("unchecked") // Must be OK to cast to Object List<Object> list = (List<Object>) base; if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); try { list.set(idx, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); } } }
// in java/javax/el/ListELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return this.readOnly || UNMODIFIABLE.equals(list.getClass()); } return this.readOnly; }
(Domain) ELException 59
              
// in java/org/apache/jasper/runtime/PageContextImpl.java
public static Object proprietaryEvaluate(final String expression, final Class<?> expectedType, final PageContext pageContext, final ProtectedFunctionMapper functionMap, final boolean escape) throws ELException { Object retValue; final ExpressionFactory exprFactory = jspf.getJspApplicationContext(pageContext.getServletContext()).getExpressionFactory(); if (SecurityUtil.isPackageProtectionEnabled()) { try { retValue = AccessController .doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { ELContextImpl ctx = (ELContextImpl) pageContext.getELContext(); ctx.setFunctionMapper(new FunctionMapperImpl(functionMap)); ValueExpression ve = exprFactory.createValueExpression(ctx, expression, expectedType); return ve.getValue(ctx); } }); } catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } } }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { return this.variableResolver.resolveVariable(property .toString()); } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getValue(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { Object obj = this.variableResolver.resolveVariable(property .toString()); return (obj != null) ? obj.getClass() : null; } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getType(context, base, property); } return null; }
// in java/org/apache/el/lang/ELSupport.java
public static final int compare(final Object obj0, final Object obj1) throws ELException { if (obj0 == obj1 || equals(obj0, obj1)) { return 0; } if (isBigDecimalOp(obj0, obj1)) { BigDecimal bd0 = (BigDecimal) coerceToNumber(obj0, BigDecimal.class); BigDecimal bd1 = (BigDecimal) coerceToNumber(obj1, BigDecimal.class); return bd0.compareTo(bd1); } if (isDoubleOp(obj0, obj1)) { Double d0 = (Double) coerceToNumber(obj0, Double.class); Double d1 = (Double) coerceToNumber(obj1, Double.class); return d0.compareTo(d1); } if (isBigIntegerOp(obj0, obj1)) { BigInteger bi0 = (BigInteger) coerceToNumber(obj0, BigInteger.class); BigInteger bi1 = (BigInteger) coerceToNumber(obj1, BigInteger.class); return bi0.compareTo(bi1); } if (isLongOp(obj0, obj1)) { Long l0 = (Long) coerceToNumber(obj0, Long.class); Long l1 = (Long) coerceToNumber(obj1, Long.class); return l0.compareTo(l1); } if (obj0 instanceof String || obj1 instanceof String) { return coerceToString(obj0).compareTo(coerceToString(obj1)); } if (obj0 instanceof Comparable<?>) { @SuppressWarnings("unchecked") // checked above final Comparable<Object> comparable = (Comparable<Object>) obj0; return (obj1 != null) ? comparable.compareTo(obj1) : 1; } if (obj1 instanceof Comparable<?>) { @SuppressWarnings("unchecked") // checked above final Comparable<Object> comparable = (Comparable<Object>) obj1; return (obj0 != null) ? -comparable.compareTo(obj0) : -1; } throw new ELException(MessageFactory.get("error.compare", obj0, obj1)); }
// in java/org/apache/el/lang/ELSupport.java
public static final Boolean coerceToBoolean(final Object obj) throws ELException { if (obj == null || "".equals(obj)) { return Boolean.FALSE; } if (obj instanceof Boolean) { return (Boolean) obj; } if (obj instanceof String) { return Boolean.valueOf((String) obj); } throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), Boolean.class)); }
// in java/org/apache/el/lang/ELSupport.java
public static final Character coerceToCharacter(final Object obj) throws ELException { if (obj == null || "".equals(obj)) { return Character.valueOf((char) 0); } if (obj instanceof String) { return Character.valueOf(((String) obj).charAt(0)); } if (ELArithmetic.isNumber(obj)) { return Character.valueOf((char) ((Number) obj).shortValue()); } Class<?> objType = obj.getClass(); if (obj instanceof Character) { return (Character) obj; } throw new ELException(MessageFactory.get("error.convert", obj, objType, Character.class)); }
// in java/org/apache/el/lang/ELSupport.java
protected static final Number coerceToNumber(final Number number, final Class<?> type) throws ELException { if (Long.TYPE == type || Long.class.equals(type)) { return Long.valueOf(number.longValue()); } if (Double.TYPE == type || Double.class.equals(type)) { return new Double(number.doubleValue()); } if (Integer.TYPE == type || Integer.class.equals(type)) { return Integer.valueOf(number.intValue()); } if (BigInteger.class.equals(type)) { if (number instanceof BigDecimal) { return ((BigDecimal) number).toBigInteger(); } if (number instanceof BigInteger) { return number; } return BigInteger.valueOf(number.longValue()); } if (BigDecimal.class.equals(type)) { if (number instanceof BigDecimal) { return number; } if (number instanceof BigInteger) { return new BigDecimal((BigInteger) number); } return new BigDecimal(number.doubleValue()); } if (Byte.TYPE == type || Byte.class.equals(type)) { return Byte.valueOf(number.byteValue()); } if (Short.TYPE == type || Short.class.equals(type)) { return Short.valueOf(number.shortValue()); } if (Float.TYPE == type || Float.class.equals(type)) { return new Float(number.floatValue()); } if (Number.class.equals(type)) { return number; } throw new ELException(MessageFactory.get("error.convert", number, number.getClass(), type)); }
// in java/org/apache/el/lang/ELSupport.java
public static final Number coerceToNumber(final Object obj, final Class<?> type) throws ELException { if (obj == null || "".equals(obj)) { return coerceToNumber(ZERO, type); } if (obj instanceof String) { return coerceToNumber((String) obj, type); } if (ELArithmetic.isNumber(obj)) { return coerceToNumber((Number) obj, type); } if (obj instanceof Character) { return coerceToNumber(Short.valueOf((short) ((Character) obj) .charValue()), type); } throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/lang/ELSupport.java
protected static final Number coerceToNumber(final String val, final Class<?> type) throws ELException { if (Long.TYPE == type || Long.class.equals(type)) { try { return Long.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Integer.TYPE == type || Integer.class.equals(type)) { try { return Integer.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Double.TYPE == type || Double.class.equals(type)) { try { return Double.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (BigInteger.class.equals(type)) { try { return new BigInteger(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (BigDecimal.class.equals(type)) { try { return new BigDecimal(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Byte.TYPE == type || Byte.class.equals(type)) { try { return Byte.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Short.TYPE == type || Short.class.equals(type)) { try { return Short.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Float.TYPE == type || Float.class.equals(type)) { try { return Float.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
public static final Object coerceToType(final Object obj, final Class<?> type) throws ELException { if (type == null || Object.class.equals(type) || (obj != null && type.isAssignableFrom(obj.getClass()))) { return obj; } if (String.class.equals(type)) { return coerceToString(obj); } if (ELArithmetic.isNumberType(type)) { return coerceToNumber(obj, type); } if (Character.class.equals(type) || Character.TYPE == type) { return coerceToCharacter(obj); } if (Boolean.class.equals(type) || Boolean.TYPE == type) { return coerceToBoolean(obj); } if (type.isEnum()) { return coerceToEnum(obj, type); } // new to spec if (obj == null) return null; if (obj instanceof String) { if ("".equals(obj)) return null; PropertyEditor editor = PropertyEditorManager.findEditor(type); if (editor != null) { editor.setAsText((String) obj); return editor.getValue(); } } throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/lang/ExpressionBuilder.java
private static final Node createNodeInternal(String expr) throws ELException { if (expr == null) { throw new ELException(MessageFactory.get("error.null")); } Node n = cache.get(expr); if (n == null) { try { n = (new ELParser(new StringReader(expr))) .CompositeExpression(); // validate composite expression int numChildren = n.jjtGetNumChildren(); if (numChildren == 1) { n = n.jjtGetChild(0); } else { Class<?> type = null; Node child = null; for (int i = 0; i < numChildren; i++) { child = n.jjtGetChild(i); if (child instanceof AstLiteralExpression) continue; if (type == null) type = child.getClass(); else { if (!type.equals(child.getClass())) { throw new ELException(MessageFactory.get( "error.mixed", expr)); } } } } if (n instanceof AstDeferredExpression || n instanceof AstDynamicExpression) { n = n.jjtGetChild(0); } cache.put(expr, n); } catch (Exception e) { throw new ELException( MessageFactory.get("error.parseFail", expr), e); } } return n; }
// in java/org/apache/el/lang/ExpressionBuilder.java
Override public void visit(Node node) throws ELException { if (node instanceof AstFunction) { AstFunction funcNode = (AstFunction) node; if (this.fnMapper == null) { throw new ELException(MessageFactory.get("error.fnMapper.null")); } Method m = fnMapper.resolveFunction(funcNode.getPrefix(), funcNode .getLocalName()); if (m == null) { throw new ELException(MessageFactory.get( "error.fnMapper.method", funcNode.getOutputName())); } int pcnt = m.getParameterTypes().length; if (node.jjtGetNumChildren() != pcnt) { throw new ELException(MessageFactory.get( "error.fnMapper.paramcount", funcNode.getOutputName(), "" + pcnt, "" + node.jjtGetNumChildren())); } } else if (node instanceof AstIdentifier && this.varMapper != null) { String variable = ((AstIdentifier) node).getImage(); // simply capture it this.varMapper.resolveVariable(variable); } }
// in java/org/apache/el/lang/ExpressionBuilder.java
public MethodExpression createMethodExpression(Class<?> expectedReturnType, Class<?>[] expectedParamTypes) throws ELException { Node n = this.build(); if (!n.isParametersProvided() && expectedParamTypes == null) { throw new NullPointerException(MessageFactory .get("error.method.nullParms")); } if (n instanceof AstValue || n instanceof AstIdentifier) { return new MethodExpressionImpl(expression, n, this.fnMapper, this.varMapper, expectedReturnType, expectedParamTypes); } else if (n instanceof AstLiteralExpression) { return new MethodExpressionLiteral(expression, expectedReturnType, expectedParamTypes); } else { throw new ELException("Not a Valid Method Expression: " + expression); } }
// in java/org/apache/el/parser/AstFunction.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { FunctionMapper fnMapper = ctx.getFunctionMapper(); // quickly validate again for this request if (fnMapper == null) { throw new ELException(MessageFactory.get("error.fnMapper.null")); } Method m = fnMapper.resolveFunction(this.prefix, this.localName); if (m == null) { throw new ELException(MessageFactory.get("error.fnMapper.method", this.getOutputName())); } return m.getReturnType(); }
// in java/org/apache/el/parser/AstFunction.java
Override public Object getValue(EvaluationContext ctx) throws ELException { FunctionMapper fnMapper = ctx.getFunctionMapper(); // quickly validate again for this request if (fnMapper == null) { throw new ELException(MessageFactory.get("error.fnMapper.null")); } Method m = fnMapper.resolveFunction(this.prefix, this.localName); if (m == null) { throw new ELException(MessageFactory.get("error.fnMapper.method", this.getOutputName())); } Class<?>[] paramTypes = m.getParameterTypes(); Object[] params = null; Object result = null; int numParams = this.jjtGetNumChildren(); if (numParams > 0) { params = new Object[numParams]; try { for (int i = 0; i < numParams; i++) { params[i] = this.children[i].getValue(ctx); params[i] = coerceToType(params[i], paramTypes[i]); } } catch (ELException ele) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), ele); } } try { result = m.invoke(null, params); } catch (IllegalAccessException iae) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), iae); } catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(MessageFactory.get("error.function", this .getOutputName()), cause); } return result; }
// in java/org/apache/el/parser/AstIdentifier.java
Override public void setImage(String image) { if (!Validation.isIdentifier(image)) { throw new ELException(MessageFactory.get("error.identifier.notjava", image)); } this.image = image; }
// in java/org/apache/el/parser/AstIdentifier.java
private final MethodExpression getMethodExpression(EvaluationContext ctx) throws ELException { Object obj = null; // case A: ValueExpression exists, getValue which must // be a MethodExpression VariableMapper varMapper = ctx.getVariableMapper(); ValueExpression ve = null; if (varMapper != null) { ve = varMapper.resolveVariable(this.image); if (ve != null) { obj = ve.getValue(ctx); } } // case B: evaluate the identity against the ELResolver, again, must be // a MethodExpression to be able to invoke if (ve == null) { ctx.setPropertyResolved(false); obj = ctx.getELResolver().getValue(ctx, null, this.image); } // finally provide helpful hints if (obj instanceof MethodExpression) { return (MethodExpression) obj; } else if (obj == null) { throw new MethodNotFoundException("Identity '" + this.image + "' was null and was unable to invoke"); } else { throw new ELException( "Identity '" + this.image + "' does not reference a MethodExpression instance, returned type: " + obj.getClass().getName()); } }
// in java/org/apache/el/parser/AstDotSuffix.java
Override public void setImage(String image) { if (!Validation.isIdentifier(image)) { throw new ELException(MessageFactory.get("error.identifier.notjava", image)); } this.image = image; }
// in java/javax/el/ExpressionFactory.java
public static ExpressionFactory newInstance(Properties properties) { ExpressionFactory result = null; ClassLoader tccl = Thread.currentThread().getContextClassLoader(); CacheValue cacheValue; Class<?> clazz; if (tccl == null) { cacheValue = nullTcclFactory; } else { CacheKey key = new CacheKey(tccl); cacheValue = factoryCache.get(key); if (cacheValue == null) { CacheValue newCacheValue = new CacheValue(); cacheValue = factoryCache.putIfAbsent(key, newCacheValue); if (cacheValue == null) { cacheValue = newCacheValue; } } } final Lock readLock = cacheValue.getLock().readLock(); readLock.lock(); try { clazz = cacheValue.getFactoryClass(); } finally { readLock.unlock(); } if (clazz == null) { String className = null; try { final Lock writeLock = cacheValue.getLock().writeLock(); writeLock.lock(); try { className = cacheValue.getFactoryClassName(); if (className == null) { className = discoverClassName(tccl); cacheValue.setFactoryClassName(className); } if (tccl == null) { clazz = Class.forName(className); } else { clazz = tccl.loadClass(className); } cacheValue.setFactoryClass(clazz); } finally { writeLock.unlock(); } } catch (ClassNotFoundException e) { throw new ELException( "Unable to find ExpressionFactory of type: " + className, e); } } try { Constructor<?> constructor = null; // Do we need to look for a constructor that will take properties? if (properties != null) { try { constructor = clazz.getConstructor(Properties.class); } catch (SecurityException se) { throw new ELException(se); } catch (NoSuchMethodException nsme) { // This can be ignored // This is OK for this constructor not to exist } } if (constructor == null) { result = (ExpressionFactory) clazz.newInstance(); } else { result = (ExpressionFactory) constructor.newInstance(properties); } } catch (InstantiationException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); } catch (IllegalAccessException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); } catch (IllegalArgumentException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); } return result; }
// in java/javax/el/ExpressionFactory.java
private static String getClassNameServices(ClassLoader tccl) { InputStream is = null; if (tccl == null) { is = ClassLoader.getSystemResourceAsStream(SERVICE_RESOURCE_NAME); } else { is = tccl.getResourceAsStream(SERVICE_RESOURCE_NAME); } if (is != null) { String line = null; BufferedReader br = null; InputStreamReader isr = null; try { isr = new InputStreamReader(is, "UTF-8"); br = new BufferedReader(isr); line = br.readLine(); if (line != null && line.trim().length() > 0) { return line.trim(); } } catch (UnsupportedEncodingException e) { // Should never happen with UTF-8 // If it does - ignore & return null } catch (IOException e) { throw new ELException("Failed to read " + SERVICE_RESOURCE_NAME, e); } finally { try { if (br != null) { br.close(); } } catch (IOException ioe) {/*Ignore*/} try { if (isr != null) { isr.close(); } } catch (IOException ioe) {/*Ignore*/} try { is.close(); } catch (IOException ioe) {/*Ignore*/} } } return null; }
// in java/javax/el/ExpressionFactory.java
private static String getClassNameJreDir() { File file = new File(PROPERTY_FILE); if (file.canRead()) { InputStream is = null; try { is = new FileInputStream(file); Properties props = new Properties(); props.load(is); String value = props.getProperty(PROPERTY_NAME); if (value != null && value.trim().length() > 0) { return value.trim(); } } catch (FileNotFoundException e) { // Should not happen - ignore it if it does } catch (IOException e) { throw new ELException("Failed to read " + PROPERTY_FILE, e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { // Ignore } } } } return null; }
// in java/javax/el/BeanELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); Method m = this.property(context, base, property).read(context); try { return m.invoke(base, (Object[]) null); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return; } context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } Method m = this.property(context, base, property).write(context); try { m.invoke(base, value); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
39
              
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } }
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/el/lang/ELSupport.java
catch (IllegalArgumentException iae) { throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ExpressionBuilder.java
catch (Exception e) { throw new ELException( MessageFactory.get("error.parseFail", expr), e); }
// in java/org/apache/el/lang/ExpressionBuilder.java
catch (Exception e) { if (e instanceof ELException) { throw (ELException) e; } else { throw (new ELException(e)); } }
// in java/org/apache/el/parser/AstFunction.java
catch (ELException ele) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), ele); }
// in java/org/apache/el/parser/AstFunction.java
catch (IllegalAccessException iae) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), iae); }
// in java/org/apache/el/parser/AstFunction.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(MessageFactory.get("error.function", this .getOutputName()), cause); }
// in java/org/apache/el/parser/ELParser.java
catch (ParseException pe) { throw new ELException(pe.getMessage());
// in java/org/apache/el/parser/AstValue.java
catch (IllegalAccessException iae) { throw new ELException(iae); }
// in java/org/apache/el/parser/AstValue.java
catch (IllegalArgumentException iae) { throw new ELException(iae); }
// in java/org/apache/el/parser/AstValue.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
// in java/javax/el/ExpressionFactory.java
catch (ClassNotFoundException e) { throw new ELException( "Unable to find ExpressionFactory of type: " + className, e); }
// in java/javax/el/ExpressionFactory.java
catch (SecurityException se) { throw new ELException(se); }
// in java/javax/el/ExpressionFactory.java
catch (InstantiationException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/ExpressionFactory.java
catch (IllegalAccessException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/ExpressionFactory.java
catch (IllegalArgumentException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/ExpressionFactory.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { throw new ELException("Failed to read " + SERVICE_RESOURCE_NAME, e); }
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { throw new ELException("Failed to read " + PROPERTY_FILE, e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (Exception e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (Exception e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IntrospectionException ie) { throw new ELException(ie); }
// in java/javax/el/BeanELResolver.java
catch (IllegalArgumentException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
140
              
// in java/org/apache/jasper/runtime/PageContextImpl.java
public static Object proprietaryEvaluate(final String expression, final Class<?> expectedType, final PageContext pageContext, final ProtectedFunctionMapper functionMap, final boolean escape) throws ELException { Object retValue; final ExpressionFactory exprFactory = jspf.getJspApplicationContext(pageContext.getServletContext()).getExpressionFactory(); if (SecurityUtil.isPackageProtectionEnabled()) { try { retValue = AccessController .doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { ELContextImpl ctx = (ELContextImpl) pageContext.getELContext(); ctx.setFunctionMapper(new FunctionMapperImpl(functionMap)); ValueExpression ve = exprFactory.createValueExpression(ctx, expression, expectedType); return ve.getValue(ctx); } }); } catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } } }
// in java/org/apache/jasper/compiler/Node.java
public void validateEL(ExpressionFactory ef, ELContext ctx) throws ELException { if (this.el != null) { // determine exact type ef.createValueExpression(ctx, this.value, String.class); } }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { return this.variableResolver.resolveVariable(property .toString()); } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getValue(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { Object obj = this.variableResolver.resolveVariable(property .toString()); return (obj != null) ? obj.getClass() : null; } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getType(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); throw new PropertyNotWritableException( "Legacy VariableResolver wrapped, not writable"); } if (!context.isPropertyResolved()) { elResolver.setValue(context, base, property, value); } }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return true; } return elResolver.isReadOnly(context, base, property); }
// in java/org/apache/jasper/el/ExpressionImpl.java
Override public Object evaluate(VariableResolver vResolver) throws ELException { ELContext ctx = new ELContextImpl(new ELResolverImpl(vResolver)); return ve.getValue(ctx); }
// in java/org/apache/jasper/el/VariableResolverImpl.java
Override public Object resolveVariable(String pName) throws ELException { return this.ctx.getELResolver().getValue(this.ctx, null, pName); }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public MethodInfo getMethodInfo(ELContext context) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.getMethodInfo(context); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public Object invoke(ELContext context, Object[] params) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.invoke(context, params); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Class<?> getType(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getType(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public boolean isReadOnly(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.isReadOnly(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void setValue(ELContext context, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { try { this.target.setValue(context, value); } catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Object getValue(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getValue(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/el/lang/ELSupport.java
public static final int compare(final Object obj0, final Object obj1) throws ELException { if (obj0 == obj1 || equals(obj0, obj1)) { return 0; } if (isBigDecimalOp(obj0, obj1)) { BigDecimal bd0 = (BigDecimal) coerceToNumber(obj0, BigDecimal.class); BigDecimal bd1 = (BigDecimal) coerceToNumber(obj1, BigDecimal.class); return bd0.compareTo(bd1); } if (isDoubleOp(obj0, obj1)) { Double d0 = (Double) coerceToNumber(obj0, Double.class); Double d1 = (Double) coerceToNumber(obj1, Double.class); return d0.compareTo(d1); } if (isBigIntegerOp(obj0, obj1)) { BigInteger bi0 = (BigInteger) coerceToNumber(obj0, BigInteger.class); BigInteger bi1 = (BigInteger) coerceToNumber(obj1, BigInteger.class); return bi0.compareTo(bi1); } if (isLongOp(obj0, obj1)) { Long l0 = (Long) coerceToNumber(obj0, Long.class); Long l1 = (Long) coerceToNumber(obj1, Long.class); return l0.compareTo(l1); } if (obj0 instanceof String || obj1 instanceof String) { return coerceToString(obj0).compareTo(coerceToString(obj1)); } if (obj0 instanceof Comparable<?>) { @SuppressWarnings("unchecked") // checked above final Comparable<Object> comparable = (Comparable<Object>) obj0; return (obj1 != null) ? comparable.compareTo(obj1) : 1; } if (obj1 instanceof Comparable<?>) { @SuppressWarnings("unchecked") // checked above final Comparable<Object> comparable = (Comparable<Object>) obj1; return (obj0 != null) ? -comparable.compareTo(obj0) : -1; } throw new ELException(MessageFactory.get("error.compare", obj0, obj1)); }
// in java/org/apache/el/lang/ELSupport.java
public static final boolean equals(final Object obj0, final Object obj1) throws ELException { if (obj0 == obj1) { return true; } else if (obj0 == null || obj1 == null) { return false; } else if (isBigDecimalOp(obj0, obj1)) { BigDecimal bd0 = (BigDecimal) coerceToNumber(obj0, BigDecimal.class); BigDecimal bd1 = (BigDecimal) coerceToNumber(obj1, BigDecimal.class); return bd0.equals(bd1); } else if (isDoubleOp(obj0, obj1)) { Double d0 = (Double) coerceToNumber(obj0, Double.class); Double d1 = (Double) coerceToNumber(obj1, Double.class); return d0.equals(d1); } else if (isBigIntegerOp(obj0, obj1)) { BigInteger bi0 = (BigInteger) coerceToNumber(obj0, BigInteger.class); BigInteger bi1 = (BigInteger) coerceToNumber(obj1, BigInteger.class); return bi0.equals(bi1); } else if (isLongOp(obj0, obj1)) { Long l0 = (Long) coerceToNumber(obj0, Long.class); Long l1 = (Long) coerceToNumber(obj1, Long.class); return l0.equals(l1); } else if (obj0 instanceof Boolean || obj1 instanceof Boolean) { return coerceToBoolean(obj0).equals(coerceToBoolean(obj1)); } else if (obj0.getClass().isEnum()) { return obj0.equals(coerceToEnum(obj1, obj0.getClass())); } else if (obj1.getClass().isEnum()) { return obj1.equals(coerceToEnum(obj0, obj1.getClass())); } else if (obj0 instanceof String || obj1 instanceof String) { int lexCompare = coerceToString(obj0).compareTo(coerceToString(obj1)); return (lexCompare == 0) ? true : false; } else { return obj0.equals(obj1); } }
// in java/org/apache/el/lang/ELSupport.java
public static final Boolean coerceToBoolean(final Object obj) throws ELException { if (obj == null || "".equals(obj)) { return Boolean.FALSE; } if (obj instanceof Boolean) { return (Boolean) obj; } if (obj instanceof String) { return Boolean.valueOf((String) obj); } throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), Boolean.class)); }
// in java/org/apache/el/lang/ELSupport.java
public static final Character coerceToCharacter(final Object obj) throws ELException { if (obj == null || "".equals(obj)) { return Character.valueOf((char) 0); } if (obj instanceof String) { return Character.valueOf(((String) obj).charAt(0)); } if (ELArithmetic.isNumber(obj)) { return Character.valueOf((char) ((Number) obj).shortValue()); } Class<?> objType = obj.getClass(); if (obj instanceof Character) { return (Character) obj; } throw new ELException(MessageFactory.get("error.convert", obj, objType, Character.class)); }
// in java/org/apache/el/lang/ELSupport.java
protected static final Number coerceToNumber(final Number number, final Class<?> type) throws ELException { if (Long.TYPE == type || Long.class.equals(type)) { return Long.valueOf(number.longValue()); } if (Double.TYPE == type || Double.class.equals(type)) { return new Double(number.doubleValue()); } if (Integer.TYPE == type || Integer.class.equals(type)) { return Integer.valueOf(number.intValue()); } if (BigInteger.class.equals(type)) { if (number instanceof BigDecimal) { return ((BigDecimal) number).toBigInteger(); } if (number instanceof BigInteger) { return number; } return BigInteger.valueOf(number.longValue()); } if (BigDecimal.class.equals(type)) { if (number instanceof BigDecimal) { return number; } if (number instanceof BigInteger) { return new BigDecimal((BigInteger) number); } return new BigDecimal(number.doubleValue()); } if (Byte.TYPE == type || Byte.class.equals(type)) { return Byte.valueOf(number.byteValue()); } if (Short.TYPE == type || Short.class.equals(type)) { return Short.valueOf(number.shortValue()); } if (Float.TYPE == type || Float.class.equals(type)) { return new Float(number.floatValue()); } if (Number.class.equals(type)) { return number; } throw new ELException(MessageFactory.get("error.convert", number, number.getClass(), type)); }
// in java/org/apache/el/lang/ELSupport.java
public static final Number coerceToNumber(final Object obj, final Class<?> type) throws ELException { if (obj == null || "".equals(obj)) { return coerceToNumber(ZERO, type); } if (obj instanceof String) { return coerceToNumber((String) obj, type); } if (ELArithmetic.isNumber(obj)) { return coerceToNumber((Number) obj, type); } if (obj instanceof Character) { return coerceToNumber(Short.valueOf((short) ((Character) obj) .charValue()), type); } throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/lang/ELSupport.java
protected static final Number coerceToNumber(final String val, final Class<?> type) throws ELException { if (Long.TYPE == type || Long.class.equals(type)) { try { return Long.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Integer.TYPE == type || Integer.class.equals(type)) { try { return Integer.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Double.TYPE == type || Double.class.equals(type)) { try { return Double.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (BigInteger.class.equals(type)) { try { return new BigInteger(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (BigDecimal.class.equals(type)) { try { return new BigDecimal(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Byte.TYPE == type || Byte.class.equals(type)) { try { return Byte.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Short.TYPE == type || Short.class.equals(type)) { try { return Short.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Float.TYPE == type || Float.class.equals(type)) { try { return Float.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
public static final Object coerceToType(final Object obj, final Class<?> type) throws ELException { if (type == null || Object.class.equals(type) || (obj != null && type.isAssignableFrom(obj.getClass()))) { return obj; } if (String.class.equals(type)) { return coerceToString(obj); } if (ELArithmetic.isNumberType(type)) { return coerceToNumber(obj, type); } if (Character.class.equals(type) || Character.TYPE == type) { return coerceToCharacter(obj); } if (Boolean.class.equals(type) || Boolean.TYPE == type) { return coerceToBoolean(obj); } if (type.isEnum()) { return coerceToEnum(obj, type); } // new to spec if (obj == null) return null; if (obj instanceof String) { if ("".equals(obj)) return null; PropertyEditor editor = PropertyEditorManager.findEditor(type); if (editor != null) { editor.setAsText((String) obj); return editor.getValue(); } } throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/lang/ExpressionBuilder.java
public static final Node createNode(String expr) throws ELException { Node n = createNodeInternal(expr); return n; }
// in java/org/apache/el/lang/ExpressionBuilder.java
private static final Node createNodeInternal(String expr) throws ELException { if (expr == null) { throw new ELException(MessageFactory.get("error.null")); } Node n = cache.get(expr); if (n == null) { try { n = (new ELParser(new StringReader(expr))) .CompositeExpression(); // validate composite expression int numChildren = n.jjtGetNumChildren(); if (numChildren == 1) { n = n.jjtGetChild(0); } else { Class<?> type = null; Node child = null; for (int i = 0; i < numChildren; i++) { child = n.jjtGetChild(i); if (child instanceof AstLiteralExpression) continue; if (type == null) type = child.getClass(); else { if (!type.equals(child.getClass())) { throw new ELException(MessageFactory.get( "error.mixed", expr)); } } } } if (n instanceof AstDeferredExpression || n instanceof AstDynamicExpression) { n = n.jjtGetChild(0); } cache.put(expr, n); } catch (Exception e) { throw new ELException( MessageFactory.get("error.parseFail", expr), e); } } return n; }
// in java/org/apache/el/lang/ExpressionBuilder.java
private void prepare(Node node) throws ELException { try { node.accept(this); } catch (Exception e) { if (e instanceof ELException) { throw (ELException) e; } else { throw (new ELException(e)); } } if (this.fnMapper instanceof FunctionMapperFactory) { this.fnMapper = ((FunctionMapperFactory) this.fnMapper).create(); } if (this.varMapper instanceof VariableMapperFactory) { this.varMapper = ((VariableMapperFactory) this.varMapper).create(); } }
// in java/org/apache/el/lang/ExpressionBuilder.java
private Node build() throws ELException { Node n = createNodeInternal(this.expression); this.prepare(n); if (n instanceof AstDeferredExpression || n instanceof AstDynamicExpression) { n = n.jjtGetChild(0); } return n; }
// in java/org/apache/el/lang/ExpressionBuilder.java
Override public void visit(Node node) throws ELException { if (node instanceof AstFunction) { AstFunction funcNode = (AstFunction) node; if (this.fnMapper == null) { throw new ELException(MessageFactory.get("error.fnMapper.null")); } Method m = fnMapper.resolveFunction(funcNode.getPrefix(), funcNode .getLocalName()); if (m == null) { throw new ELException(MessageFactory.get( "error.fnMapper.method", funcNode.getOutputName())); } int pcnt = m.getParameterTypes().length; if (node.jjtGetNumChildren() != pcnt) { throw new ELException(MessageFactory.get( "error.fnMapper.paramcount", funcNode.getOutputName(), "" + pcnt, "" + node.jjtGetNumChildren())); } } else if (node instanceof AstIdentifier && this.varMapper != null) { String variable = ((AstIdentifier) node).getImage(); // simply capture it this.varMapper.resolveVariable(variable); } }
// in java/org/apache/el/lang/ExpressionBuilder.java
public ValueExpression createValueExpression(Class<?> expectedType) throws ELException { Node n = this.build(); return new ValueExpressionImpl(this.expression, n, this.fnMapper, this.varMapper, expectedType); }
// in java/org/apache/el/lang/ExpressionBuilder.java
public MethodExpression createMethodExpression(Class<?> expectedReturnType, Class<?>[] expectedParamTypes) throws ELException { Node n = this.build(); if (!n.isParametersProvided() && expectedParamTypes == null) { throw new NullPointerException(MessageFactory .get("error.method.nullParms")); } if (n instanceof AstValue || n instanceof AstIdentifier) { return new MethodExpressionImpl(expression, n, this.fnMapper, this.varMapper, expectedReturnType, expectedParamTypes); } else if (n instanceof AstLiteralExpression) { return new MethodExpressionLiteral(expression, expectedReturnType, expectedParamTypes); } else { throw new ELException("Not a Valid Method Expression: " + expression); } }
// in java/org/apache/el/MethodExpressionImpl.java
Override public MethodInfo getMethodInfo(ELContext context) throws PropertyNotFoundException, MethodNotFoundException, ELException { Node n = this.getNode(); EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return n.getMethodInfo(ctx, this.paramTypes); }
// in java/org/apache/el/MethodExpressionImpl.java
private Node getNode() throws ELException { if (this.node == null) { this.node = ExpressionBuilder.createNode(this.expr); } return this.node; }
// in java/org/apache/el/MethodExpressionImpl.java
Override public Object invoke(ELContext context, Object[] params) throws PropertyNotFoundException, MethodNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return this.getNode().invoke(ctx, this.paramTypes, params); }
// in java/org/apache/el/MethodExpressionLiteral.java
Override public MethodInfo getMethodInfo(ELContext context) throws ELException { return new MethodInfo(this.expr, this.expectedType, this.paramTypes); }
// in java/org/apache/el/MethodExpressionLiteral.java
Override public Object invoke(ELContext context, Object[] params) throws ELException { if (this.expectedType != null) { return ELSupport.coerceToType(this.expr, this.expectedType); } else { return this.expr; } }
// in java/org/apache/el/parser/AstMult.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); return ELArithmetic.multiply(obj0, obj1); }
// in java/org/apache/el/parser/AstFunction.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { FunctionMapper fnMapper = ctx.getFunctionMapper(); // quickly validate again for this request if (fnMapper == null) { throw new ELException(MessageFactory.get("error.fnMapper.null")); } Method m = fnMapper.resolveFunction(this.prefix, this.localName); if (m == null) { throw new ELException(MessageFactory.get("error.fnMapper.method", this.getOutputName())); } return m.getReturnType(); }
// in java/org/apache/el/parser/AstFunction.java
Override public Object getValue(EvaluationContext ctx) throws ELException { FunctionMapper fnMapper = ctx.getFunctionMapper(); // quickly validate again for this request if (fnMapper == null) { throw new ELException(MessageFactory.get("error.fnMapper.null")); } Method m = fnMapper.resolveFunction(this.prefix, this.localName); if (m == null) { throw new ELException(MessageFactory.get("error.fnMapper.method", this.getOutputName())); } Class<?>[] paramTypes = m.getParameterTypes(); Object[] params = null; Object result = null; int numParams = this.jjtGetNumChildren(); if (numParams > 0) { params = new Object[numParams]; try { for (int i = 0; i < numParams; i++) { params[i] = this.children[i].getValue(ctx); params[i] = coerceToType(params[i], paramTypes[i]); } } catch (ELException ele) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), ele); } } try { result = m.invoke(null, params); } catch (IllegalAccessException iae) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), iae); } catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(MessageFactory.get("error.function", this .getOutputName()), cause); } return result; }
// in java/org/apache/el/parser/SimpleNode.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/el/parser/SimpleNode.java
Override public Object getValue(EvaluationContext ctx) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/el/parser/SimpleNode.java
Override public boolean isReadOnly(EvaluationContext ctx) throws ELException { return true; }
// in java/org/apache/el/parser/SimpleNode.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { throw new PropertyNotWritableException(MessageFactory.get("error.syntax.set")); }
// in java/org/apache/el/parser/SimpleNode.java
Override public Object invoke(EvaluationContext ctx, Class<?>[] paramTypes, Object[] paramValues) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/el/parser/SimpleNode.java
Override public MethodInfo getMethodInfo(EvaluationContext ctx, Class<?>[] paramTypes) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/el/parser/AstIdentifier.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { return expr.getType(ctx.getELContext()); } } ctx.setPropertyResolved(false); Class<?> result = ctx.getELResolver().getType(ctx, null, this.image); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } return result; }
// in java/org/apache/el/parser/AstIdentifier.java
Override public Object getValue(EvaluationContext ctx) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { return expr.getValue(ctx.getELContext()); } } ctx.setPropertyResolved(false); Object result = ctx.getELResolver().getValue(ctx, null, this.image); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } return result; }
// in java/org/apache/el/parser/AstIdentifier.java
Override public boolean isReadOnly(EvaluationContext ctx) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { return expr.isReadOnly(ctx.getELContext()); } } ctx.setPropertyResolved(false); boolean result = ctx.getELResolver().isReadOnly(ctx, null, this.image); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } return result; }
// in java/org/apache/el/parser/AstIdentifier.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { expr.setValue(ctx.getELContext(), value); return; } } ctx.setPropertyResolved(false); ctx.getELResolver().setValue(ctx, null, this.image, value); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } }
// in java/org/apache/el/parser/AstIdentifier.java
Override public Object invoke(EvaluationContext ctx, Class<?>[] paramTypes, Object[] paramValues) throws ELException { return this.getMethodExpression(ctx).invoke(ctx.getELContext(), paramValues); }
// in java/org/apache/el/parser/AstIdentifier.java
Override public MethodInfo getMethodInfo(EvaluationContext ctx, Class<?>[] paramTypes) throws ELException { return this.getMethodExpression(ctx).getMethodInfo(ctx.getELContext()); }
// in java/org/apache/el/parser/AstIdentifier.java
private final MethodExpression getMethodExpression(EvaluationContext ctx) throws ELException { Object obj = null; // case A: ValueExpression exists, getValue which must // be a MethodExpression VariableMapper varMapper = ctx.getVariableMapper(); ValueExpression ve = null; if (varMapper != null) { ve = varMapper.resolveVariable(this.image); if (ve != null) { obj = ve.getValue(ctx); } } // case B: evaluate the identity against the ELResolver, again, must be // a MethodExpression to be able to invoke if (ve == null) { ctx.setPropertyResolved(false); obj = ctx.getELResolver().getValue(ctx, null, this.image); } // finally provide helpful hints if (obj instanceof MethodExpression) { return (MethodExpression) obj; } else if (obj == null) { throw new MethodNotFoundException("Identity '" + this.image + "' was null and was unable to invoke"); } else { throw new ELException( "Identity '" + this.image + "' does not reference a MethodExpression instance, returned type: " + obj.getClass().getName()); } }
// in java/org/apache/el/parser/AstDeferredExpression.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return this.children[0].getType(ctx); }
// in java/org/apache/el/parser/AstDeferredExpression.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.children[0].getValue(ctx); }
// in java/org/apache/el/parser/AstDeferredExpression.java
Override public boolean isReadOnly(EvaluationContext ctx) throws ELException { return this.children[0].isReadOnly(ctx); }
// in java/org/apache/el/parser/AstDeferredExpression.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { this.children[0].setValue(ctx, value); }
// in java/org/apache/el/parser/AstString.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return String.class; }
// in java/org/apache/el/parser/AstString.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.getString(); }
// in java/org/apache/el/parser/AstEmpty.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return Boolean.class; }
// in java/org/apache/el/parser/AstEmpty.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj = this.children[0].getValue(ctx); if (obj == null) { return Boolean.TRUE; } else if (obj instanceof String) { return Boolean.valueOf(((String) obj).length() == 0); } else if (obj instanceof Object[]) { return Boolean.valueOf(((Object[]) obj).length == 0); } else if (obj instanceof Collection<?>) { return Boolean.valueOf(((Collection<?>) obj).isEmpty()); } else if (obj instanceof Map<?,?>) { return Boolean.valueOf(((Map<?,?>) obj).isEmpty()); } return Boolean.FALSE; }
// in java/org/apache/el/parser/ArithmeticNode.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return Number.class; }
// in java/org/apache/el/parser/AstNot.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return Boolean.class; }
// in java/org/apache/el/parser/AstNot.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj = this.children[0].getValue(ctx); Boolean b = coerceToBoolean(obj); return Boolean.valueOf(!b.booleanValue()); }
// in java/org/apache/el/parser/AstAnd.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj = children[0].getValue(ctx); Boolean b = coerceToBoolean(obj); if (!b.booleanValue()) { return b; } obj = children[1].getValue(ctx); b = coerceToBoolean(obj); return b; }
// in java/org/apache/el/parser/AstDotSuffix.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.image; }
// in java/org/apache/el/parser/AstGreaterThanEqual.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); if (obj0 == obj1) { return Boolean.TRUE; } if (obj0 == null || obj1 == null) { return Boolean.FALSE; } return (compare(obj0, obj1) >= 0) ? Boolean.TRUE : Boolean.FALSE; }
// in java/org/apache/el/parser/AstInteger.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return this.getInteger().getClass(); }
// in java/org/apache/el/parser/AstInteger.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.getInteger(); }
// in java/org/apache/el/parser/AstGreaterThan.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); if (obj0 == null) { return Boolean.FALSE; } Object obj1 = this.children[1].getValue(ctx); if (obj1 == null) { return Boolean.FALSE; } return (compare(obj0, obj1) > 0) ? Boolean.TRUE : Boolean.FALSE; }
// in java/org/apache/el/parser/AstBracketSuffix.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.children[0].getValue(ctx); }
// in java/org/apache/el/parser/AstLiteralExpression.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return String.class; }
// in java/org/apache/el/parser/AstLiteralExpression.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.image; }
// in java/org/apache/el/parser/AstFalse.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return Boolean.FALSE; }
// in java/org/apache/el/parser/AstPlus.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); return ELArithmetic.add(obj0, obj1); }
// in java/org/apache/el/parser/AstDiv.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); return ELArithmetic.divide(obj0, obj1); }
// in java/org/apache/el/parser/AstLessThan.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); if (obj0 == null) { return Boolean.FALSE; } Object obj1 = this.children[1].getValue(ctx); if (obj1 == null) { return Boolean.FALSE; } return (compare(obj0, obj1) < 0) ? Boolean.TRUE : Boolean.FALSE; }
// in java/org/apache/el/parser/AstNull.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return null; }
// in java/org/apache/el/parser/AstNull.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return null; }
// in java/org/apache/el/parser/AstMod.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); return ELArithmetic.mod(obj0, obj1); }
// in java/org/apache/el/parser/AstChoice.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { Object val = this.getValue(ctx); return (val != null) ? val.getClass() : null; }
// in java/org/apache/el/parser/AstChoice.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Boolean b0 = coerceToBoolean(obj0); return this.children[((b0.booleanValue() ? 1 : 2))].getValue(ctx); }
// in java/org/apache/el/parser/AstDynamicExpression.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return this.children[0].getType(ctx); }
// in java/org/apache/el/parser/AstDynamicExpression.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.children[0].getValue(ctx); }
// in java/org/apache/el/parser/AstDynamicExpression.java
Override public boolean isReadOnly(EvaluationContext ctx) throws ELException { return this.children[0].isReadOnly(ctx); }
// in java/org/apache/el/parser/AstDynamicExpression.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { this.children[0].setValue(ctx, value); }
// in java/org/apache/el/parser/AstNotEqual.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); return Boolean.valueOf(!equals(obj0, obj1)); }
// in java/org/apache/el/parser/AstCompositeExpression.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return String.class; }
// in java/org/apache/el/parser/AstCompositeExpression.java
Override public Object getValue(EvaluationContext ctx) throws ELException { StringBuilder sb = new StringBuilder(16); Object obj = null; if (this.children != null) { for (int i = 0; i < this.children.length; i++) { obj = this.children[i].getValue(ctx); if (obj != null) { sb.append(ELSupport.coerceToString(obj)); } } } return sb.toString(); }
// in java/org/apache/el/parser/AstOr.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj = this.children[0].getValue(ctx); Boolean b = coerceToBoolean(obj); if (b.booleanValue()) { return b; } obj = this.children[1].getValue(ctx); b = coerceToBoolean(obj); return b; }
// in java/org/apache/el/parser/AstMinus.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); return ELArithmetic.subtract(obj0, obj1); }
// in java/org/apache/el/parser/AstFloatingPoint.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.getFloatingPoint(); }
// in java/org/apache/el/parser/AstFloatingPoint.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return this.getFloatingPoint().getClass(); }
// in java/org/apache/el/parser/AstNegative.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return Number.class; }
// in java/org/apache/el/parser/AstNegative.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj = this.children[0].getValue(ctx); if (obj == null) { return Long.valueOf(0); } if (obj instanceof BigDecimal) { return ((BigDecimal) obj).negate(); } if (obj instanceof BigInteger) { return ((BigInteger) obj).negate(); } if (obj instanceof String) { if (isStringFloat((String) obj)) { return new Double(-Double.parseDouble((String) obj)); } return Long.valueOf(-Long.parseLong((String) obj)); } if (obj instanceof Long) { return Long.valueOf(-((Long) obj).longValue()); } if (obj instanceof Double) { return new Double(-((Double) obj).doubleValue()); } if (obj instanceof Integer) { return Integer.valueOf(-((Integer) obj).intValue()); } if (obj instanceof Float) { return new Float(-((Float) obj).floatValue()); } if (obj instanceof Short) { return Short.valueOf((short) -((Short) obj).shortValue()); } if (obj instanceof Byte) { return Byte.valueOf((byte) -((Byte) obj).byteValue()); } Long num = (Long) coerceToNumber(obj, Long.class); return Long.valueOf(-num.longValue()); }
// in java/org/apache/el/parser/AstLessThanEqual.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); if (obj0 == obj1) { return Boolean.TRUE; } if (obj0 == null || obj1 == null) { return Boolean.FALSE; } return (compare(obj0, obj1) <= 0) ? Boolean.TRUE : Boolean.FALSE; }
// in java/org/apache/el/parser/AstTrue.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return Boolean.TRUE; }
// in java/org/apache/el/parser/AstEqual.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); return Boolean.valueOf(equals(obj0, obj1)); }
// in java/org/apache/el/parser/AstValue.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { Target t = getTarget(ctx); ctx.setPropertyResolved(false); Class<?> result = ctx.getELResolver().getType(ctx, t.base, t.property); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", t.base, t.property)); } return result; }
// in java/org/apache/el/parser/AstValue.java
private final Target getTarget(EvaluationContext ctx) throws ELException { // evaluate expr-a to value-a Object base = this.children[0].getValue(ctx); // if our base is null (we know there are more properties to evaluate) if (base == null) { throw new PropertyNotFoundException(MessageFactory.get( "error.unreachable.base", this.children[0].getImage())); } // set up our start/end Object property = null; int propCount = this.jjtGetNumChildren(); if (propCount > 2 && this.jjtGetChild(propCount - 1) instanceof AstMethodParameters) { // Method call with paramaters. propCount-=2; } else { propCount--; } int i = 1; // evaluate any properties before our target ELResolver resolver = ctx.getELResolver(); if (propCount > 1) { while (base != null && i < propCount) { property = this.children[i].getValue(ctx); ctx.setPropertyResolved(false); base = resolver.getValue(ctx, base, property); i++; } // if we are in this block, we have more properties to resolve, // but our base was null if (base == null || property == null) { throw new PropertyNotFoundException(MessageFactory.get( "error.unreachable.property", property)); } } property = this.children[i].getValue(ctx); if (property == null) { throw new PropertyNotFoundException(MessageFactory.get( "error.unreachable.property", this.children[i])); } Target t = new Target(); t.base = base; t.property = property; return t; }
// in java/org/apache/el/parser/AstValue.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object base = this.children[0].getValue(ctx); int propCount = this.jjtGetNumChildren(); int i = 1; Object suffix = null; ELResolver resolver = ctx.getELResolver(); while (base != null && i < propCount) { suffix = this.children[i].getValue(ctx); if (i + 1 < propCount && (this.children[i+1] instanceof AstMethodParameters)) { AstMethodParameters mps = (AstMethodParameters) this.children[i+1]; // This is a method base = resolver.invoke(ctx, base, suffix, null, mps.getParameters(ctx)); i+=2; } else { // This is a property if (suffix == null) { return null; } ctx.setPropertyResolved(false); base = resolver.getValue(ctx, base, suffix); i++; } } if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", base, suffix)); } return base; }
// in java/org/apache/el/parser/AstValue.java
Override public boolean isReadOnly(EvaluationContext ctx) throws ELException { Target t = getTarget(ctx); ctx.setPropertyResolved(false); boolean result = ctx.getELResolver().isReadOnly(ctx, t.base, t.property); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", t.base, t.property)); } return result; }
// in java/org/apache/el/parser/AstValue.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { Target t = getTarget(ctx); ctx.setPropertyResolved(false); ELResolver resolver = ctx.getELResolver(); // coerce to the expected type Class<?> targetClass = resolver.getType(ctx, t.base, t.property); if (COERCE_TO_ZERO == true || !isAssignable(value, targetClass)) { resolver.setValue(ctx, t.base, t.property, ELSupport.coerceToType(value, targetClass)); } else { resolver.setValue(ctx, t.base, t.property, value); } if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", t.base, t.property)); } }
// in java/org/apache/el/parser/BooleanNode.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return Boolean.class; }
// in java/org/apache/el/ValueExpressionImpl.java
private Node getNode() throws ELException { if (this.node == null) { this.node = ExpressionBuilder.createNode(this.expr); } return this.node; }
// in java/org/apache/el/ValueExpressionImpl.java
Override public Class<?> getType(ELContext context) throws PropertyNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return this.getNode().getType(ctx); }
// in java/org/apache/el/ValueExpressionImpl.java
Override public Object getValue(ELContext context) throws PropertyNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); Object value = this.getNode().getValue(ctx); if (this.expectedType != null) { return ELSupport.coerceToType(value, this.expectedType); } return value; }
// in java/org/apache/el/ValueExpressionImpl.java
Override public boolean isReadOnly(ELContext context) throws PropertyNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return this.getNode().isReadOnly(ctx); }
// in java/org/apache/el/ValueExpressionImpl.java
Override public void setValue(ELContext context, Object value) throws PropertyNotFoundException, PropertyNotWritableException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); this.getNode().setValue(ctx, value); }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { PageContext page = (PageContext) context .getContext(JspContext.class); context.setPropertyResolved(true); switch (idx) { case APPLICATIONSCOPE: return ScopeManager.get(page).getApplicationScope(); case COOKIE: return ScopeManager.get(page).getCookie(); case HEADER: return ScopeManager.get(page).getHeader(); case HEADERVALUES: return ScopeManager.get(page).getHeaderValues(); case INITPARAM: return ScopeManager.get(page).getInitParam(); case PAGECONTEXT: return ScopeManager.get(page).getPageContext(); case PAGESCOPE: return ScopeManager.get(page).getPageScope(); case PARAM: return ScopeManager.get(page).getParam(); case PARAM_VALUES: return ScopeManager.get(page).getParamValues(); case REQUEST_SCOPE: return ScopeManager.get(page).getRequestScope(); case SESSION_SCOPE: return ScopeManager.get(page).getSessionScope(); } } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
public Class getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); throw new PropertyNotWritableException(); } } }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); return true; } } return false; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); return page.findAttribute(key); } } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Class<Object> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); int scope = page.getAttributesScope(key); if (scope != 0) { page.setAttribute(key, value, scope); } else { page.setAttribute(key, value); } } } }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); } return false; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); if (property != null) { try { return ((ResourceBundle) base).getObject(property .toString()); } catch (MissingResourceException mre) { return "???" + property.toString() + "???"; } } } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } }
// in java/javax/el/ResourceBundleELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return true; }
// in java/javax/el/CompositeELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; Object result = null; for (int i = 0; i < sz; i++) { result = this.resolvers[i].getValue(context, base, property); if (context.isPropertyResolved()) { return result; } } return null; }
// in java/javax/el/CompositeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { context.setPropertyResolved(false); int sz = this.size; for (int i = 0; i < sz; i++) { this.resolvers[i].setValue(context, base, property, value); if (context.isPropertyResolved()) { return; } } }
// in java/javax/el/CompositeELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; boolean readOnly = false; for (int i = 0; i < sz; i++) { readOnly = this.resolvers[i].isReadOnly(context, base, property); if (context.isPropertyResolved()) { return readOnly; } } return false; }
// in java/javax/el/CompositeELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; Class<?> type; for (int i = 0; i < sz; i++) { type = this.resolvers[i].getType(context, base, property); if (context.isPropertyResolved()) { if (SCOPED_ATTRIBUTE_EL_RESOLVER != null && SCOPED_ATTRIBUTE_EL_RESOLVER.isAssignableFrom( resolvers[i].getClass())) { // Special case since // javax.servlet.jsp.el.ScopedAttributeELResolver will // always return Object.class for type Object value = resolvers[i].getValue(context, base, property); if (value != null) { return value.getClass(); } } return type; } } return null; }
// in java/javax/el/ArrayELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); if (idx < 0 || idx >= Array.getLength(base)) { return null; } return Array.get(base, idx); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); return base.getClass().getComponentType(); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); checkBounds(base, idx); if (value != null && !base.getClass().getComponentType().isAssignableFrom( value.getClass())) { throw new ClassCastException(message(context, "objectNotAssignable", new Object[] {value.getClass().getName(), base.getClass().getComponentType().getName()})); } Array.set(base, idx, value); } }
// in java/javax/el/ArrayELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); } return this.readOnly; }
// in java/javax/el/MapELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return ((Map<?,?>) base).get(property); } return null; }
// in java/javax/el/MapELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/el/MapELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } try { @SuppressWarnings("unchecked") // Must be OK Map<Object, Object> map = ((Map<Object, Object>) base); map.put(property, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } } }
// in java/javax/el/MapELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); return this.readOnly || UNMODIFIABLE.equals(base.getClass()); } return this.readOnly; }
// in java/javax/el/BeanELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); Method m = this.property(context, base, property).read(context); try { return m.invoke(base, (Object[]) null); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); return this.property(context, base, property).getPropertyType(); }
// in java/javax/el/BeanELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return; } context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } Method m = this.property(context, base, property).write(context); try { m.invoke(base, value); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return false; } context.setPropertyResolved(true); return this.readOnly || this.property(context, base, property).isReadOnly(); }
// in java/javax/el/ListELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { return null; } return list.get(idx); } return null; }
// in java/javax/el/ListELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return Object.class; } return null; }
// in java/javax/el/ListELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); @SuppressWarnings("unchecked") // Must be OK to cast to Object List<Object> list = (List<Object>) base; if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); try { list.set(idx, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); } } }
// in java/javax/el/ListELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return this.readOnly || UNMODIFIABLE.equals(list.getClass()); } return this.readOnly; }
(Domain) JasperException 59
              
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object convert(String propertyName, String s, Class<?> t, Class<?> propertyEditorClass) throws JasperException { try { if (s == null) { if (t.equals(Boolean.class) || t.equals(Boolean.TYPE)) s = "false"; else return null; } if (propertyEditorClass != null) { return getValueFromBeanInfoPropertyEditor( t, propertyName, s, propertyEditorClass); } else if ( t.equals(Boolean.class) || t.equals(Boolean.TYPE) ) { if (s.equalsIgnoreCase("on") || s.equalsIgnoreCase("true")) s = "true"; else s = "false"; return Boolean.valueOf(s); } else if ( t.equals(Byte.class) || t.equals(Byte.TYPE) ) { return Byte.valueOf(s); } else if (t.equals(Character.class) || t.equals(Character.TYPE)) { return s.length() > 0 ? Character.valueOf(s.charAt(0)) : null; } else if ( t.equals(Short.class) || t.equals(Short.TYPE) ) { return Short.valueOf(s); } else if ( t.equals(Integer.class) || t.equals(Integer.TYPE) ) { return Integer.valueOf(s); } else if ( t.equals(Float.class) || t.equals(Float.TYPE) ) { return Float.valueOf(s); } else if ( t.equals(Long.class) || t.equals(Long.TYPE) ) { return Long.valueOf(s); } else if ( t.equals(Double.class) || t.equals(Double.TYPE) ) { return Double.valueOf(s); } else if ( t.equals(String.class) ) { return s; } else if ( t.equals(java.io.File.class) ) { return new java.io.File(s); } else if (t.getName().equals("java.lang.Object")) { return new Object[] {s}; } else { return getValueFromPropertyEditorManager( t, propertyName, s); } } catch (Exception ex) { throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
private static void internalIntrospecthelper(Object bean, String prop, String value, ServletRequest request, String param, boolean ignoreMethodNF) throws JasperException { Method method = null; Class<?> type = null; Class<?> propertyEditorClass = null; try { java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(bean.getClass()); if ( info != null ) { java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); for (int i = 0 ; i < pd.length ; i++) { if ( pd[i].getName().equals(prop) ) { method = pd[i].getWriteMethod(); type = pd[i].getPropertyType(); propertyEditorClass = pd[i].getPropertyEditorClass(); break; } } } if ( method != null ) { if (type.isArray()) { if (request == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.setproperty.noindexset")); } Class<?> t = type.getComponentType(); String[] values = request.getParameterValues(param); //XXX Please check. if(values == null) return; if(t.equals(String.class)) { method.invoke(bean, new Object[] { values }); } else { createTypedArray (prop, bean, method, values, t, propertyEditorClass); } } else { if(value == null || (param != null && value.equals(""))) return; Object oval = convert(prop, value, type, propertyEditorClass); if ( oval != null ) method.invoke(bean, new Object[] { oval }); } } } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } if (!ignoreMethodNF && (method == null)) { if (type == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.noproperty", prop, bean.getClass().getName())); } else { throw new JasperException( Localizer.getMessage("jsp.error.beans.nomethod.setproperty", prop, type.getName(), bean.getClass().getName())); } } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void createTypedArray(String propertyName, Object bean, Method method, String[] values, Class<?> t, Class<?> propertyEditorClass) throws JasperException { try { if (propertyEditorClass != null) { Object[] tmpval = new Integer[values.length]; for (int i=0; i<values.length; i++) { tmpval[i] = getValueFromBeanInfoPropertyEditor( t, propertyName, values[i], propertyEditorClass); } method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Integer.class)) { Integer []tmpval = new Integer[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Integer (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Byte.class)) { Byte[] tmpval = new Byte[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Byte (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Boolean.class)) { Boolean[] tmpval = new Boolean[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Boolean.valueOf(values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Short.class)) { Short[] tmpval = new Short[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Short (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Long.class)) { Long[] tmpval = new Long[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Long (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Double.class)) { Double[] tmpval = new Double[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Double (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Float.class)) { Float[] tmpval = new Float[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Float (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Character.class)) { Character[] tmpval = new Character[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Character.valueOf(values[i].charAt(0)); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(int.class)) { int []tmpval = new int[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Integer.parseInt (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(byte.class)) { byte[] tmpval = new byte[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Byte.parseByte (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(boolean.class)) { boolean[] tmpval = new boolean[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = (Boolean.valueOf(values[i])).booleanValue(); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(short.class)) { short[] tmpval = new short[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Short.parseShort (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(long.class)) { long[] tmpval = new long[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Long.parseLong (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(double.class)) { double[] tmpval = new double[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Double.valueOf(values[i]).doubleValue(); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(float.class)) { float[] tmpval = new float[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Float.valueOf(values[i]).floatValue(); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(char.class)) { char[] tmpval = new char[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = values[i].charAt(0); method.invoke (bean, new Object[] {tmpval}); } else { Object[] tmpval = new Integer[values.length]; for (int i=0; i<values.length; i++) { tmpval[i] = getValueFromPropertyEditorManager( t, propertyName, values[i]); } method.invoke (bean, new Object[] {tmpval}); } } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException ("error in invoking method", ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object handleGetProperty(Object o, String prop) throws JasperException { if (o == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.nullbean")); } Object value = null; try { Method method = getReadMethod(o.getClass(), prop); value = method.invoke(o, (Object[]) null); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException (ex); } return value; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetPropertyExpression(Object bean, String prop, String expression, PageContext pageContext, ProtectedFunctionMapper functionMapper ) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { PageContextImpl.proprietaryEvaluate( expression, method.getParameterTypes()[0], pageContext, functionMapper, false ) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, Object value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { value }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, int value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Integer.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, short value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Short.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, long value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Long.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, double value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Double.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, float value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Float.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, char value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Character.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, byte value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Byte.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, boolean value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Boolean.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Method getWriteMethod(Class<?> beanClass, String prop) throws JasperException { Method method = null; Class<?> type = null; try { java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(beanClass); if ( info != null ) { java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); for (int i = 0 ; i < pd.length ; i++) { if ( pd[i].getName().equals(prop) ) { method = pd[i].getWriteMethod(); type = pd[i].getPropertyType(); break; } } } else { // just in case introspection silently fails. throw new JasperException( Localizer.getMessage("jsp.error.beans.nobeaninfo", beanClass.getName())); } } catch (Exception ex) { throw new JasperException (ex); } if (method == null) { if (type == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.noproperty", prop, beanClass.getName())); } else { throw new JasperException( Localizer.getMessage("jsp.error.beans.nomethod.setproperty", prop, type.getName(), beanClass.getName())); } } return method; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Method getReadMethod(Class<?> beanClass, String prop) throws JasperException { Method method = null; Class<?> type = null; try { java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(beanClass); if ( info != null ) { java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); for (int i = 0 ; i < pd.length ; i++) { if ( pd[i].getName().equals(prop) ) { method = pd[i].getReadMethod(); type = pd[i].getPropertyType(); break; } } } else { // just in case introspection silently fails. throw new JasperException( Localizer.getMessage("jsp.error.beans.nobeaninfo", beanClass.getName())); } } catch (Exception ex) { throw new JasperException (ex); } if (method == null) { if (type == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.noproperty", prop, beanClass.getName())); } else { throw new JasperException( Localizer.getMessage("jsp.error.beans.nomethod", prop, beanClass.getName())); } } return method; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object getValueFromBeanInfoPropertyEditor( Class<?> attrClass, String attrName, String attrValue, Class<?> propertyEditorClass) throws JasperException { try { PropertyEditor pe = (PropertyEditor)propertyEditorClass.newInstance(); pe.setAsText(attrValue); return pe.getValue(); } catch (Exception ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object getValueFromPropertyEditorManager( Class<?> attrClass, String attrName, String attrValue) throws JasperException { try { PropertyEditor propEditor = PropertyEditorManager.findEditor(attrClass); if (propEditor != null) { propEditor.setAsText(attrValue); return propEditor.getValue(); } else { throw new IllegalArgumentException( Localizer.getMessage("jsp.error.beans.propertyeditor.notregistered")); } } catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); } }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void jspError(String fname, int line, int column, String errMsg, Exception ex) throws JasperException { throw new JasperException(fname + " (" + Localizer.getMessage("jsp.error.location", Integer.toString(line), Integer.toString(column)) + ") " + errMsg, ex); }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void jspError(String errMsg, Exception ex) throws JasperException { throw new JasperException(errMsg, ex); }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void javacError(JavacErrorDetail[] details) throws JasperException { if (details == null) { return; } Object[] args = null; StringBuilder buf = new StringBuilder(); for (int i=0; i < details.length; i++) { if (details[i].getJspBeginLineNumber() >= 0) { args = new Object[] { Integer.valueOf(details[i].getJspBeginLineNumber()), details[i].getJspFileName() }; buf.append(Constants.NEWLINE); buf.append(Constants.NEWLINE); buf.append(Localizer.getMessage("jsp.error.single.line.number", args)); buf.append(Constants.NEWLINE); buf.append(details[i].getErrorMessage()); buf.append(Constants.NEWLINE); buf.append(details[i].getJspExtract()); } else { args = new Object[] { Integer.valueOf(details[i].getJavaLineNumber()) }; buf.append(Constants.NEWLINE); buf.append(Constants.NEWLINE); buf.append(Localizer.getMessage("jsp.error.java.line.number", args)); buf.append(Constants.NEWLINE); buf.append(details[i].getErrorMessage()); } } buf.append(Constants.NEWLINE); buf.append(Constants.NEWLINE); buf.append("Stacktrace:"); throw new JasperException( Localizer.getMessage("jsp.error.unable.compile") + ": " + buf); }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void javacError(String errorReport, Exception exception) throws JasperException { throw new JasperException( Localizer.getMessage("jsp.error.unable.compile"), exception); }
// in java/org/apache/jasper/compiler/ParserController.java
private void determineSyntaxAndEncoding(String absFileName, JarFile jarFile, String jspConfigPageEnc) throws JasperException, IOException { isXml = false; /* * 'true' if the syntax (XML or standard) of the file is given * from external information: either via a JSP configuration element, * the ".jspx" suffix, or the enclosing file (for included resources) */ boolean isExternal = false; /* * Indicates whether we need to revert from temporary usage of * "ISO-8859-1" back to "UTF-8" */ boolean revert = false; JspConfig jspConfig = ctxt.getOptions().getJspConfig(); JspConfig.JspProperty jspProperty = jspConfig.findJspProperty( absFileName); if (jspProperty.isXml() != null) { // If <is-xml> is specified in a <jsp-property-group>, it is used. isXml = JspUtil.booleanValue(jspProperty.isXml()); isExternal = true; } else if (absFileName.endsWith(".jspx") || absFileName.endsWith(".tagx")) { isXml = true; isExternal = true; } if (isExternal && !isXml) { // JSP (standard) syntax. Use encoding specified in jsp-config // if provided. sourceEnc = jspConfigPageEnc; if (sourceEnc != null) { return; } // We don't know the encoding, so use BOM to determine it sourceEnc = "ISO-8859-1"; } else { // XML syntax or unknown, (auto)detect encoding ... Object[] ret = XMLEncodingDetector.getEncoding(absFileName, jarFile, ctxt, err); sourceEnc = (String) ret[0]; if (((Boolean) ret[1]).booleanValue()) { isEncodingSpecifiedInProlog = true; } if (((Boolean) ret[2]).booleanValue()) { isBomPresent = true; } skip = ((Integer) ret[3]).intValue(); if (!isXml && sourceEnc.equals("UTF-8")) { /* * We don't know if we're dealing with XML or standard syntax. * Therefore, we need to check to see if the page contains * a <jsp:root> element. * * We need to be careful, because the page may be encoded in * ISO-8859-1 (or something entirely different), and may * contain byte sequences that will cause a UTF-8 converter to * throw exceptions. * * It is safe to use a source encoding of ISO-8859-1 in this * case, as there are no invalid byte sequences in ISO-8859-1, * and the byte/character sequences we're looking for (i.e., * <jsp:root>) are identical in either encoding (both UTF-8 * and ISO-8859-1 are extensions of ASCII). */ sourceEnc = "ISO-8859-1"; revert = true; } } if (isXml) { // (This implies 'isExternal' is TRUE.) // We know we're dealing with a JSP document (via JSP config or // ".jspx" suffix), so we're done. return; } /* * At this point, 'isExternal' or 'isXml' is FALSE. * Search for jsp:root action, in order to determine if we're dealing * with XML or standard syntax (unless we already know what we're * dealing with, i.e., when 'isExternal' is TRUE and 'isXml' is FALSE). * No check for XML prolog, since nothing prevents a page from * outputting XML and still using JSP syntax (in this case, the * XML prolog is treated as template text). */ JspReader jspReader = null; try { jspReader = new JspReader(ctxt, absFileName, sourceEnc, jarFile, err); } catch (FileNotFoundException ex) { throw new JasperException(ex); } jspReader.setSingleFile(true); Mark startMark = jspReader.mark(); if (!isExternal) { jspReader.reset(startMark); if (hasJspRoot(jspReader)) { if (revert) { sourceEnc = "UTF-8"; } isXml = true; return; } else { if (revert && isBomPresent) { sourceEnc = "UTF-8"; } isXml = false; } } /* * At this point, we know we're dealing with JSP syntax. * If an XML prolog is provided, it's treated as template text. * Determine the page encoding from the page directive, unless it's * specified via JSP config. */ if (!isBomPresent) { sourceEnc = jspConfigPageEnc; if (sourceEnc == null) { sourceEnc = getPageEncodingForJspSyntax(jspReader, startMark); if (sourceEnc == null) { // Default to "ISO-8859-1" per JSP spec sourceEnc = "ISO-8859-1"; isDefaultPageEncoding = true; } } } }
// in java/org/apache/jasper/compiler/BeanRepository.java
public Class<?> getBeanType(String bean) throws JasperException { Class<?> clazz = null; try { clazz = loader.loadClass(beanTypes.get(bean)); } catch (ClassNotFoundException ex) { throw new JasperException (ex); } return clazz; }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
Override public void visit(Node.CustomTag n) throws JasperException { TagFileInfo tagFileInfo = n.getTagFileInfo(); if (tagFileInfo != null) { String tagFilePath = tagFileInfo.getPath(); if (tagFilePath.startsWith("/META-INF/")) { // For tags in JARs, add the TLD and the tag as a dependency TldLocation location = compiler.getCompilationContext().getTldLocation( tagFileInfo.getTagInfo().getTagLibrary().getURI()); JarResource jarResource = location.getJarResource(); if (jarResource != null) { try { // Add TLD pageInfo.addDependant(jarResource.getEntry(location.getName()).toString(), Long.valueOf(jarResource.getJarFile().getEntry(location.getName()).getTime())); // Add Tag pageInfo.addDependant(jarResource.getEntry(tagFilePath.substring(1)).toString(), Long.valueOf(jarResource.getJarFile().getEntry(tagFilePath.substring(1)).getTime())); } catch (IOException ioe) { throw new JasperException(ioe); } } else { pageInfo.addDependant(tagFilePath, compiler.getCompilationContext().getLastModified( tagFilePath)); } } else { pageInfo.addDependant(tagFilePath, compiler.getCompilationContext().getLastModified( tagFilePath)); } Class<?> c = loadTagFile(compiler, tagFilePath, n.getTagInfo(), pageInfo); n.setTagHandlerClass(c); } visitBody(n); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private synchronized void init() throws JasperException { if (initialized) return; try { tldScanWebXml(); tldScanResourcePaths(WEB_INF); JarScanner jarScanner = JarScannerFactory.getJarScanner(ctxt); if (jarScanner != null) { jarScanner.scan(ctxt, Thread.currentThread().getContextClassLoader(), new TldJarScannerCallback(), noTldJars); } initialized = true; } catch (Exception ex) { throw new JasperException(Localizer.getMessage( "jsp.error.internal.tldinit", ex.getMessage()), ex); } }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
private String getCanonicalName(String className) throws JasperException { Class<?> clazz; ClassLoader tccl; if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<ClassLoader> pa = new PrivilegedGetTccl(); tccl = AccessController.doPrivileged(pa); } else { tccl = Thread.currentThread().getContextClassLoader(); } try { clazz = Class.forName(className, false, tccl); } catch (ClassNotFoundException e) { throw new JasperException(e); } return clazz.getCanonicalName(); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.GetProperty n) throws JasperException { String name = n.getTextAttribute("name"); String property = n.getTextAttribute("property"); n.setBeginJavaLine(out.getJavaLine()); if (beanInfo.checkVariable(name)) { // Bean is defined using useBean, introspect at compile time Class<?> bean = beanInfo.getBeanType(name); String beanName = bean.getCanonicalName(); java.lang.reflect.Method meth = JspRuntimeLibrary .getReadMethod(bean, property); String methodName = meth.getName(); out.printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString(" + "(((" + beanName + ")_jspx_page_context.findAttribute(" + "\"" + name + "\"))." + methodName + "())));"); } else if (!STRICT_GET_PROPERTY || varInfoNames.contains(name)) { // The object is a custom action with an associated // VariableInfo entry for this name. // Get the class name and then introspect at runtime. out.printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString" + "(org.apache.jasper.runtime.JspRuntimeLibrary.handleGetProperty" + "(_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\")));"); } else { StringBuilder msg = new StringBuilder(); msg.append("file:"); msg.append(n.getStart()); msg.append(" jsp:getProperty for bean with name '"); msg.append(name); msg.append( "'. Name was not previously introduced as per JSP.5.3"); throw new JasperException(msg.toString()); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
private static void generateLocalVariables(ServletWriter out, Node n) throws JasperException { Node.ChildInfo ci; if (n instanceof Node.CustomTag) { ci = ((Node.CustomTag) n).getChildInfo(); } else if (n instanceof Node.JspBody) { ci = ((Node.JspBody) n).getChildInfo(); } else if (n instanceof Node.NamedAttribute) { ci = ((Node.NamedAttribute) n).getChildInfo(); } else { // Cannot access err since this method is static, but at // least flag an error. throw new JasperException("Unexpected Node Type"); // err.getString( // "jsp.error.internal.unexpected_node_type" ) ); } if (ci.hasUseBean()) { out.printil("javax.servlet.http.HttpSession session = _jspx_page_context.getSession();"); out.printil("javax.servlet.ServletContext application = _jspx_page_context.getServletContext();"); } if (ci.hasUseBean() || ci.hasIncludeAction() || ci.hasSetProperty() || ci.hasParamAction()) { out.printil("javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest)_jspx_page_context.getRequest();"); } if (ci.hasIncludeAction()) { out.printil("javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse)_jspx_page_context.getResponse();"); } }
// in java/org/apache/jasper/compiler/TagPluginManager.java
private void init(ErrorDispatcher err) throws JasperException { if (initialized) return; InputStream is = ctxt.getResourceAsStream(TAG_PLUGINS_XML); if (is == null) return; TreeNode root = (new ParserUtils()).parseXMLDocument(TAG_PLUGINS_XML, is); if (root == null) { return; } if (!TAG_PLUGINS_ROOT_ELEM.equals(root.getName())) { err.jspError("jsp.error.plugin.wrongRootElement", TAG_PLUGINS_XML, TAG_PLUGINS_ROOT_ELEM); } tagPlugins = new HashMap<String, TagPlugin>(); Iterator<TreeNode> pluginList = root.findChildren("tag-plugin"); while (pluginList.hasNext()) { TreeNode pluginNode = pluginList.next(); TreeNode tagClassNode = pluginNode.findChild("tag-class"); if (tagClassNode == null) { // Error return; } String tagClass = tagClassNode.getBody().trim(); TreeNode pluginClassNode = pluginNode.findChild("plugin-class"); if (pluginClassNode == null) { // Error return; } String pluginClassStr = pluginClassNode.getBody(); TagPlugin tagPlugin = null; try { Class<?> pluginClass = Class.forName(pluginClassStr); tagPlugin = (TagPlugin) pluginClass.newInstance(); } catch (Exception e) { throw new JasperException(e); } if (tagPlugin == null) { return; } tagPlugins.put(tagClass, tagPlugin); } initialized = true; }
// in java/org/apache/jasper/compiler/JspConfig.java
private void processWebDotXml() throws JasperException { WebXml webXml = null; try { webXml = new WebXml(ctxt); TreeNode webApp = null; if (webXml.getInputSource() != null) { ParserUtils pu = new ParserUtils(); webApp = pu.parseXMLDocument(webXml.getSystemId(), webXml.getInputSource()); } if (webApp == null || getVersion(webApp) < 2.4) { defaultIsELIgnored = "true"; defaultDeferedSyntaxAllowedAsLiteral = "true"; return; } if (getVersion(webApp) < 2.5) { defaultDeferedSyntaxAllowedAsLiteral = "true"; } TreeNode jspConfig = webApp.findChild("jsp-config"); if (jspConfig == null) { return; } jspProperties = new Vector<JspPropertyGroup>(); Iterator<TreeNode> jspPropertyList = jspConfig.findChildren("jsp-property-group"); while (jspPropertyList.hasNext()) { TreeNode element = jspPropertyList.next(); Iterator<TreeNode> list = element.findChildren(); Vector<String> urlPatterns = new Vector<String>(); String pageEncoding = null; String scriptingInvalid = null; String elIgnored = null; String isXml = null; Vector<String> includePrelude = new Vector<String>(); Vector<String> includeCoda = new Vector<String>(); String deferredSyntaxAllowedAsLiteral = null; String trimDirectiveWhitespaces = null; String defaultContentType = null; String buffer = null; String errorOnUndeclaredNamespace = null; while (list.hasNext()) { element = list.next(); String tname = element.getName(); if ("url-pattern".equals(tname)) urlPatterns.addElement( element.getBody() ); else if ("page-encoding".equals(tname)) pageEncoding = element.getBody(); else if ("is-xml".equals(tname)) isXml = element.getBody(); else if ("el-ignored".equals(tname)) elIgnored = element.getBody(); else if ("scripting-invalid".equals(tname)) scriptingInvalid = element.getBody(); else if ("include-prelude".equals(tname)) includePrelude.addElement(element.getBody()); else if ("include-coda".equals(tname)) includeCoda.addElement(element.getBody()); else if ("deferred-syntax-allowed-as-literal".equals(tname)) deferredSyntaxAllowedAsLiteral = element.getBody(); else if ("trim-directive-whitespaces".equals(tname)) trimDirectiveWhitespaces = element.getBody(); else if ("default-content-type".equals(tname)) defaultContentType = element.getBody(); else if ("buffer".equals(tname)) buffer = element.getBody(); else if ("error-on-undeclared-namespace".equals(tname)) errorOnUndeclaredNamespace = element.getBody(); } if (urlPatterns.size() == 0) { continue; } // Add one JspPropertyGroup for each URL Pattern. This makes // the matching logic easier. for( int p = 0; p < urlPatterns.size(); p++ ) { String urlPattern = urlPatterns.elementAt( p ); String path = null; String extension = null; if (urlPattern.indexOf('*') < 0) { // Exact match path = urlPattern; } else { int i = urlPattern.lastIndexOf('/'); String file; if (i >= 0) { path = urlPattern.substring(0,i+1); file = urlPattern.substring(i+1); } else { file = urlPattern; } // pattern must be "*", or of the form "*.jsp" if (file.equals("*")) { extension = "*"; } else if (file.startsWith("*.")) { extension = file.substring(file.indexOf('.')+1); } // The url patterns are reconstructed as the following: // path != null, extension == null: / or /foo/bar.ext // path == null, extension != null: *.ext // path != null, extension == "*": /foo/* boolean isStar = "*".equals(extension); if ((path == null && (extension == null || isStar)) || (path != null && !isStar)) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage( "jsp.warning.bad.urlpattern.propertygroup", urlPattern)); } continue; } } JspProperty property = new JspProperty(isXml, elIgnored, scriptingInvalid, pageEncoding, includePrelude, includeCoda, deferredSyntaxAllowedAsLiteral, trimDirectiveWhitespaces, defaultContentType, buffer, errorOnUndeclaredNamespace); JspPropertyGroup propertyGroup = new JspPropertyGroup(path, extension, property); jspProperties.addElement(propertyGroup); } } } catch (Exception ex) { throw new JasperException(ex); } finally { if (webXml != null) { webXml.close(); } } }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public Servlet getServlet() throws ServletException { // DCL on 'reload' requires that 'reload' be volatile // (this also forces a read memory barrier, ensuring the // new servlet object is read consistently) if (reload) { synchronized (this) { // Synchronizing on jsw enables simultaneous loading // of different pages, but not the same page. if (reload) { // This is to maintain the original protocol. destroy(); final Servlet servlet; try { InstanceManager instanceManager = InstanceManagerFactory.getInstanceManager(config); servlet = (Servlet) instanceManager.newInstance(ctxt.getFQCN(), ctxt.getJspLoader()); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JasperException(t); } servlet.init(config); if (!firstTime) { ctxt.getRuntimeContext().incrementJspReloadCount(); } theServlet = servlet; reload = false; // Volatile 'reload' forces in order write of 'theServlet' and new servlet object } } } return theServlet; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public Class<?> loadTagFile() throws JasperException { try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; ctxt.compile(); } } else { if (compileException != null) { throw compileException; } } if (reload) { tagHandlerClass = ctxt.load(); reload = false; } } catch (FileNotFoundException ex) { throw new JasperException(ex); } return tagHandlerClass; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile) throws ServletException, IOException, FileNotFoundException { Servlet servlet; try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if ((available > 0L) && (available < Long.MAX_VALUE)) { if (available > System.currentTimeMillis()) { response.setDateHeader("Retry-After", available); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, Localizer.getMessage("jsp.error.unavailable")); return; } // Wait period has expired. Reset. available = 0; } /* * (1) Compile */ if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; // The following sets reload to true, if necessary ctxt.compile(); } } else { if (compileException != null) { // Throw cached compilation exception throw compileException; } } /* * (2) (Re)load servlet class file */ servlet = getServlet(); // If a page is to be precompiled only, return. if (precompile) { return; } } catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; } catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } try { /* * (3) Handle limitation of number of loaded Jsps */ if (unloadAllowed) { synchronized(this) { if (unloadByCount) { if (unloadHandle == null) { unloadHandle = ctxt.getRuntimeContext().push(this); } else if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { ctxt.getRuntimeContext().makeYoungest(unloadHandle); lastUsageTime = System.currentTimeMillis(); } } else { if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { lastUsageTime = System.currentTimeMillis(); } } } } /* * (4) Service request */ if (servlet instanceof SingleThreadModel) { // sync on the wrapper so that the freshness // of the page is determined right before servicing synchronized (this) { servlet.service(request, response); } } else { servlet.service(request, response); } } catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); } catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
protected JasperException handleJspException(Exception ex) { try { Throwable realException = ex; if (ex instanceof ServletException) { realException = ((ServletException) ex).getRootCause(); } // First identify the stack frame in the trace that represents the JSP StackTraceElement[] frames = realException.getStackTrace(); StackTraceElement jspFrame = null; for (int i=0; i<frames.length; ++i) { if ( frames[i].getClassName().equals(this.getServlet().getClass().getName()) ) { jspFrame = frames[i]; break; } } if (jspFrame == null || this.ctxt.getCompiler().getPageNodes() == null) { // If we couldn't find a frame in the stack trace corresponding // to the generated servlet class or we don't have a copy of the // parsed JSP to hand, we can't really add anything return new JasperException(ex); } int javaLineNumber = jspFrame.getLineNumber(); JavacErrorDetail detail = ErrorDispatcher.createJavacError( jspFrame.getMethodName(), this.ctxt.getCompiler().getPageNodes(), null, javaLineNumber, ctxt); // If the line number is less than one we couldn't find out // where in the JSP things went wrong int jspLineNumber = detail.getJspBeginLineNumber(); if (jspLineNumber < 1) { throw new JasperException(ex); } if (options.getDisplaySourceFragment()) { return new JasperException(Localizer.getMessage ("jsp.exception", detail.getJspFileName(), "" + jspLineNumber) + Constants.NEWLINE + Constants.NEWLINE + detail.getJspExtract() + Constants.NEWLINE + Constants.NEWLINE + "Stacktrace:", ex); } return new JasperException(Localizer.getMessage ("jsp.exception", detail.getJspFileName(), "" + jspLineNumber), ex); } catch (Exception je) { // If anything goes wrong, just revert to the original behaviour if (ex instanceof JasperException) { return (JasperException) ex; } return new JasperException(ex); } }
// in java/org/apache/jasper/JspCompilationContext.java
public Class<?> load() throws JasperException { try { getJspLoader(); String name = getFQCN(); servletClass = jspLoader.loadClass(name); } catch (ClassNotFoundException cex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.load"), cex); } catch (Exception ex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); } removed = 0; return servletClass; }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
public TreeNode parseXMLDocument(String location, InputSource is) throws JasperException { Document document = null; // Perform an XML parse of this document, via JAXP try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(validating); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(entityResolver); builder.setErrorHandler(errorHandler); document = builder.parse(is); } catch (ParserConfigurationException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), ex); } catch (SAXParseException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); } catch (SAXException sx) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), sx); } catch (IOException io) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), io); } // Convert the resulting document to a graph of TreeNodes return (convert(null, document.getDocumentElement())); }
// in java/org/apache/jasper/JspC.java
public void setArgs(String[] arg) throws JasperException { args = arg; String tok; dieLevel = NO_DIE_LEVEL; while ((tok = nextArg()) != null) { if (tok.equals(SWITCH_VERBOSE)) { verbose = true; showSuccess = true; listErrors = true; } else if (tok.equals(SWITCH_OUTPUT_DIR)) { tok = nextArg(); setOutputDir( tok ); } else if (tok.equals(SWITCH_PACKAGE_NAME)) { targetPackage = nextArg(); } else if (tok.equals(SWITCH_COMPILE)) { compile=true; } else if (tok.equals(SWITCH_CLASS_NAME)) { targetClassName = nextArg(); } else if (tok.equals(SWITCH_URI_BASE)) { uriBase=nextArg(); } else if (tok.equals(SWITCH_URI_ROOT)) { setUriroot( nextArg()); } else if (tok.equals(SWITCH_FILE_WEBAPP)) { setUriroot( nextArg()); } else if ( tok.equals( SHOW_SUCCESS ) ) { showSuccess = true; } else if ( tok.equals( LIST_ERRORS ) ) { listErrors = true; } else if (tok.equals(SWITCH_WEBAPP_INC)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = INC_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = ALL_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML_ENCODING)) { setWebXmlEncoding(nextArg()); } else if (tok.equals(SWITCH_ADD_WEBAPP_XML_MAPPINGS)) { setAddWebXmlMappings(true); } else if (tok.equals(SWITCH_MAPPED)) { mappedFile = true; } else if (tok.equals(SWITCH_XPOWERED_BY)) { xpoweredBy = true; } else if (tok.equals(SWITCH_TRIM_SPACES)) { setTrimSpaces(true); } else if (tok.equals(SWITCH_CACHE)) { tok = nextArg(); if ("false".equals(tok)) { caching = false; } else { caching = true; } } else if (tok.equals(SWITCH_CLASSPATH)) { setClassPath(nextArg()); } else if (tok.startsWith(SWITCH_DIE)) { try { dieLevel = Integer.parseInt( tok.substring(SWITCH_DIE.length())); } catch (NumberFormatException nfe) { dieLevel = DEFAULT_DIE_LEVEL; } } else if (tok.equals(SWITCH_HELP)) { helpNeeded = true; } else if (tok.equals(SWITCH_POOLING)) { tok = nextArg(); if ("false".equals(tok)) { poolingEnabled = false; } else { poolingEnabled = true; } } else if (tok.equals(SWITCH_ENCODING)) { setJavaEncoding(nextArg()); } else if (tok.equals(SWITCH_SOURCE)) { setCompilerSourceVM(nextArg()); } else if (tok.equals(SWITCH_TARGET)) { setCompilerTargetVM(nextArg()); } else if (tok.equals(SWITCH_SMAP)) { smapSuppressed = false; } else if (tok.equals(SWITCH_DUMP_SMAP)) { smapDumped = true; } else { if (tok.startsWith("-")) { throw new JasperException("Unrecognized option: " + tok + ". Use -help for help."); } if (!fullstop) { argPos--; } // Start treating the rest as JSP Pages break; } } // Add all extra arguments to the list of files while( true ) { String file = nextFile(); if( file==null ) { break; } pages.add( file ); } }
// in java/org/apache/jasper/JspC.java
protected void processFile(String file) throws JasperException { if (log.isDebugEnabled()) { log.debug("Processing file: " + file); } ClassLoader originalClassLoader = null; try { // set up a scratch/output dir if none is provided if (scratchDir == null) { String temp = System.getProperty("java.io.tmpdir"); if (temp == null) { temp = ""; } scratchDir = new File(new File(temp).getAbsolutePath()); } String jspUri=file.replace('\\','/'); JspCompilationContext clctxt = new JspCompilationContext ( jspUri, this, context, null, rctxt ); /* Override the defaults */ if ((targetClassName != null) && (targetClassName.length() > 0)) { clctxt.setServletClassName(targetClassName); targetClassName = null; } if (targetPackage != null) { clctxt.setServletPackageName(targetPackage); } originalClassLoader = Thread.currentThread().getContextClassLoader(); if( loader==null ) { initClassLoader( clctxt ); } Thread.currentThread().setContextClassLoader(loader); clctxt.setClassLoader(loader); clctxt.setClassPath(classPath); Compiler clc = clctxt.createCompiler(); // If compile is set, generate both .java and .class, if // .jsp file is newer than .class file; // Otherwise only generate .java, if .jsp file is newer than // the .java file if( clc.isOutDated(compile) ) { if (log.isDebugEnabled()) { log.debug(jspUri + " is out dated, compiling..."); } clc.compile(compile, true); } // Generate mapping generateWebMapping( file, clctxt ); if ( showSuccess ) { log.info( "Built File: " + file ); } } catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } } catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); } finally { if(originalClassLoader != null) { Thread.currentThread().setContextClassLoader(originalClassLoader); } } }
// in java/org/apache/jasper/JspC.java
public void execute() throws JasperException { if(log.isDebugEnabled()) { log.debug("execute() starting for " + pages.size() + " pages."); } try { if (uriRoot == null) { if( pages.size() == 0 ) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.missingTarget")); } String firstJsp = pages.get( 0 ); File firstJspF = new File( firstJsp ); if (!firstJspF.exists()) { throw new JasperException( Localizer.getMessage("jspc.error.fileDoesNotExist", firstJsp)); } locateUriRoot( firstJspF ); } if (uriRoot == null) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.no_uriroot")); } File uriRootF = new File(uriRoot); if (!uriRootF.isDirectory()) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.uriroot_not_dir")); } if(context == null) { initServletContext(); } // No explicit pages, we'll process all .jsp in the webapp if (pages.size() == 0) { scanFiles(uriRootF); } initWebXml(); Iterator<String> iter = pages.iterator(); while (iter.hasNext()) { String nextjsp = iter.next().toString(); File fjsp = new File(nextjsp); if (!fjsp.isAbsolute()) { fjsp = new File(uriRootF, nextjsp); } if (!fjsp.exists()) { if (log.isWarnEnabled()) { log.warn (Localizer.getMessage ("jspc.error.fileDoesNotExist", fjsp.toString())); } continue; } String s = fjsp.getAbsolutePath(); if (s.startsWith(uriRoot)) { nextjsp = s.substring(uriRoot.length()); } if (nextjsp.startsWith("." + File.separatorChar)) { nextjsp = nextjsp.substring(2); } processFile(nextjsp); } completeWebXml(); if (addWebXmlMappings) { mergeIntoWebXml(); } } catch (IOException ioe) { throw new JasperException(ioe); } catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { rootCause.printStackTrace(); } throw je; } finally { if (loader != null) { LogFactory.release(loader); } } }
37
              
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException ("error in invoking method", ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/jasper/compiler/ParserController.java
catch (FileNotFoundException ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/compiler/BeanRepository.java
catch (ClassNotFoundException ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
catch (IOException ioe) { throw new JasperException(ioe); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage( "jsp.error.internal.tldinit", ex.getMessage()), ex); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
catch (ClassNotFoundException e) { throw new JasperException(e); }
// in java/org/apache/jasper/compiler/TagPluginManager.java
catch (Exception e) { throw new JasperException(e); }
// in java/org/apache/jasper/compiler/JspConfig.java
catch (Exception ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JasperException(t); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (FileNotFoundException ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (ClassNotFoundException cex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.load"), cex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (ParserConfigurationException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), ex); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXParseException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXException sx) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), sx); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (IOException io) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), io); }
// in java/org/apache/jasper/JspC.java
catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { throw new JasperException(ioe); }
491
              
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
Override public Void run() throws JasperException { internalIntrospecthelper( bean,prop,value,request,param,ignoreMethodNF); return null; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object convert(String propertyName, String s, Class<?> t, Class<?> propertyEditorClass) throws JasperException { try { if (s == null) { if (t.equals(Boolean.class) || t.equals(Boolean.TYPE)) s = "false"; else return null; } if (propertyEditorClass != null) { return getValueFromBeanInfoPropertyEditor( t, propertyName, s, propertyEditorClass); } else if ( t.equals(Boolean.class) || t.equals(Boolean.TYPE) ) { if (s.equalsIgnoreCase("on") || s.equalsIgnoreCase("true")) s = "true"; else s = "false"; return Boolean.valueOf(s); } else if ( t.equals(Byte.class) || t.equals(Byte.TYPE) ) { return Byte.valueOf(s); } else if (t.equals(Character.class) || t.equals(Character.TYPE)) { return s.length() > 0 ? Character.valueOf(s.charAt(0)) : null; } else if ( t.equals(Short.class) || t.equals(Short.TYPE) ) { return Short.valueOf(s); } else if ( t.equals(Integer.class) || t.equals(Integer.TYPE) ) { return Integer.valueOf(s); } else if ( t.equals(Float.class) || t.equals(Float.TYPE) ) { return Float.valueOf(s); } else if ( t.equals(Long.class) || t.equals(Long.TYPE) ) { return Long.valueOf(s); } else if ( t.equals(Double.class) || t.equals(Double.TYPE) ) { return Double.valueOf(s); } else if ( t.equals(String.class) ) { return s; } else if ( t.equals(java.io.File.class) ) { return new java.io.File(s); } else if (t.getName().equals("java.lang.Object")) { return new Object[] {s}; } else { return getValueFromPropertyEditorManager( t, propertyName, s); } } catch (Exception ex) { throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void introspect(Object bean, ServletRequest request) throws JasperException { Enumeration<String> e = request.getParameterNames(); while ( e.hasMoreElements() ) { String name = e.nextElement(); String value = request.getParameter(name); introspecthelper(bean, name, value, request, name, true); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void introspecthelper(Object bean, String prop, String value, ServletRequest request, String param, boolean ignoreMethodNF) throws JasperException { if( Constants.IS_SECURITY_ENABLED ) { try { PrivilegedIntrospectHelper dp = new PrivilegedIntrospectHelper( bean,prop,value,request,param,ignoreMethodNF); AccessController.doPrivileged(dp); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); throw (JasperException)e; } } else { internalIntrospecthelper( bean,prop,value,request,param,ignoreMethodNF); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
private static void internalIntrospecthelper(Object bean, String prop, String value, ServletRequest request, String param, boolean ignoreMethodNF) throws JasperException { Method method = null; Class<?> type = null; Class<?> propertyEditorClass = null; try { java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(bean.getClass()); if ( info != null ) { java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); for (int i = 0 ; i < pd.length ; i++) { if ( pd[i].getName().equals(prop) ) { method = pd[i].getWriteMethod(); type = pd[i].getPropertyType(); propertyEditorClass = pd[i].getPropertyEditorClass(); break; } } } if ( method != null ) { if (type.isArray()) { if (request == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.setproperty.noindexset")); } Class<?> t = type.getComponentType(); String[] values = request.getParameterValues(param); //XXX Please check. if(values == null) return; if(t.equals(String.class)) { method.invoke(bean, new Object[] { values }); } else { createTypedArray (prop, bean, method, values, t, propertyEditorClass); } } else { if(value == null || (param != null && value.equals(""))) return; Object oval = convert(prop, value, type, propertyEditorClass); if ( oval != null ) method.invoke(bean, new Object[] { oval }); } } } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } if (!ignoreMethodNF && (method == null)) { if (type == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.noproperty", prop, bean.getClass().getName())); } else { throw new JasperException( Localizer.getMessage("jsp.error.beans.nomethod.setproperty", prop, type.getName(), bean.getClass().getName())); } } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void createTypedArray(String propertyName, Object bean, Method method, String[] values, Class<?> t, Class<?> propertyEditorClass) throws JasperException { try { if (propertyEditorClass != null) { Object[] tmpval = new Integer[values.length]; for (int i=0; i<values.length; i++) { tmpval[i] = getValueFromBeanInfoPropertyEditor( t, propertyName, values[i], propertyEditorClass); } method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Integer.class)) { Integer []tmpval = new Integer[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Integer (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Byte.class)) { Byte[] tmpval = new Byte[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Byte (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Boolean.class)) { Boolean[] tmpval = new Boolean[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Boolean.valueOf(values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Short.class)) { Short[] tmpval = new Short[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Short (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Long.class)) { Long[] tmpval = new Long[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Long (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Double.class)) { Double[] tmpval = new Double[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Double (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Float.class)) { Float[] tmpval = new Float[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Float (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Character.class)) { Character[] tmpval = new Character[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Character.valueOf(values[i].charAt(0)); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(int.class)) { int []tmpval = new int[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Integer.parseInt (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(byte.class)) { byte[] tmpval = new byte[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Byte.parseByte (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(boolean.class)) { boolean[] tmpval = new boolean[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = (Boolean.valueOf(values[i])).booleanValue(); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(short.class)) { short[] tmpval = new short[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Short.parseShort (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(long.class)) { long[] tmpval = new long[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Long.parseLong (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(double.class)) { double[] tmpval = new double[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Double.valueOf(values[i]).doubleValue(); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(float.class)) { float[] tmpval = new float[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Float.valueOf(values[i]).floatValue(); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(char.class)) { char[] tmpval = new char[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = values[i].charAt(0); method.invoke (bean, new Object[] {tmpval}); } else { Object[] tmpval = new Integer[values.length]; for (int i=0; i<values.length; i++) { tmpval[i] = getValueFromPropertyEditorManager( t, propertyName, values[i]); } method.invoke (bean, new Object[] {tmpval}); } } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException ("error in invoking method", ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object handleGetProperty(Object o, String prop) throws JasperException { if (o == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.nullbean")); } Object value = null; try { Method method = getReadMethod(o.getClass(), prop); value = method.invoke(o, (Object[]) null); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException (ex); } return value; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetPropertyExpression(Object bean, String prop, String expression, PageContext pageContext, ProtectedFunctionMapper functionMapper ) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { PageContextImpl.proprietaryEvaluate( expression, method.getParameterTypes()[0], pageContext, functionMapper, false ) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, Object value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { value }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, int value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Integer.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, short value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Short.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, long value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Long.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, double value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Double.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, float value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Float.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, char value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Character.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, byte value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Byte.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, boolean value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Boolean.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Method getWriteMethod(Class<?> beanClass, String prop) throws JasperException { Method method = null; Class<?> type = null; try { java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(beanClass); if ( info != null ) { java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); for (int i = 0 ; i < pd.length ; i++) { if ( pd[i].getName().equals(prop) ) { method = pd[i].getWriteMethod(); type = pd[i].getPropertyType(); break; } } } else { // just in case introspection silently fails. throw new JasperException( Localizer.getMessage("jsp.error.beans.nobeaninfo", beanClass.getName())); } } catch (Exception ex) { throw new JasperException (ex); } if (method == null) { if (type == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.noproperty", prop, beanClass.getName())); } else { throw new JasperException( Localizer.getMessage("jsp.error.beans.nomethod.setproperty", prop, type.getName(), beanClass.getName())); } } return method; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Method getReadMethod(Class<?> beanClass, String prop) throws JasperException { Method method = null; Class<?> type = null; try { java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(beanClass); if ( info != null ) { java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); for (int i = 0 ; i < pd.length ; i++) { if ( pd[i].getName().equals(prop) ) { method = pd[i].getReadMethod(); type = pd[i].getPropertyType(); break; } } } else { // just in case introspection silently fails. throw new JasperException( Localizer.getMessage("jsp.error.beans.nobeaninfo", beanClass.getName())); } } catch (Exception ex) { throw new JasperException (ex); } if (method == null) { if (type == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.noproperty", prop, beanClass.getName())); } else { throw new JasperException( Localizer.getMessage("jsp.error.beans.nomethod", prop, beanClass.getName())); } } return method; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object getValueFromBeanInfoPropertyEditor( Class<?> attrClass, String attrName, String attrValue, Class<?> propertyEditorClass) throws JasperException { try { PropertyEditor pe = (PropertyEditor)propertyEditorClass.newInstance(); pe.setAsText(attrValue); return pe.getValue(); } catch (Exception ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object getValueFromPropertyEditorManager( Class<?> attrClass, String attrName, String attrValue) throws JasperException { try { PropertyEditor propEditor = PropertyEditorManager.findEditor(attrClass); if (propEditor != null) { propEditor.setAsText(attrValue); return propEditor.getValue(); } else { throw new IllegalArgumentException( Localizer.getMessage("jsp.error.beans.propertyeditor.notregistered")); } } catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); } }
// in java/org/apache/jasper/compiler/JspUtil.java
public static void checkScope(String scope, Node n, ErrorDispatcher err) throws JasperException { if (scope != null && !scope.equals("page") && !scope.equals("request") && !scope.equals("session") && !scope.equals("application")) { err.jspError(n, "jsp.error.invalid.scope", scope); } }
// in java/org/apache/jasper/compiler/JspUtil.java
public static void checkAttributes(String typeOfTag, Node n, ValidAttribute[] validAttributes, ErrorDispatcher err) throws JasperException { Attributes attrs = n.getAttributes(); Mark start = n.getStart(); boolean valid = true; // AttributesImpl.removeAttribute is broken, so we do this... int tempLength = (attrs == null) ? 0 : attrs.getLength(); Vector<String> temp = new Vector<String>(tempLength, 1); for (int i = 0; i < tempLength; i++) { @SuppressWarnings("null") // If attrs==null, tempLength == 0 String qName = attrs.getQName(i); if ((!qName.equals("xmlns")) && (!qName.startsWith("xmlns:"))) { temp.addElement(qName); } } // Add names of attributes specified using jsp:attribute Node.Nodes tagBody = n.getBody(); if (tagBody != null) { int numSubElements = tagBody.size(); for (int i = 0; i < numSubElements; i++) { Node node = tagBody.getNode(i); if (node instanceof Node.NamedAttribute) { String attrName = node.getAttributeValue("name"); temp.addElement(attrName); // Check if this value appear in the attribute of the node if (n.getAttributeValue(attrName) != null) { err.jspError(n, "jsp.error.duplicate.name.jspattribute", attrName); } } else { // Nothing can come before jsp:attribute, and only // jsp:body can come after it. break; } } } /* * First check to see if all the mandatory attributes are present. If so * only then proceed to see if the other attributes are valid for the * particular tag. */ String missingAttribute = null; for (int i = 0; i < validAttributes.length; i++) { int attrPos; if (validAttributes[i].mandatory) { attrPos = temp.indexOf(validAttributes[i].name); if (attrPos != -1) { temp.remove(attrPos); valid = true; } else { valid = false; missingAttribute = validAttributes[i].name; break; } } } // If mandatory attribute is missing then the exception is thrown if (!valid) { err.jspError(start, "jsp.error.mandatory.attribute", typeOfTag, missingAttribute); } // Check to see if there are any more attributes for the specified tag. int attrLeftLength = temp.size(); if (attrLeftLength == 0) { return; } // Now check to see if the rest of the attributes are valid too. String attribute = null; for (int j = 0; j < attrLeftLength; j++) { valid = false; attribute = temp.elementAt(j); for (int i = 0; i < validAttributes.length; i++) { if (attribute.equals(validAttributes[i].name)) { valid = true; break; } } if (!valid) { err.jspError(start, "jsp.error.invalid.attribute", typeOfTag, attribute); } } // XXX *could* move EL-syntax validation here... (sb) }
// in java/org/apache/jasper/compiler/JspUtil.java
public static String getTagHandlerClassName(String path, String urn, ErrorDispatcher err) throws JasperException { String className = null; int begin = 0; int index; index = path.lastIndexOf(".tag"); if (index == -1) { err.jspError("jsp.error.tagfile.badSuffix", path); } // It's tempting to remove the ".tag" suffix here, but we can't. // If we remove it, the fully-qualified class name of this tag // could conflict with the package name of other tags. // For instance, the tag file // /WEB-INF/tags/foo.tag // would have fully-qualified class name // org.apache.jsp.tag.web.foo // which would conflict with the package name of the tag file // /WEB-INF/tags/foo/bar.tag index = path.indexOf(WEB_INF_TAGS); if (index != -1) { className = Constants.TAG_FILE_PACKAGE_NAME + ".web"; begin = index + WEB_INF_TAGS.length(); } else { index = path.indexOf(META_INF_TAGS); if (index != -1) { className = getClassNameBase(urn); begin = index + META_INF_TAGS.length(); } else { err.jspError("jsp.error.tagfile.illegalPath", path); } } className += makeJavaPackage(path.substring(begin)); return className; }
// in java/org/apache/jasper/compiler/JspUtil.java
static InputStreamReader getReader(String fname, String encoding, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err) throws JasperException, IOException { return getReader(fname, encoding, jarFile, ctxt, err, 0); }
// in java/org/apache/jasper/compiler/JspUtil.java
static InputStreamReader getReader(String fname, String encoding, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err, int skip) throws JasperException, IOException { InputStreamReader reader = null; InputStream in = getInputStream(fname, jarFile, ctxt); for (int i = 0; i < skip; i++) { in.read(); } try { reader = new InputStreamReader(in, encoding); } catch (UnsupportedEncodingException ex) { err.jspError("jsp.error.unsupported.encoding", encoding); } return reader; }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visitBody(Node n) throws JasperException { SmapStratum smapSave = smap; String innerClass = n.getInnerClassName(); if (innerClass != null) { this.smap = innerClassMap.get(innerClass); } super.visitBody(n); smap = smapSave; }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.Declaration n) throws JasperException { doSmapText(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.Expression n) throws JasperException { doSmapText(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.Scriptlet n) throws JasperException { doSmapText(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.IncludeAction n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.ForwardAction n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.GetProperty n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.SetProperty n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.UseBean n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.PlugIn n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.CustomTag n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.UninterpretedTag n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.JspElement n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.JspText n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.NamedAttribute n) throws JasperException { visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.JspBody n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.InvokeAction n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.DoBodyAction n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.ELExpression n) throws JasperException { doSmap(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.TemplateText n) throws JasperException { Mark mark = n.getStart(); if (mark == null) { return; } //Add the file information String fileName = mark.getFile(); smap.addFile(unqualify(fileName), fileName); //Add a LineInfo that corresponds to the beginning of this node int iInputStartLine = mark.getLineNumber(); int iOutputStartLine = n.getBeginJavaLine(); int iOutputLineIncrement = breakAtLF? 1: 0; smap.addLineData(iInputStartLine, fileName, 1, iOutputStartLine, iOutputLineIncrement); // Output additional mappings in the text java.util.ArrayList<Integer> extraSmap = n.getExtraSmap(); if (extraSmap != null) { for (int i = 0; i < extraSmap.size(); i++) { iOutputStartLine += iOutputLineIncrement; smap.addLineData( iInputStartLine+extraSmap.get(i).intValue(), fileName, 1, iOutputStartLine, iOutputLineIncrement); } } }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void jspError(String fname, int line, int column, String errMsg, Exception ex) throws JasperException { throw new JasperException(fname + " (" + Localizer.getMessage("jsp.error.location", Integer.toString(line), Integer.toString(column)) + ") " + errMsg, ex); }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void jspError(String errMsg, Exception ex) throws JasperException { throw new JasperException(errMsg, ex); }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void javacError(JavacErrorDetail[] details) throws JasperException { if (details == null) { return; } Object[] args = null; StringBuilder buf = new StringBuilder(); for (int i=0; i < details.length; i++) { if (details[i].getJspBeginLineNumber() >= 0) { args = new Object[] { Integer.valueOf(details[i].getJspBeginLineNumber()), details[i].getJspFileName() }; buf.append(Constants.NEWLINE); buf.append(Constants.NEWLINE); buf.append(Localizer.getMessage("jsp.error.single.line.number", args)); buf.append(Constants.NEWLINE); buf.append(details[i].getErrorMessage()); buf.append(Constants.NEWLINE); buf.append(details[i].getJspExtract()); } else { args = new Object[] { Integer.valueOf(details[i].getJavaLineNumber()) }; buf.append(Constants.NEWLINE); buf.append(Constants.NEWLINE); buf.append(Localizer.getMessage("jsp.error.java.line.number", args)); buf.append(Constants.NEWLINE); buf.append(details[i].getErrorMessage()); } } buf.append(Constants.NEWLINE); buf.append(Constants.NEWLINE); buf.append("Stacktrace:"); throw new JasperException( Localizer.getMessage("jsp.error.unable.compile") + ": " + buf); }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void javacError(String errorReport, Exception exception) throws JasperException { throw new JasperException( Localizer.getMessage("jsp.error.unable.compile"), exception); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.ParamAction n) throws JasperException { if (n.getValue().isExpression()) { scriptingElementSeen = true; } paramActionSeen = true; }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.IncludeAction n) throws JasperException { if (n.getPage().isExpression()) { scriptingElementSeen = true; } includeActionSeen = true; visitBody(n); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.ForwardAction n) throws JasperException { if (n.getPage().isExpression()) { scriptingElementSeen = true; } visitBody(n); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.SetProperty n) throws JasperException { if (n.getValue() != null && n.getValue().isExpression()) { scriptingElementSeen = true; } setPropertySeen = true; }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.UseBean n) throws JasperException { if (n.getBeanName() != null && n.getBeanName().isExpression()) { scriptingElementSeen = true; } usebeanSeen = true; visitBody(n); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.PlugIn n) throws JasperException { if (n.getHeight() != null && n.getHeight().isExpression()) { scriptingElementSeen = true; } if (n.getWidth() != null && n.getWidth().isExpression()) { scriptingElementSeen = true; } visitBody(n); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.CustomTag n) throws JasperException { // Check to see what kinds of element we see as child elements checkSeen( n.getChildInfo(), n ); }
// in java/org/apache/jasper/compiler/Collector.java
private void checkSeen( Node.ChildInfo ci, Node n ) throws JasperException { // save values collected so far boolean scriptingElementSeenSave = scriptingElementSeen; scriptingElementSeen = false; boolean usebeanSeenSave = usebeanSeen; usebeanSeen = false; boolean includeActionSeenSave = includeActionSeen; includeActionSeen = false; boolean paramActionSeenSave = paramActionSeen; paramActionSeen = false; boolean setPropertySeenSave = setPropertySeen; setPropertySeen = false; boolean hasScriptingVarsSave = hasScriptingVars; hasScriptingVars = false; // Scan attribute list for expressions if( n instanceof Node.CustomTag ) { Node.CustomTag ct = (Node.CustomTag)n; Node.JspAttribute[] attrs = ct.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { if (attrs[i].isExpression()) { scriptingElementSeen = true; break; } } } visitBody(n); if( (n instanceof Node.CustomTag) && !hasScriptingVars) { Node.CustomTag ct = (Node.CustomTag)n; hasScriptingVars = ct.getVariableInfos().length > 0 || ct.getTagVariableInfos().length > 0; } // Record if the tag element and its body contains any scriptlet. ci.setScriptless(! scriptingElementSeen); ci.setHasUseBean(usebeanSeen); ci.setHasIncludeAction(includeActionSeen); ci.setHasParamAction(paramActionSeen); ci.setHasSetProperty(setPropertySeen); ci.setHasScriptingVars(hasScriptingVars); // Propagate value of scriptingElementSeen up. scriptingElementSeen = scriptingElementSeen || scriptingElementSeenSave; usebeanSeen = usebeanSeen || usebeanSeenSave; setPropertySeen = setPropertySeen || setPropertySeenSave; includeActionSeen = includeActionSeen || includeActionSeenSave; paramActionSeen = paramActionSeen || paramActionSeenSave; hasScriptingVars = hasScriptingVars || hasScriptingVarsSave; }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.JspElement n) throws JasperException { if (n.getNameAttribute().isExpression()) scriptingElementSeen = true; Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; i < attrs.length; i++) { if (attrs[i].isExpression()) { scriptingElementSeen = true; break; } } visitBody(n); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.JspBody n) throws JasperException { checkSeen( n.getChildInfo(), n ); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.NamedAttribute n) throws JasperException { checkSeen( n.getChildInfo(), n ); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.Declaration n) throws JasperException { scriptingElementSeen = true; }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.Expression n) throws JasperException { scriptingElementSeen = true; }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.Scriptlet n) throws JasperException { scriptingElementSeen = true; }
// in java/org/apache/jasper/compiler/Collector.java
public static void collect(Compiler compiler, Node.Nodes page) throws JasperException { CollectVisitor collectVisitor = new CollectVisitor(); page.visit(collectVisitor); collectVisitor.updatePageInfo(compiler.getPageInfo()); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(Visitor v) throws JasperException { Iterator<Node> iter = list.iterator(); while (iter.hasNext()) { Node n = iter.next(); n.accept(v); } }
// in java/org/apache/jasper/compiler/Node.java
public void visit(Root n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(JspRoot n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(PageDirective n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(TagDirective n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(IncludeDirective n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(TaglibDirective n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(AttributeDirective n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(VariableDirective n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(Comment n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(Declaration n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(Expression n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(Scriptlet n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(ELExpression n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(IncludeAction n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(ForwardAction n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(GetProperty n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(SetProperty n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(ParamAction n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(ParamsAction n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(FallBackAction n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(UseBean n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(PlugIn n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(CustomTag n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(UninterpretedTag n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(JspElement n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(JspText n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(NamedAttribute n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(JspBody n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(InvokeAction n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(DoBodyAction n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(TemplateText n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(JspOutput n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(AttributeGenerator n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Compiler.java
private ServletWriter setupContextWriter(String javaFileName) throws FileNotFoundException, JasperException { ServletWriter writer; // Setup the ServletWriter String javaEncoding = ctxt.getOptions().getJavaEncoding(); OutputStreamWriter osw = null; try { osw = new OutputStreamWriter( new FileOutputStream(javaFileName), javaEncoding); } catch (UnsupportedEncodingException ex) { errDispatcher.jspError("jsp.error.needAlternateJavaEncoding", javaEncoding); } writer = new ServletWriter(new PrintWriter(osw)); ctxt.setWriter(writer); return writer; }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile() throws FileNotFoundException, JasperException, Exception { compile(true); }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile(boolean compileClass) throws FileNotFoundException, JasperException, Exception { compile(compileClass, false); }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile(boolean compileClass, boolean jspcMode) throws FileNotFoundException, JasperException, Exception { if (errDispatcher == null) { this.errDispatcher = new ErrorDispatcher(jspcMode); } try { String[] smap = generateJava(); File javaFile = new File(ctxt.getServletJavaFileName()); Long jspLastModified = ctxt.getLastModified(ctxt.getJspFile()); javaFile.setLastModified(jspLastModified.longValue()); if (compileClass) { generateClass(smap); // Fix for bugzilla 41606 // Set JspServletWrapper.servletClassLastModifiedTime after successful compile String targetFileName = ctxt.getClassFileName(); if (targetFileName != null) { File targetFile = new File(targetFileName); if (targetFile.exists()) { targetFile.setLastModified(jspLastModified.longValue()); if (jsw != null) { jsw.setServletClassLastModifiedTime( jspLastModified.longValue()); } } } } } finally { if (tfp != null && ctxt.isPrototypeMode()) { tfp.removeProtoTypeFiles(null); } // Make sure these object which are only used during the // generation and compilation of the JSP page get // dereferenced so that they can be GC'd and reduce the // memory footprint. tfp = null; errDispatcher = null; pageInfo = null; // Only get rid of the pageNodes if in production. // In development mode, they are used for detailed // error messages. // http://issues.apache.org/bugzilla/show_bug.cgi?id=37062 if (!this.options.getDevelopment()) { pageNodes = null; } if (ctxt.getWriter() != null) { ctxt.getWriter().close(); ctxt.setWriter(null); } } }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parse(String inFileName) throws FileNotFoundException, JasperException, IOException { // If we're parsing a packaged tag file or a resource included by it // (using an include directive), ctxt.getTagFileJar() returns the // JAR file from which to read the tag file or included resource, // respectively. isTagFile = ctxt.isTagFile(); directiveOnly = false; return doParse(inFileName, null, ctxt.getTagFileJarResource()); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parseDirectives(String inFileName) throws FileNotFoundException, JasperException, IOException { // If we're parsing a packaged tag file or a resource included by it // (using an include directive), ctxt.getTagFileJar() returns the // JAR file from which to read the tag file or included resource, // respectively. isTagFile = ctxt.isTagFile(); directiveOnly = true; return doParse(inFileName, null, ctxt.getTagFileJarResource()); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parse(String inFileName, Node parent, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { // For files that are statically included, isTagfile and directiveOnly // remain unchanged. return doParse(inFileName, parent, jarResource); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parseTagFileDirectives(String inFileName, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { boolean isTagFileSave = isTagFile; boolean directiveOnlySave = directiveOnly; isTagFile = true; directiveOnly = true; Node.Nodes page = doParse(inFileName, null, jarResource); directiveOnly = directiveOnlySave; isTagFile = isTagFileSave; return page; }
// in java/org/apache/jasper/compiler/ParserController.java
private Node.Nodes doParse(String inFileName, Node parent, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { Node.Nodes parsedPage = null; isEncodingSpecifiedInProlog = false; isBomPresent = false; isDefaultPageEncoding = false; JarFile jarFile = (jarResource == null) ? null : jarResource.getJarFile(); String absFileName = resolveFileName(inFileName); String jspConfigPageEnc = getJspConfigPageEncoding(absFileName); // Figure out what type of JSP document and encoding type we are // dealing with determineSyntaxAndEncoding(absFileName, jarFile, jspConfigPageEnc); if (parent != null) { // Included resource, add to dependent list if (jarFile == null) { compiler.getPageInfo().addDependant(absFileName, ctxt.getLastModified(absFileName)); } else { String entry = absFileName.substring(1); compiler.getPageInfo().addDependant( jarResource.getEntry(entry).toString(), Long.valueOf(jarFile.getEntry(entry).getTime())); } } if ((isXml && isEncodingSpecifiedInProlog) || isBomPresent) { /* * Make sure the encoding explicitly specified in the XML * prolog (if any) matches that in the JSP config element * (if any), treating "UTF-16", "UTF-16BE", and "UTF-16LE" as * identical. */ if (jspConfigPageEnc != null && !jspConfigPageEnc.equals(sourceEnc) && (!jspConfigPageEnc.startsWith("UTF-16") || !sourceEnc.startsWith("UTF-16"))) { err.jspError("jsp.error.prolog_config_encoding_mismatch", sourceEnc, jspConfigPageEnc); } } // Dispatch to the appropriate parser if (isXml) { // JSP document (XML syntax) // InputStream for jspx page is created and properly closed in // JspDocumentParser. parsedPage = JspDocumentParser.parse(this, absFileName, jarFile, parent, isTagFile, directiveOnly, sourceEnc, jspConfigPageEnc, isEncodingSpecifiedInProlog, isBomPresent); } else { // Standard syntax InputStreamReader inStreamReader = null; try { inStreamReader = JspUtil.getReader(absFileName, sourceEnc, jarFile, ctxt, err, skip); JspReader jspReader = new JspReader(ctxt, absFileName, sourceEnc, inStreamReader, err); parsedPage = Parser.parse(this, jspReader, parent, isTagFile, directiveOnly, jarResource, sourceEnc, jspConfigPageEnc, isDefaultPageEncoding, isBomPresent); } finally { if (inStreamReader != null) { try { inStreamReader.close(); } catch (Exception any) { } } } } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } baseDirStack.pop(); return parsedPage; }
// in java/org/apache/jasper/compiler/ParserController.java
private String getJspConfigPageEncoding(String absFileName) throws JasperException { JspConfig jspConfig = ctxt.getOptions().getJspConfig(); JspConfig.JspProperty jspProperty = jspConfig.findJspProperty(absFileName); return jspProperty.getPageEncoding(); }
// in java/org/apache/jasper/compiler/ParserController.java
private void determineSyntaxAndEncoding(String absFileName, JarFile jarFile, String jspConfigPageEnc) throws JasperException, IOException { isXml = false; /* * 'true' if the syntax (XML or standard) of the file is given * from external information: either via a JSP configuration element, * the ".jspx" suffix, or the enclosing file (for included resources) */ boolean isExternal = false; /* * Indicates whether we need to revert from temporary usage of * "ISO-8859-1" back to "UTF-8" */ boolean revert = false; JspConfig jspConfig = ctxt.getOptions().getJspConfig(); JspConfig.JspProperty jspProperty = jspConfig.findJspProperty( absFileName); if (jspProperty.isXml() != null) { // If <is-xml> is specified in a <jsp-property-group>, it is used. isXml = JspUtil.booleanValue(jspProperty.isXml()); isExternal = true; } else if (absFileName.endsWith(".jspx") || absFileName.endsWith(".tagx")) { isXml = true; isExternal = true; } if (isExternal && !isXml) { // JSP (standard) syntax. Use encoding specified in jsp-config // if provided. sourceEnc = jspConfigPageEnc; if (sourceEnc != null) { return; } // We don't know the encoding, so use BOM to determine it sourceEnc = "ISO-8859-1"; } else { // XML syntax or unknown, (auto)detect encoding ... Object[] ret = XMLEncodingDetector.getEncoding(absFileName, jarFile, ctxt, err); sourceEnc = (String) ret[0]; if (((Boolean) ret[1]).booleanValue()) { isEncodingSpecifiedInProlog = true; } if (((Boolean) ret[2]).booleanValue()) { isBomPresent = true; } skip = ((Integer) ret[3]).intValue(); if (!isXml && sourceEnc.equals("UTF-8")) { /* * We don't know if we're dealing with XML or standard syntax. * Therefore, we need to check to see if the page contains * a <jsp:root> element. * * We need to be careful, because the page may be encoded in * ISO-8859-1 (or something entirely different), and may * contain byte sequences that will cause a UTF-8 converter to * throw exceptions. * * It is safe to use a source encoding of ISO-8859-1 in this * case, as there are no invalid byte sequences in ISO-8859-1, * and the byte/character sequences we're looking for (i.e., * <jsp:root>) are identical in either encoding (both UTF-8 * and ISO-8859-1 are extensions of ASCII). */ sourceEnc = "ISO-8859-1"; revert = true; } } if (isXml) { // (This implies 'isExternal' is TRUE.) // We know we're dealing with a JSP document (via JSP config or // ".jspx" suffix), so we're done. return; } /* * At this point, 'isExternal' or 'isXml' is FALSE. * Search for jsp:root action, in order to determine if we're dealing * with XML or standard syntax (unless we already know what we're * dealing with, i.e., when 'isExternal' is TRUE and 'isXml' is FALSE). * No check for XML prolog, since nothing prevents a page from * outputting XML and still using JSP syntax (in this case, the * XML prolog is treated as template text). */ JspReader jspReader = null; try { jspReader = new JspReader(ctxt, absFileName, sourceEnc, jarFile, err); } catch (FileNotFoundException ex) { throw new JasperException(ex); } jspReader.setSingleFile(true); Mark startMark = jspReader.mark(); if (!isExternal) { jspReader.reset(startMark); if (hasJspRoot(jspReader)) { if (revert) { sourceEnc = "UTF-8"; } isXml = true; return; } else { if (revert && isBomPresent) { sourceEnc = "UTF-8"; } isXml = false; } } /* * At this point, we know we're dealing with JSP syntax. * If an XML prolog is provided, it's treated as template text. * Determine the page encoding from the page directive, unless it's * specified via JSP config. */ if (!isBomPresent) { sourceEnc = jspConfigPageEnc; if (sourceEnc == null) { sourceEnc = getPageEncodingForJspSyntax(jspReader, startMark); if (sourceEnc == null) { // Default to "ISO-8859-1" per JSP spec sourceEnc = "ISO-8859-1"; isDefaultPageEncoding = true; } } } }
// in java/org/apache/jasper/compiler/ParserController.java
private String getPageEncodingForJspSyntax(JspReader jspReader, Mark startMark) throws JasperException { String encoding = null; String saveEncoding = null; jspReader.reset(startMark); /* * Determine page encoding from directive of the form <%@ page %>, * <%@ tag %>, <jsp:directive.page > or <jsp:directive.tag >. */ while (true) { if (jspReader.skipUntil("<") == null) { break; } // If this is a comment, skip until its end if (jspReader.matches("%--")) { if (jspReader.skipUntil("--%>") == null) { // error will be caught in Parser break; } continue; } boolean isDirective = jspReader.matches("%@"); if (isDirective) { jspReader.skipSpaces(); } else { isDirective = jspReader.matches("jsp:directive."); } if (!isDirective) { continue; } // compare for "tag ", so we don't match "taglib" if (jspReader.matches("tag ") || jspReader.matches("page")) { jspReader.skipSpaces(); Attributes attrs = Parser.parseAttributes(this, jspReader); encoding = getPageEncodingFromDirective(attrs, "pageEncoding"); if (encoding != null) { break; } encoding = getPageEncodingFromDirective(attrs, "contentType"); if (encoding != null) { saveEncoding = encoding; } } } if (encoding == null) { encoding = saveEncoding; } return encoding; }
// in java/org/apache/jasper/compiler/ParserController.java
private boolean hasJspRoot(JspReader reader) throws JasperException { // <prefix>:root must be the first element Mark start = null; while ((start = reader.skipUntil("<")) != null) { int c = reader.nextChar(); if (c != '!' && c != '?') break; } if (start == null) { return false; } Mark stop = reader.skipUntil(":root"); if (stop == null) { return false; } // call substring to get rid of leading '<' String prefix = reader.getText(start, stop).substring(1); start = stop; stop = reader.skipUntil(">"); if (stop == null) { return false; } // Determine namespace associated with <root> element's prefix String root = reader.getText(start, stop); String xmlnsDecl = "xmlns:" + prefix; int index = root.indexOf(xmlnsDecl); if (index == -1) { return false; } index += xmlnsDecl.length(); while (index < root.length() && Character.isWhitespace(root.charAt(index))) { index++; } if (index < root.length() && root.charAt(index) == '=') { index++; while (index < root.length() && Character.isWhitespace(root.charAt(index))) { index++; } if (index < root.length() && (root.charAt(index) == '"' || root.charAt(index) == '\'')) { index++; if (root.regionMatches(index, JSP_URI, 0, JSP_URI.length())) { return true; } } } return false; }
// in java/org/apache/jasper/compiler/ELNode.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/ELNode.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/ELNode.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/ELNode.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/ELNode.java
public void visit(Visitor v) throws JasperException { Iterator<ELNode> iter = list.iterator(); while (iter.hasNext()) { ELNode n = iter.next(); n.accept(v); } }
// in java/org/apache/jasper/compiler/ELNode.java
public void visit(Root n) throws JasperException { n.getExpression().visit(this); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
private void parseTLD(String uri, InputStream in, JarResource jarResource) throws JasperException { Vector<TagInfo> tagVector = new Vector<TagInfo>(); Vector<TagFileInfo> tagFileVector = new Vector<TagFileInfo>(); Hashtable<String, FunctionInfo> functionTable = new Hashtable<String, FunctionInfo>(); // Create an iterator over the child elements of our <taglib> element ParserUtils pu = new ParserUtils(); TreeNode tld = pu.parseXMLDocument(uri, in); // Check to see if the <taglib> root element contains a 'version' // attribute, which was added in JSP 2.0 to replace the <jsp-version> // subelement this.jspversion = tld.findAttribute("version"); // Process each child element of our <taglib> element Iterator<TreeNode> list = tld.findChildren(); while (list.hasNext()) { TreeNode element = list.next(); String tname = element.getName(); if ("tlibversion".equals(tname) // JSP 1.1 || "tlib-version".equals(tname)) { // JSP 1.2 this.tlibversion = element.getBody(); } else if ("jspversion".equals(tname) || "jsp-version".equals(tname)) { this.jspversion = element.getBody(); } else if ("shortname".equals(tname) || "short-name".equals(tname)) this.shortname = element.getBody(); else if ("uri".equals(tname)) this.urn = element.getBody(); else if ("info".equals(tname) || "description".equals(tname)) this.info = element.getBody(); else if ("validator".equals(tname)) this.tagLibraryValidator = createValidator(element); else if ("tag".equals(tname)) tagVector.addElement(createTagInfo(element, jspversion)); else if ("tag-file".equals(tname)) { TagFileInfo tagFileInfo = createTagFileInfo(element, jarResource); tagFileVector.addElement(tagFileInfo); } else if ("function".equals(tname)) { // JSP2.0 FunctionInfo funcInfo = createFunctionInfo(element); String funcName = funcInfo.getName(); if (functionTable.containsKey(funcName)) { err.jspError("jsp.error.tld.fn.duplicate.name", funcName, uri); } functionTable.put(funcName, funcInfo); } else if ("display-name".equals(tname) || "small-icon".equals(tname) || "large-icon".equals(tname) || "listener".equals(tname)) { // Ignored elements } else if ("taglib-extension".equals(tname)) { // Recognized but ignored } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage( "jsp.warning.unknown.element.in.taglib", tname)); } } } if (tlibversion == null) { err.jspError("jsp.error.tld.mandatory.element.missing", "tlib-version", uri); } if (jspversion == null) { err.jspError("jsp.error.tld.mandatory.element.missing", "jsp-version", uri); } this.tags = new TagInfo[tagVector.size()]; tagVector.copyInto(this.tags); this.tagFiles = new TagFileInfo[tagFileVector.size()]; tagFileVector.copyInto(this.tagFiles); this.functions = new FunctionInfo[functionTable.size()]; int i = 0; Enumeration<FunctionInfo> enumeration = functionTable.elements(); while (enumeration.hasMoreElements()) { this.functions[i++] = enumeration.nextElement(); } }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
private TldLocation generateTLDLocation(String uri, JspCompilationContext ctxt) throws JasperException { int uriType = TldLocationsCache.uriType(uri); if (uriType == TldLocationsCache.ABS_URI) { err.jspError("jsp.error.taglibDirective.absUriCannotBeResolved", uri); } else if (uriType == TldLocationsCache.NOROOT_REL_URI) { uri = ctxt.resolveRelativeUri(uri); } if (uri.endsWith(".jar")) { URL url = null; try { url = ctxt.getResource(uri); } catch (Exception ex) { err.jspError("jsp.error.tld.unable_to_get_jar", uri, ex .toString()); } if (url == null) { err.jspError("jsp.error.tld.missing_jar", uri); } return new TldLocation("META-INF/taglib.tld", url.toString()); } else { return new TldLocation(uri); } }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
private TagInfo createTagInfo(TreeNode elem, String jspVersion) throws JasperException { String tagName = null; String tagClassName = null; String teiClassName = null; /* * Default body content for JSP 1.2 tag handlers (<body-content> has * become mandatory in JSP 2.0, because the default would be invalid for * simple tag handlers) */ String bodycontent = "JSP"; String info = null; String displayName = null; String smallIcon = null; String largeIcon = null; boolean dynamicAttributes = false; Vector<TagAttributeInfo> attributeVector = new Vector<TagAttributeInfo>(); Vector<TagVariableInfo> variableVector = new Vector<TagVariableInfo>(); Iterator<TreeNode> list = elem.findChildren(); while (list.hasNext()) { TreeNode element = list.next(); String tname = element.getName(); if ("name".equals(tname)) { tagName = element.getBody(); } else if ("tagclass".equals(tname) || "tag-class".equals(tname)) { tagClassName = element.getBody(); } else if ("teiclass".equals(tname) || "tei-class".equals(tname)) { teiClassName = element.getBody(); } else if ("bodycontent".equals(tname) || "body-content".equals(tname)) { bodycontent = element.getBody(); } else if ("display-name".equals(tname)) { displayName = element.getBody(); } else if ("small-icon".equals(tname)) { smallIcon = element.getBody(); } else if ("large-icon".equals(tname)) { largeIcon = element.getBody(); } else if ("icon".equals(tname)) { TreeNode icon = element.findChild("small-icon"); if (icon != null) { smallIcon = icon.getBody(); } icon = element.findChild("large-icon"); if (icon != null) { largeIcon = icon.getBody(); } } else if ("info".equals(tname) || "description".equals(tname)) { info = element.getBody(); } else if ("variable".equals(tname)) { variableVector.addElement(createVariable(element)); } else if ("attribute".equals(tname)) { attributeVector .addElement(createAttribute(element, jspVersion)); } else if ("dynamic-attributes".equals(tname)) { dynamicAttributes = JspUtil.booleanValue(element.getBody()); } else if ("example".equals(tname)) { // Ignored elements } else if ("tag-extension".equals(tname)) { // Ignored } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage( "jsp.warning.unknown.element.in.tag", tname)); } } } TagExtraInfo tei = null; if (teiClassName != null && !teiClassName.equals("")) { try { Class<?> teiClass = ctxt.getClassLoader().loadClass(teiClassName); tei = (TagExtraInfo) teiClass.newInstance(); } catch (Exception e) { err.jspError("jsp.error.teiclass.instantiation", teiClassName, e); } } TagAttributeInfo[] tagAttributeInfo = new TagAttributeInfo[attributeVector .size()]; attributeVector.copyInto(tagAttributeInfo); TagVariableInfo[] tagVariableInfos = new TagVariableInfo[variableVector .size()]; variableVector.copyInto(tagVariableInfos); TagInfo taginfo = new TagInfo(tagName, tagClassName, bodycontent, info, this, tei, tagAttributeInfo, displayName, smallIcon, largeIcon, tagVariableInfos, dynamicAttributes); return taginfo; }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
private TagFileInfo createTagFileInfo(TreeNode elem, JarResource jarResource) throws JasperException { String name = null; String path = null; Iterator<TreeNode> list = elem.findChildren(); while (list.hasNext()) { TreeNode child = list.next(); String tname = child.getName(); if ("name".equals(tname)) { name = child.getBody(); } else if ("path".equals(tname)) { path = child.getBody(); } else if ("example".equals(tname)) { // Ignore <example> element: Bugzilla 33538 } else if ("tag-extension".equals(tname)) { // Ignore <tag-extension> element: Bugzilla 33538 } else if ("icon".equals(tname) || "display-name".equals(tname) || "description".equals(tname)) { // Ignore these elements: Bugzilla 38015 } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage( "jsp.warning.unknown.element.in.tagfile", tname)); } } } if (path.startsWith("/META-INF/tags")) { // Tag file packaged in JAR // See https://issues.apache.org/bugzilla/show_bug.cgi?id=46471 // This needs to be removed once all the broken code that depends on // it has been removed ctxt.setTagFileJarResource(path, jarResource); } else if (!path.startsWith("/WEB-INF/tags")) { err.jspError("jsp.error.tagfile.illegalPath", path); } TagInfo tagInfo = TagFileProcessor.parseTagFileDirectives( parserController, name, path, jarResource, this); return new TagFileInfo(name, path, tagInfo); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
private TagLibraryValidator createValidator(TreeNode elem) throws JasperException { String validatorClass = null; Map<String,Object> initParams = new Hashtable<String,Object>(); Iterator<TreeNode> list = elem.findChildren(); while (list.hasNext()) { TreeNode element = list.next(); String tname = element.getName(); if ("validator-class".equals(tname)) validatorClass = element.getBody(); else if ("init-param".equals(tname)) { String[] initParam = createInitParam(element); initParams.put(initParam[0], initParam[1]); } else if ("description".equals(tname) || // Ignored elements false) { } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage( "jsp.warning.unknown.element.in.validator", tname)); } } } TagLibraryValidator tlv = null; if (validatorClass != null && !validatorClass.equals("")) { try { Class<?> tlvClass = ctxt.getClassLoader() .loadClass(validatorClass); tlv = (TagLibraryValidator) tlvClass.newInstance(); } catch (Exception e) { err.jspError("jsp.error.tlvclass.instantiation", validatorClass, e); } } if (tlv != null) { tlv.setInitParameters(initParams); } return tlv; }
// in java/org/apache/jasper/compiler/Parser.java
public static Node.Nodes parse(ParserController pc, JspReader reader, Node parent, boolean isTagFile, boolean directivesOnly, JarResource jarResource, String pageEnc, String jspConfigPageEnc, boolean isDefaultPageEncoding, boolean isBomPresent) throws JasperException { Parser parser = new Parser(pc, reader, isTagFile, directivesOnly, jarResource); Node.Root root = new Node.Root(reader.mark(), parent, false); root.setPageEncoding(pageEnc); root.setJspConfigPageEncoding(jspConfigPageEnc); root.setIsDefaultPageEncoding(isDefaultPageEncoding); root.setIsBomPresent(isBomPresent); // For the Top level page, add include-prelude and include-coda PageInfo pageInfo = pc.getCompiler().getPageInfo(); if (parent == null && !isTagFile) { parser.addInclude(root, pageInfo.getIncludePrelude()); } if (directivesOnly) { parser.parseFileDirectives(root); } else { while (reader.hasMoreInput()) { parser.parseElements(root); } } if (parent == null && !isTagFile) { parser.addInclude(root, pageInfo.getIncludeCoda()); } Node.Nodes page = new Node.Nodes(root); return page; }
// in java/org/apache/jasper/compiler/Parser.java
Attributes parseAttributes() throws JasperException { return parseAttributes(false); }
// in java/org/apache/jasper/compiler/Parser.java
Attributes parseAttributes(boolean pageDirective) throws JasperException { UniqueAttributesImpl attrs = new UniqueAttributesImpl(pageDirective); reader.skipSpaces(); int ws = 1; try { while (parseAttribute(attrs)) { if (ws == 0 && STRICT_WHITESPACE) { err.jspError(reader.mark(), "jsp.error.attribute.nowhitespace"); } ws = reader.skipSpaces(); } } catch (IllegalArgumentException iae) { // Duplicate attribute err.jspError(reader.mark(), "jsp.error.attribute.duplicate"); } return attrs; }
// in java/org/apache/jasper/compiler/Parser.java
public static Attributes parseAttributes(ParserController pc, JspReader reader) throws JasperException { Parser tmpParser = new Parser(pc, reader, false, false, null); return tmpParser.parseAttributes(true); }
// in java/org/apache/jasper/compiler/Parser.java
private boolean parseAttribute(AttributesImpl attrs) throws JasperException { // Get the qualified name String qName = parseName(); if (qName == null) return false; // Determine prefix and local name components String localName = qName; String uri = ""; int index = qName.indexOf(':'); if (index != -1) { String prefix = qName.substring(0, index); uri = pageInfo.getURI(prefix); if (uri == null) { err.jspError(reader.mark(), "jsp.error.attribute.invalidPrefix", prefix); } localName = qName.substring(index + 1); } reader.skipSpaces(); if (!reader.matches("=")) err.jspError(reader.mark(), "jsp.error.attribute.noequal"); reader.skipSpaces(); char quote = (char) reader.nextChar(); if (quote != '\'' && quote != '"') err.jspError(reader.mark(), "jsp.error.attribute.noquote"); String watchString = ""; if (reader.matches("<%=")) watchString = "%>"; watchString = watchString + quote; String attrValue = parseAttributeValue(watchString); attrs.addAttribute(uri, localName, qName, "CDATA", attrValue); return true; }
// in java/org/apache/jasper/compiler/Parser.java
private String parseName() throws JasperException { char ch = (char) reader.peekChar(); if (Character.isLetter(ch) || ch == '_' || ch == ':') { StringBuilder buf = new StringBuilder(); buf.append(ch); reader.nextChar(); ch = (char) reader.peekChar(); while (Character.isLetter(ch) || Character.isDigit(ch) || ch == '.' || ch == '_' || ch == '-' || ch == ':') { buf.append(ch); reader.nextChar(); ch = (char) reader.peekChar(); } return buf.toString(); } return null; }
// in java/org/apache/jasper/compiler/Parser.java
private String parseAttributeValue(String watch) throws JasperException { Mark start = reader.mark(); Mark stop = reader.skipUntilIgnoreEsc(watch); if (stop == null) { err.jspError(start, "jsp.error.attribute.unterminated", watch); } String ret = null; try { char quote = watch.charAt(watch.length() - 1); // If watch is longer than 1 character this is a scripting // expression and EL is always ignored boolean isElIgnored = pageInfo.isELIgnored() || watch.length() > 1; ret = AttributeParser.getUnquoted(reader.getText(start, stop), quote, isElIgnored, pageInfo.isDeferredSyntaxAllowedAsLiteral()); } catch (IllegalArgumentException iae) { err.jspError(start, iae.getMessage()); } if (watch.length() == 1) // quote return ret; // Put back delimiter '<%=' and '%>', since they are needed if the // attribute does not allow RTexpression. return "<%=" + ret + "%>"; }
// in java/org/apache/jasper/compiler/Parser.java
private void processIncludeDirective(String file, Node parent) throws JasperException { if (file == null) { return; } try { parserController.parse(file, parent, jarResource); } catch (FileNotFoundException ex) { err.jspError(start, "jsp.error.file.not.found", file); } catch (Exception ex) { err.jspError(start, ex.getMessage()); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parsePageDirective(Node parent) throws JasperException { Attributes attrs = parseAttributes(true); Node.PageDirective n = new Node.PageDirective(attrs, start, parent); /* * A page directive may contain multiple 'import' attributes, each of * which consists of a comma-separated list of package names. Store each * list with the node, where it is parsed. */ for (int i = 0; i < attrs.getLength(); i++) { if ("import".equals(attrs.getQName(i))) { n.addImport(attrs.getValue(i)); } } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseIncludeDirective(Node parent) throws JasperException { Attributes attrs = parseAttributes(); // Included file expanded here Node includeNode = new Node.IncludeDirective(attrs, start, parent); processIncludeDirective(attrs.getValue("file"), includeNode); }
// in java/org/apache/jasper/compiler/Parser.java
private void addInclude(Node parent, List<String> files) throws JasperException { if (files != null) { Iterator<String> iter = files.iterator(); while (iter.hasNext()) { String file = iter.next(); AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute("", "file", "file", "CDATA", file); // Create a dummy Include directive node Node includeNode = new Node.IncludeDirective(attrs, reader .mark(), parent); processIncludeDirective(file, includeNode); } } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseTaglibDirective(Node parent) throws JasperException { Attributes attrs = parseAttributes(); String uri = attrs.getValue("uri"); String prefix = attrs.getValue("prefix"); if (prefix != null) { Mark prevMark = pageInfo.getNonCustomTagPrefix(prefix); if (prevMark != null) { err.jspError(reader.mark(), "jsp.error.prefix.use_before_dcl", prefix, prevMark.getFile(), "" + prevMark.getLineNumber()); } if (uri != null) { String uriPrev = pageInfo.getURI(prefix); if (uriPrev != null && !uriPrev.equals(uri)) { err.jspError(reader.mark(), "jsp.error.prefix.refined", prefix, uri, uriPrev); } if (pageInfo.getTaglib(uri) == null) { TagLibraryInfoImpl impl = null; if (ctxt.getOptions().isCaching()) { impl = (TagLibraryInfoImpl) ctxt.getOptions() .getCache().get(uri); } if (impl == null) { TldLocation location = ctxt.getTldLocation(uri); impl = new TagLibraryInfoImpl(ctxt, parserController, pageInfo, prefix, uri, location, err, reader.mark()); if (ctxt.getOptions().isCaching()) { ctxt.getOptions().getCache().put(uri, impl); } } else { // Current compilation context needs location of cached // tag files for (TagFileInfo info : impl.getTagFiles()) { ctxt.setTagFileJarResource(info.getPath(), ctxt.getTagFileJarResource()); } } pageInfo.addTaglib(uri, impl); } pageInfo.addPrefixMapping(prefix, uri); } else { String tagdir = attrs.getValue("tagdir"); if (tagdir != null) { String urnTagdir = URN_JSPTAGDIR + tagdir; if (pageInfo.getTaglib(urnTagdir) == null) { pageInfo.addTaglib(urnTagdir, new ImplicitTagLibraryInfo(ctxt, parserController, pageInfo, prefix, tagdir, err)); } pageInfo.addPrefixMapping(prefix, urnTagdir); } } } new Node.TaglibDirective(attrs, start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseDirective(Node parent) throws JasperException { reader.skipSpaces(); String directive = null; if (reader.matches("page")) { directive = "&lt;%@ page"; if (isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.istagfile", directive); } parsePageDirective(parent); } else if (reader.matches("include")) { directive = "&lt;%@ include"; parseIncludeDirective(parent); } else if (reader.matches("taglib")) { if (directivesOnly) { // No need to get the tagLibInfo objects. This alos suppresses // parsing of any tag files used in this tag file. return; } directive = "&lt;%@ taglib"; parseTaglibDirective(parent); } else if (reader.matches("tag")) { directive = "&lt;%@ tag"; if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.isnottagfile", directive); } parseTagDirective(parent); } else if (reader.matches("attribute")) { directive = "&lt;%@ attribute"; if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.isnottagfile", directive); } parseAttributeDirective(parent); } else if (reader.matches("variable")) { directive = "&lt;%@ variable"; if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.isnottagfile", directive); } parseVariableDirective(parent); } else { err.jspError(reader.mark(), "jsp.error.invalid.directive"); } reader.skipSpaces(); if (!reader.matches("%>")) { err.jspError(start, "jsp.error.unterminated", directive); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseXMLDirective(Node parent) throws JasperException { reader.skipSpaces(); String eTag = null; if (reader.matches("page")) { eTag = "jsp:directive.page"; if (isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.istagfile", "&lt;" + eTag); } parsePageDirective(parent); } else if (reader.matches("include")) { eTag = "jsp:directive.include"; parseIncludeDirective(parent); } else if (reader.matches("tag")) { eTag = "jsp:directive.tag"; if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.isnottagfile", "&lt;" + eTag); } parseTagDirective(parent); } else if (reader.matches("attribute")) { eTag = "jsp:directive.attribute"; if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.isnottagfile", "&lt;" + eTag); } parseAttributeDirective(parent); } else if (reader.matches("variable")) { eTag = "jsp:directive.variable"; if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.isnottagfile", "&lt;" + eTag); } parseVariableDirective(parent); } else { err.jspError(reader.mark(), "jsp.error.invalid.directive"); } reader.skipSpaces(); if (reader.matches(">")) { reader.skipSpaces(); if (!reader.matchesETag(eTag)) { err.jspError(start, "jsp.error.unterminated", "&lt;" + eTag); } } else if (!reader.matches("/>")) { err.jspError(start, "jsp.error.unterminated", "&lt;" + eTag); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseTagDirective(Node parent) throws JasperException { Attributes attrs = parseAttributes(true); Node.TagDirective n = new Node.TagDirective(attrs, start, parent); /* * A page directive may contain multiple 'import' attributes, each of * which consists of a comma-separated list of package names. Store each * list with the node, where it is parsed. */ for (int i = 0; i < attrs.getLength(); i++) { if ("import".equals(attrs.getQName(i))) { n.addImport(attrs.getValue(i)); } } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseAttributeDirective(Node parent) throws JasperException { Attributes attrs = parseAttributes(); new Node.AttributeDirective(attrs, start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseVariableDirective(Node parent) throws JasperException { Attributes attrs = parseAttributes(); new Node.VariableDirective(attrs, start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseComment(Node parent) throws JasperException { start = reader.mark(); Mark stop = reader.skipUntil("--%>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "&lt;%--"); } new Node.Comment(reader.getText(start, stop), start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseDeclaration(Node parent) throws JasperException { start = reader.mark(); Mark stop = reader.skipUntil("%>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "&lt;%!"); } new Node.Declaration(parseScriptText(reader.getText(start, stop)), start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseXMLDeclaration(Node parent) throws JasperException { reader.skipSpaces(); if (!reader.matches("/>")) { if (!reader.matches(">")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:declaration&gt;"); } Mark stop; String text; while (true) { start = reader.mark(); stop = reader.skipUntil("<"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:declaration&gt;"); } text = parseScriptText(reader.getText(start, stop)); new Node.Declaration(text, start, parent); if (reader.matches("![CDATA[")) { start = reader.mark(); stop = reader.skipUntil("]]>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "CDATA"); } text = parseScriptText(reader.getText(start, stop)); new Node.Declaration(text, start, parent); } else { break; } } if (!reader.matchesETagWithoutLessThan("jsp:declaration")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:declaration&gt;"); } } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseExpression(Node parent) throws JasperException { start = reader.mark(); Mark stop = reader.skipUntil("%>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "&lt;%="); } new Node.Expression(parseScriptText(reader.getText(start, stop)), start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseXMLExpression(Node parent) throws JasperException { reader.skipSpaces(); if (!reader.matches("/>")) { if (!reader.matches(">")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:expression&gt;"); } Mark stop; String text; while (true) { start = reader.mark(); stop = reader.skipUntil("<"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:expression&gt;"); } text = parseScriptText(reader.getText(start, stop)); new Node.Expression(text, start, parent); if (reader.matches("![CDATA[")) { start = reader.mark(); stop = reader.skipUntil("]]>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "CDATA"); } text = parseScriptText(reader.getText(start, stop)); new Node.Expression(text, start, parent); } else { break; } } if (!reader.matchesETagWithoutLessThan("jsp:expression")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:expression&gt;"); } } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseELExpression(Node parent, char type) throws JasperException { start = reader.mark(); Mark last = null; boolean singleQuoted = false, doubleQuoted = false; int currentChar; do { // XXX could move this logic to JspReader last = reader.mark(); // XXX somewhat wasteful currentChar = reader.nextChar(); if (currentChar == '\\' && (singleQuoted || doubleQuoted)) { // skip character following '\' within quotes reader.nextChar(); currentChar = reader.nextChar(); } if (currentChar == -1) err.jspError(start, "jsp.error.unterminated", type + "{"); if (currentChar == '"' && !singleQuoted) doubleQuoted = !doubleQuoted; if (currentChar == '\'' && !doubleQuoted) singleQuoted = !singleQuoted; } while (currentChar != '}' || (singleQuoted || doubleQuoted)); new Node.ELExpression(type, reader.getText(start, last), start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseScriptlet(Node parent) throws JasperException { start = reader.mark(); Mark stop = reader.skipUntil("%>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "&lt;%"); } new Node.Scriptlet(parseScriptText(reader.getText(start, stop)), start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseXMLScriptlet(Node parent) throws JasperException { reader.skipSpaces(); if (!reader.matches("/>")) { if (!reader.matches(">")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:scriptlet&gt;"); } Mark stop; String text; while (true) { start = reader.mark(); stop = reader.skipUntil("<"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:scriptlet&gt;"); } text = parseScriptText(reader.getText(start, stop)); new Node.Scriptlet(text, start, parent); if (reader.matches("![CDATA[")) { start = reader.mark(); stop = reader.skipUntil("]]>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "CDATA"); } text = parseScriptText(reader.getText(start, stop)); new Node.Scriptlet(text, start, parent); } else { break; } } if (!reader.matchesETagWithoutLessThan("jsp:scriptlet")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:scriptlet&gt;"); } } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseParam(Node parent) throws JasperException { if (!reader.matches("<jsp:param")) { err.jspError(reader.mark(), "jsp.error.paramexpected"); } Attributes attrs = parseAttributes(); reader.skipSpaces(); Node paramActionNode = new Node.ParamAction(attrs, start, parent); parseEmptyBody(paramActionNode, "jsp:param"); reader.skipSpaces(); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseInclude(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node includeNode = new Node.IncludeAction(attrs, start, parent); parseOptionalBody(includeNode, "jsp:include", JAVAX_BODY_CONTENT_PARAM); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseForward(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node forwardNode = new Node.ForwardAction(attrs, start, parent); parseOptionalBody(forwardNode, "jsp:forward", JAVAX_BODY_CONTENT_PARAM); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseInvoke(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node invokeNode = new Node.InvokeAction(attrs, start, parent); parseEmptyBody(invokeNode, "jsp:invoke"); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseDoBody(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node doBodyNode = new Node.DoBodyAction(attrs, start, parent); parseEmptyBody(doBodyNode, "jsp:doBody"); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseElement(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node elementNode = new Node.JspElement(attrs, start, parent); parseOptionalBody(elementNode, "jsp:element", TagInfo.BODY_CONTENT_JSP); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseGetProperty(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node getPropertyNode = new Node.GetProperty(attrs, start, parent); parseOptionalBody(getPropertyNode, "jsp:getProperty", TagInfo.BODY_CONTENT_EMPTY); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseSetProperty(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node setPropertyNode = new Node.SetProperty(attrs, start, parent); parseOptionalBody(setPropertyNode, "jsp:setProperty", TagInfo.BODY_CONTENT_EMPTY); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseEmptyBody(Node parent, String tag) throws JasperException { if (reader.matches("/>")) { // Done } else if (reader.matches(">")) { if (reader.matchesETag(tag)) { // Done } else if (reader.matchesOptionalSpacesFollowedBy("<jsp:attribute")) { // Parse the one or more named attribute nodes parseNamedAttributes(parent); if (!reader.matchesETag(tag)) { // Body not allowed err.jspError(reader.mark(), "jsp.error.jspbody.emptybody.only", "&lt;" + tag); } } else { err.jspError(reader.mark(), "jsp.error.jspbody.emptybody.only", "&lt;" + tag); } } else { err.jspError(reader.mark(), "jsp.error.unterminated", "&lt;" + tag); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseUseBean(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node useBeanNode = new Node.UseBean(attrs, start, parent); parseOptionalBody(useBeanNode, "jsp:useBean", TagInfo.BODY_CONTENT_JSP); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseOptionalBody(Node parent, String tag, String bodyType) throws JasperException { if (reader.matches("/>")) { // EmptyBody return; } if (!reader.matches(">")) { err.jspError(reader.mark(), "jsp.error.unterminated", "&lt;" + tag); } if (reader.matchesETag(tag)) { // EmptyBody return; } if (!parseJspAttributeAndBody(parent, tag, bodyType)) { // Must be ( '>' # Body ETag ) parseBody(parent, tag, bodyType); } }
// in java/org/apache/jasper/compiler/Parser.java
private boolean parseJspAttributeAndBody(Node parent, String tag, String bodyType) throws JasperException { boolean result = false; if (reader.matchesOptionalSpacesFollowedBy("<jsp:attribute")) { // May be an EmptyBody, depending on whether // There's a "<jsp:body" before the ETag // First, parse <jsp:attribute> elements: parseNamedAttributes(parent); result = true; } if (reader.matchesOptionalSpacesFollowedBy("<jsp:body")) { // ActionBody parseJspBody(parent, bodyType); reader.skipSpaces(); if (!reader.matchesETag(tag)) { err.jspError(reader.mark(), "jsp.error.unterminated", "&lt;" + tag); } result = true; } else if (result && !reader.matchesETag(tag)) { // If we have <jsp:attribute> but something other than // <jsp:body> or the end tag, translation error. err.jspError(reader.mark(), "jsp.error.jspbody.required", "&lt;" + tag); } return result; }
// in java/org/apache/jasper/compiler/Parser.java
private void parseJspParams(Node parent) throws JasperException { Node jspParamsNode = new Node.ParamsAction(start, parent); parseOptionalBody(jspParamsNode, "jsp:params", JAVAX_BODY_CONTENT_PARAM); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseFallBack(Node parent) throws JasperException { Node fallBackNode = new Node.FallBackAction(start, parent); parseOptionalBody(fallBackNode, "jsp:fallback", JAVAX_BODY_CONTENT_TEMPLATE_TEXT); }
// in java/org/apache/jasper/compiler/Parser.java
private void parsePlugin(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node pluginNode = new Node.PlugIn(attrs, start, parent); parseOptionalBody(pluginNode, "jsp:plugin", JAVAX_BODY_CONTENT_PLUGIN); }
// in java/org/apache/jasper/compiler/Parser.java
private void parsePluginTags(Node parent) throws JasperException { reader.skipSpaces(); if (reader.matches("<jsp:params")) { parseJspParams(parent); reader.skipSpaces(); } if (reader.matches("<jsp:fallback")) { parseFallBack(parent); reader.skipSpaces(); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseStandardAction(Node parent) throws JasperException { Mark start = reader.mark(); if (reader.matches(INCLUDE_ACTION)) { parseInclude(parent); } else if (reader.matches(FORWARD_ACTION)) { parseForward(parent); } else if (reader.matches(INVOKE_ACTION)) { if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.action.isnottagfile", "&lt;jsp:invoke"); } parseInvoke(parent); } else if (reader.matches(DOBODY_ACTION)) { if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.action.isnottagfile", "&lt;jsp:doBody"); } parseDoBody(parent); } else if (reader.matches(GET_PROPERTY_ACTION)) { parseGetProperty(parent); } else if (reader.matches(SET_PROPERTY_ACTION)) { parseSetProperty(parent); } else if (reader.matches(USE_BEAN_ACTION)) { parseUseBean(parent); } else if (reader.matches(PLUGIN_ACTION)) { parsePlugin(parent); } else if (reader.matches(ELEMENT_ACTION)) { parseElement(parent); } else if (reader.matches(ATTRIBUTE_ACTION)) { err.jspError(start, "jsp.error.namedAttribute.invalidUse"); } else if (reader.matches(BODY_ACTION)) { err.jspError(start, "jsp.error.jspbody.invalidUse"); } else if (reader.matches(FALLBACK_ACTION)) { err.jspError(start, "jsp.error.fallback.invalidUse"); } else if (reader.matches(PARAMS_ACTION)) { err.jspError(start, "jsp.error.params.invalidUse"); } else if (reader.matches(PARAM_ACTION)) { err.jspError(start, "jsp.error.param.invalidUse"); } else if (reader.matches(OUTPUT_ACTION)) { err.jspError(start, "jsp.error.jspoutput.invalidUse"); } else { err.jspError(start, "jsp.error.badStandardAction"); } }
// in java/org/apache/jasper/compiler/Parser.java
private boolean parseCustomTag(Node parent) throws JasperException { if (reader.peekChar() != '<') { return false; } // Parse 'CustomAction' production (tag prefix and custom action name) reader.nextChar(); // skip '<' String tagName = reader.parseToken(false); int i = tagName.indexOf(':'); if (i == -1) { reader.reset(start); return false; } String prefix = tagName.substring(0, i); String shortTagName = tagName.substring(i + 1); // Check if this is a user-defined tag. String uri = pageInfo.getURI(prefix); if (uri == null) { if (pageInfo.isErrorOnUndeclaredNamespace()) { err.jspError(start, "jsp.error.undeclared_namespace", prefix); } else { reader.reset(start); // Remember the prefix for later error checking pageInfo.putNonCustomTagPrefix(prefix, reader.mark()); return false; } } TagLibraryInfo tagLibInfo = pageInfo.getTaglib(uri); TagInfo tagInfo = tagLibInfo.getTag(shortTagName); TagFileInfo tagFileInfo = tagLibInfo.getTagFile(shortTagName); if (tagInfo == null && tagFileInfo == null) { err.jspError(start, "jsp.error.bad_tag", shortTagName, prefix); } Class<?> tagHandlerClass = null; if (tagInfo != null) { // Must be a classic tag, load it here. // tag files will be loaded later, in TagFileProcessor String handlerClassName = tagInfo.getTagClassName(); try { tagHandlerClass = ctxt.getClassLoader().loadClass( handlerClassName); } catch (Exception e) { err.jspError(start, "jsp.error.loadclass.taghandler", handlerClassName, tagName); } } // Parse 'CustomActionBody' production: // At this point we are committed - if anything fails, we produce // a translation error. // Parse 'Attributes' production: Attributes attrs = parseAttributes(); reader.skipSpaces(); // Parse 'CustomActionEnd' production: if (reader.matches("/>")) { if (tagInfo != null) { new Node.CustomTag(tagName, prefix, shortTagName, uri, attrs, start, parent, tagInfo, tagHandlerClass); } else { new Node.CustomTag(tagName, prefix, shortTagName, uri, attrs, start, parent, tagFileInfo); } return true; } // Now we parse one of 'CustomActionTagDependent', // 'CustomActionJSPContent', or 'CustomActionScriptlessContent'. // depending on body-content in TLD. // Looking for a body, it still can be empty; but if there is a // a tag body, its syntax would be dependent on the type of // body content declared in the TLD. String bc; if (tagInfo != null) { bc = tagInfo.getBodyContent(); } else { bc = tagFileInfo.getTagInfo().getBodyContent(); } Node tagNode = null; if (tagInfo != null) { tagNode = new Node.CustomTag(tagName, prefix, shortTagName, uri, attrs, start, parent, tagInfo, tagHandlerClass); } else { tagNode = new Node.CustomTag(tagName, prefix, shortTagName, uri, attrs, start, parent, tagFileInfo); } parseOptionalBody(tagNode, tagName, bc); return true; }
// in java/org/apache/jasper/compiler/Parser.java
private void parseTemplateText(Node parent) throws JasperException { if (!reader.hasMoreInput()) return; CharArrayWriter ttext = new CharArrayWriter(); // Output the first character int ch = reader.nextChar(); if (ch == '\\') { reader.pushChar(); } else { ttext.write(ch); } while (reader.hasMoreInput()) { int prev = ch; ch = reader.nextChar(); if (ch == '<') { reader.pushChar(); break; } else if ((ch == '$' || ch == '#') && !pageInfo.isELIgnored()) { if (!reader.hasMoreInput()) { ttext.write(ch); break; } if (reader.nextChar() == '{') { reader.pushChar(); reader.pushChar(); break; } ttext.write(ch); reader.pushChar(); continue; } else if (ch == '\\') { if (!reader.hasMoreInput()) { ttext.write('\\'); break; } char next = (char) reader.peekChar(); // Looking for \% or \$ or \# if ((prev == '<' && next == '%') || ((next == '$' || next == '#') && !pageInfo.isELIgnored())) { ch = reader.nextChar(); } } ttext.write(ch); } new Node.TemplateText(ttext.toString(), start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseXMLTemplateText(Node parent) throws JasperException { reader.skipSpaces(); if (!reader.matches("/>")) { if (!reader.matches(">")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:text&gt;"); } CharArrayWriter ttext = new CharArrayWriter(); while (reader.hasMoreInput()) { int ch = reader.nextChar(); if (ch == '<') { // Check for <![CDATA[ if (!reader.matches("![CDATA[")) { break; } start = reader.mark(); Mark stop = reader.skipUntil("]]>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "CDATA"); } String text = reader.getText(start, stop); ttext.write(text, 0, text.length()); } else if (ch == '\\') { if (!reader.hasMoreInput()) { ttext.write('\\'); break; } ch = reader.nextChar(); if (ch != '$' && ch != '#') { ttext.write('\\'); } ttext.write(ch); } else if (ch == '$' || ch == '#') { if (!reader.hasMoreInput()) { ttext.write(ch); break; } if (reader.nextChar() != '{') { ttext.write(ch); reader.pushChar(); continue; } // Create a template text node new Node.TemplateText(ttext.toString(), start, parent); // Mark and parse the EL expression and create its node: start = reader.mark(); parseELExpression(parent, (char) ch); start = reader.mark(); ttext = new CharArrayWriter(); } else { ttext.write(ch); } } new Node.TemplateText(ttext.toString(), start, parent); if (!reader.hasMoreInput()) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:text&gt;"); } else if (!reader.matchesETagWithoutLessThan("jsp:text")) { err.jspError(start, "jsp.error.jsptext.badcontent"); } } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseElements(Node parent) throws JasperException { if (scriptlessCount > 0) { // vc: ScriptlessBody // We must follow the ScriptlessBody production if one of // our parents is ScriptlessBody. parseElementsScriptless(parent); return; } start = reader.mark(); if (reader.matches("<%--")) { parseComment(parent); } else if (reader.matches("<%@")) { parseDirective(parent); } else if (reader.matches("<jsp:directive.")) { parseXMLDirective(parent); } else if (reader.matches("<%!")) { parseDeclaration(parent); } else if (reader.matches("<jsp:declaration")) { parseXMLDeclaration(parent); } else if (reader.matches("<%=")) { parseExpression(parent); } else if (reader.matches("<jsp:expression")) { parseXMLExpression(parent); } else if (reader.matches("<%")) { parseScriptlet(parent); } else if (reader.matches("<jsp:scriptlet")) { parseXMLScriptlet(parent); } else if (reader.matches("<jsp:text")) { parseXMLTemplateText(parent); } else if (!pageInfo.isELIgnored() && reader.matches("${")) { parseELExpression(parent, '$'); } else if (!pageInfo.isELIgnored() && !pageInfo.isDeferredSyntaxAllowedAsLiteral() && reader.matches("#{")) { parseELExpression(parent, '#'); } else if (reader.matches("<jsp:")) { parseStandardAction(parent); } else if (!parseCustomTag(parent)) { checkUnbalancedEndTag(); parseTemplateText(parent); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseElementsScriptless(Node parent) throws JasperException { // Keep track of how many scriptless nodes we've encountered // so we know whether our child nodes are forced scriptless scriptlessCount++; start = reader.mark(); if (reader.matches("<%--")) { parseComment(parent); } else if (reader.matches("<%@")) { parseDirective(parent); } else if (reader.matches("<jsp:directive.")) { parseXMLDirective(parent); } else if (reader.matches("<%!")) { err.jspError(reader.mark(), "jsp.error.no.scriptlets"); } else if (reader.matches("<jsp:declaration")) { err.jspError(reader.mark(), "jsp.error.no.scriptlets"); } else if (reader.matches("<%=")) { err.jspError(reader.mark(), "jsp.error.no.scriptlets"); } else if (reader.matches("<jsp:expression")) { err.jspError(reader.mark(), "jsp.error.no.scriptlets"); } else if (reader.matches("<%")) { err.jspError(reader.mark(), "jsp.error.no.scriptlets"); } else if (reader.matches("<jsp:scriptlet")) { err.jspError(reader.mark(), "jsp.error.no.scriptlets"); } else if (reader.matches("<jsp:text")) { parseXMLTemplateText(parent); } else if (!pageInfo.isELIgnored() && reader.matches("${")) { parseELExpression(parent, '$'); } else if (!pageInfo.isELIgnored() && !pageInfo.isDeferredSyntaxAllowedAsLiteral() && reader.matches("#{")) { parseELExpression(parent, '#'); } else if (reader.matches("<jsp:")) { parseStandardAction(parent); } else if (!parseCustomTag(parent)) { checkUnbalancedEndTag(); parseTemplateText(parent); } scriptlessCount--; }
// in java/org/apache/jasper/compiler/Parser.java
private void parseElementsTemplateText(Node parent) throws JasperException { start = reader.mark(); if (reader.matches("<%--")) { parseComment(parent); } else if (reader.matches("<%@")) { parseDirective(parent); } else if (reader.matches("<jsp:directive.")) { parseXMLDirective(parent); } else if (reader.matches("<%!")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Declarations"); } else if (reader.matches("<jsp:declaration")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Declarations"); } else if (reader.matches("<%=")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Expressions"); } else if (reader.matches("<jsp:expression")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Expressions"); } else if (reader.matches("<%")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Scriptlets"); } else if (reader.matches("<jsp:scriptlet")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Scriptlets"); } else if (reader.matches("<jsp:text")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "&lt;jsp:text"); } else if (!pageInfo.isELIgnored() && reader.matches("${")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Expression language"); } else if (!pageInfo.isELIgnored() && !pageInfo.isDeferredSyntaxAllowedAsLiteral() && reader.matches("#{")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Expression language"); } else if (reader.matches("<jsp:")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Standard actions"); } else if (parseCustomTag(parent)) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Custom actions"); } else { checkUnbalancedEndTag(); parseTemplateText(parent); } }
// in java/org/apache/jasper/compiler/Parser.java
private void checkUnbalancedEndTag() throws JasperException { if (!reader.matches("</")) { return; } // Check for unbalanced standard actions if (reader.matches("jsp:")) { err.jspError(start, "jsp.error.unbalanced.endtag", "jsp:"); } // Check for unbalanced custom actions String tagName = reader.parseToken(false); int i = tagName.indexOf(':'); if (i == -1 || pageInfo.getURI(tagName.substring(0, i)) == null) { reader.reset(start); return; } err.jspError(start, "jsp.error.unbalanced.endtag", tagName); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseTagDependentBody(Node parent, String tag) throws JasperException { Mark bodyStart = reader.mark(); Mark bodyEnd = reader.skipUntilETag(tag); if (bodyEnd == null) { err.jspError(start, "jsp.error.unterminated", "&lt;" + tag); } new Node.TemplateText(reader.getText(bodyStart, bodyEnd), bodyStart, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseJspBody(Node parent, String bodyType) throws JasperException { Mark start = reader.mark(); Node bodyNode = new Node.JspBody(start, parent); reader.skipSpaces(); if (!reader.matches("/>")) { if (!reader.matches(">")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:body"); } parseBody(bodyNode, "jsp:body", bodyType); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseBody(Node parent, String tag, String bodyType) throws JasperException { if (bodyType.equalsIgnoreCase(TagInfo.BODY_CONTENT_TAG_DEPENDENT)) { parseTagDependentBody(parent, tag); } else if (bodyType.equalsIgnoreCase(TagInfo.BODY_CONTENT_EMPTY)) { if (!reader.matchesETag(tag)) { err.jspError(start, "jasper.error.emptybodycontent.nonempty", tag); } } else if (bodyType == JAVAX_BODY_CONTENT_PLUGIN) { // (note the == since we won't recognize JAVAX_* // from outside this module). parsePluginTags(parent); if (!reader.matchesETag(tag)) { err.jspError(reader.mark(), "jsp.error.unterminated", "&lt;" + tag); } } else if (bodyType.equalsIgnoreCase(TagInfo.BODY_CONTENT_JSP) || bodyType.equalsIgnoreCase(TagInfo.BODY_CONTENT_SCRIPTLESS) || (bodyType == JAVAX_BODY_CONTENT_PARAM) || (bodyType == JAVAX_BODY_CONTENT_TEMPLATE_TEXT)) { while (reader.hasMoreInput()) { if (reader.matchesETag(tag)) { return; } // Check for nested jsp:body or jsp:attribute if (tag.equals("jsp:body") || tag.equals("jsp:attribute")) { if (reader.matches("<jsp:attribute")) { err.jspError(reader.mark(), "jsp.error.nested.jspattribute"); } else if (reader.matches("<jsp:body")) { err.jspError(reader.mark(), "jsp.error.nested.jspbody"); } } if (bodyType.equalsIgnoreCase(TagInfo.BODY_CONTENT_JSP)) { parseElements(parent); } else if (bodyType .equalsIgnoreCase(TagInfo.BODY_CONTENT_SCRIPTLESS)) { parseElementsScriptless(parent); } else if (bodyType == JAVAX_BODY_CONTENT_PARAM) { // (note the == since we won't recognize JAVAX_* // from outside this module). reader.skipSpaces(); parseParam(parent); } else if (bodyType == JAVAX_BODY_CONTENT_TEMPLATE_TEXT) { parseElementsTemplateText(parent); } } err.jspError(start, "jsp.error.unterminated", "&lt;" + tag); } else { err.jspError(start, "jasper.error.bad.bodycontent.type"); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseNamedAttributes(Node parent) throws JasperException { do { Mark start = reader.mark(); Attributes attrs = parseAttributes(); Node.NamedAttribute namedAttributeNode = new Node.NamedAttribute( attrs, start, parent); reader.skipSpaces(); if (!reader.matches("/>")) { if (!reader.matches(">")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:attribute"); } if (namedAttributeNode.isTrim()) { reader.skipSpaces(); } parseBody(namedAttributeNode, "jsp:attribute", getAttributeBodyType(parent, attrs.getValue("name"))); if (namedAttributeNode.isTrim()) { Node.Nodes subElems = namedAttributeNode.getBody(); if (subElems != null) { Node lastNode = subElems.getNode(subElems.size() - 1); if (lastNode instanceof Node.TemplateText) { ((Node.TemplateText) lastNode).rtrim(); } } } } reader.skipSpaces(); } while (reader.matches("<jsp:attribute")); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseFileDirectives(Node parent) throws JasperException { reader.setSingleFile(true); reader.skipUntil("<"); while (reader.hasMoreInput()) { start = reader.mark(); if (reader.matches("%--")) { // Comment reader.skipUntil("--%>"); } else if (reader.matches("%@")) { parseDirective(parent); } else if (reader.matches("jsp:directive.")) { parseXMLDirective(parent); } else if (reader.matches("%!")) { // Declaration reader.skipUntil("%>"); } else if (reader.matches("%=")) { // Expression reader.skipUntil("%>"); } else if (reader.matches("%")) { // Scriptlet reader.skipUntil("%>"); } reader.skipUntil("<"); } }
// in java/org/apache/jasper/compiler/BeanRepository.java
public void addBean(Node.UseBean n, String s, String type, String scope) throws JasperException { if (!(scope == null || scope.equals("page") || scope.equals("request") || scope.equals("session") || scope.equals("application"))) { errDispatcher.jspError(n, "jsp.error.usebean.badScope"); } beanTypes.put(s, type); }
// in java/org/apache/jasper/compiler/BeanRepository.java
public Class<?> getBeanType(String bean) throws JasperException { Class<?> clazz = null; try { clazz = loader.loadClass(beanTypes.get(bean)); } catch (ClassNotFoundException ex) { throw new JasperException (ex); } return clazz; }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
Override public void visit(Node.TagDirective n) throws JasperException { JspUtil.checkAttributes("Tag directive", n, tagDirectiveAttrs, err); bodycontent = checkConflict(n, bodycontent, "body-content"); if (bodycontent != null && !bodycontent .equalsIgnoreCase(TagInfo.BODY_CONTENT_EMPTY) && !bodycontent .equalsIgnoreCase(TagInfo.BODY_CONTENT_TAG_DEPENDENT) && !bodycontent .equalsIgnoreCase(TagInfo.BODY_CONTENT_SCRIPTLESS)) { err.jspError(n, "jsp.error.tagdirective.badbodycontent", bodycontent); } dynamicAttrsMapName = checkConflict(n, dynamicAttrsMapName, "dynamic-attributes"); if (dynamicAttrsMapName != null) { checkUniqueName(dynamicAttrsMapName, TAG_DYNAMIC, n); } smallIcon = checkConflict(n, smallIcon, "small-icon"); largeIcon = checkConflict(n, largeIcon, "large-icon"); description = checkConflict(n, description, "description"); displayName = checkConflict(n, displayName, "display-name"); example = checkConflict(n, example, "example"); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
private String checkConflict(Node n, String oldAttrValue, String attr) throws JasperException { String result = oldAttrValue; String attrValue = n.getAttributeValue(attr); if (attrValue != null) { if (oldAttrValue != null && !oldAttrValue.equals(attrValue)) { err.jspError(n, "jsp.error.tag.conflict.attr", attr, oldAttrValue, attrValue); } result = attrValue; } return result; }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
Override public void visit(Node.AttributeDirective n) throws JasperException { JspUtil.checkAttributes("Attribute directive", n, attributeDirectiveAttrs, err); // JSP 2.1 Table JSP.8-3 // handle deferredValue and deferredValueType boolean deferredValue = false; boolean deferredValueSpecified = false; String deferredValueString = n.getAttributeValue("deferredValue"); if (deferredValueString != null) { deferredValueSpecified = true; deferredValue = JspUtil.booleanValue(deferredValueString); } String deferredValueType = n.getAttributeValue("deferredValueType"); if (deferredValueType != null) { if (deferredValueSpecified && !deferredValue) { err.jspError(n, "jsp.error.deferredvaluetypewithoutdeferredvalue"); } else { deferredValue = true; } } else if (deferredValue) { deferredValueType = "java.lang.Object"; } else { deferredValueType = "java.lang.String"; } // JSP 2.1 Table JSP.8-3 // handle deferredMethod and deferredMethodSignature boolean deferredMethod = false; boolean deferredMethodSpecified = false; String deferredMethodString = n.getAttributeValue("deferredMethod"); if (deferredMethodString != null) { deferredMethodSpecified = true; deferredMethod = JspUtil.booleanValue(deferredMethodString); } String deferredMethodSignature = n .getAttributeValue("deferredMethodSignature"); if (deferredMethodSignature != null) { if (deferredMethodSpecified && !deferredMethod) { err.jspError(n, "jsp.error.deferredmethodsignaturewithoutdeferredmethod"); } else { deferredMethod = true; } } else if (deferredMethod) { deferredMethodSignature = "void methodname()"; } if (deferredMethod && deferredValue) { err.jspError(n, "jsp.error.deferredmethodandvalue"); } String attrName = n.getAttributeValue("name"); boolean required = JspUtil.booleanValue(n .getAttributeValue("required")); boolean rtexprvalue = true; String rtexprvalueString = n.getAttributeValue("rtexprvalue"); if (rtexprvalueString != null) { rtexprvalue = JspUtil.booleanValue(rtexprvalueString); } boolean fragment = JspUtil.booleanValue(n .getAttributeValue("fragment")); String type = n.getAttributeValue("type"); if (fragment) { // type is fixed to "JspFragment" and a translation error // must occur if specified. if (type != null) { err.jspError(n, "jsp.error.fragmentwithtype"); } // rtexprvalue is fixed to "true" and a translation error // must occur if specified. rtexprvalue = true; if (rtexprvalueString != null) { err.jspError(n, "jsp.error.frgmentwithrtexprvalue"); } } else { if (type == null) type = "java.lang.String"; if (deferredValue) { type = ValueExpression.class.getName(); } else if (deferredMethod) { type = MethodExpression.class.getName(); } } if (("2.0".equals(tagLibInfo.getRequiredVersion()) || ("1.2".equals(tagLibInfo.getRequiredVersion()))) && (deferredMethodSpecified || deferredMethod || deferredValueSpecified || deferredValue)) { err.jspError("jsp.error.invalid.version", path); } TagAttributeInfo tagAttributeInfo = new TagAttributeInfo(attrName, required, type, rtexprvalue, fragment, null, deferredValue, deferredMethod, deferredValueType, deferredMethodSignature); attributeVector.addElement(tagAttributeInfo); checkUniqueName(attrName, ATTR_NAME, n, tagAttributeInfo); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
Override public void visit(Node.VariableDirective n) throws JasperException { JspUtil.checkAttributes("Variable directive", n, variableDirectiveAttrs, err); String nameGiven = n.getAttributeValue("name-given"); String nameFromAttribute = n .getAttributeValue("name-from-attribute"); if (nameGiven == null && nameFromAttribute == null) { err.jspError("jsp.error.variable.either.name"); } if (nameGiven != null && nameFromAttribute != null) { err.jspError("jsp.error.variable.both.name"); } String alias = n.getAttributeValue("alias"); if (nameFromAttribute != null && alias == null || nameFromAttribute == null && alias != null) { err.jspError("jsp.error.variable.alias"); } String className = n.getAttributeValue("variable-class"); if (className == null) className = "java.lang.String"; String declareStr = n.getAttributeValue("declare"); boolean declare = true; if (declareStr != null) declare = JspUtil.booleanValue(declareStr); int scope = VariableInfo.NESTED; String scopeStr = n.getAttributeValue("scope"); if (scopeStr != null) { if ("NESTED".equals(scopeStr)) { // Already the default } else if ("AT_BEGIN".equals(scopeStr)) { scope = VariableInfo.AT_BEGIN; } else if ("AT_END".equals(scopeStr)) { scope = VariableInfo.AT_END; } } if (nameFromAttribute != null) { /* * An alias has been specified. We use 'nameGiven' to hold the * value of the alias, and 'nameFromAttribute' to hold the name * of the attribute whose value (at invocation-time) denotes the * name of the variable that is being aliased */ nameGiven = alias; checkUniqueName(nameFromAttribute, VAR_NAME_FROM, n); checkUniqueName(alias, VAR_ALIAS, n); } else { // name-given specified checkUniqueName(nameGiven, VAR_NAME_GIVEN, n); } variableVector.addElement(new TagVariableInfo(nameGiven, nameFromAttribute, className, declare, scope)); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
public TagInfo getTagInfo() throws JasperException { if (name == null) { // XXX Get it from tag file name } if (bodycontent == null) { bodycontent = TagInfo.BODY_CONTENT_SCRIPTLESS; } String tagClassName = JspUtil.getTagHandlerClassName( path, tagLibInfo.getReliableURN(), err); TagVariableInfo[] tagVariableInfos = new TagVariableInfo[variableVector .size()]; variableVector.copyInto(tagVariableInfos); TagAttributeInfo[] tagAttributeInfo = new TagAttributeInfo[attributeVector .size()]; attributeVector.copyInto(tagAttributeInfo); return new JasperTagInfo(name, tagClassName, bodycontent, description, tagLibInfo, tei, tagAttributeInfo, displayName, smallIcon, largeIcon, tagVariableInfos, dynamicAttrsMapName); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
private void checkUniqueName(String name, String type, Node n) throws JasperException { checkUniqueName(name, type, n, null); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
private void checkUniqueName(String name, String type, Node n, TagAttributeInfo attr) throws JasperException { HashMap<String, NameEntry> table = (type == VAR_NAME_FROM) ? nameFromTable : nameTable; NameEntry nameEntry = table.get(name); if (nameEntry != null) { if (!TAG_DYNAMIC.equals(type) || !TAG_DYNAMIC.equals(nameEntry.getType())) { int line = nameEntry.getNode().getStart().getLineNumber(); err.jspError(n, "jsp.error.tagfile.nameNotUnique", type, nameEntry.getType(), Integer.toString(line)); } } else { table.put(name, new NameEntry(type, n, attr)); } }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
void postCheck() throws JasperException { // Check that var.name-from-attributes has valid values. Iterator<String> iter = nameFromTable.keySet().iterator(); while (iter.hasNext()) { String nameFrom = iter.next(); NameEntry nameEntry = nameTable.get(nameFrom); NameEntry nameFromEntry = nameFromTable.get(nameFrom); Node nameFromNode = nameFromEntry.getNode(); if (nameEntry == null) { err.jspError(nameFromNode, "jsp.error.tagfile.nameFrom.noAttribute", nameFrom); } else { Node node = nameEntry.getNode(); TagAttributeInfo tagAttr = nameEntry.getTagAttributeInfo(); if (!"java.lang.String".equals(tagAttr.getTypeName()) || !tagAttr.isRequired() || tagAttr.canBeRequestTime()) { err.jspError(nameFromNode, "jsp.error.tagfile.nameFrom.badAttribute", nameFrom, Integer.toString(node.getStart() .getLineNumber())); } } } }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
public static TagInfo parseTagFileDirectives(ParserController pc, String name, String path, JarResource jarResource, TagLibraryInfo tagLibInfo) throws JasperException { ErrorDispatcher err = pc.getCompiler().getErrorDispatcher(); Node.Nodes page = null; try { page = pc.parseTagFileDirectives(path, jarResource); } catch (FileNotFoundException e) { err.jspError("jsp.error.file.not.found", path); } catch (IOException e) { err.jspError("jsp.error.file.not.found", path); } TagFileDirectiveVisitor tagFileVisitor = new TagFileDirectiveVisitor(pc .getCompiler(), tagLibInfo, name, path); page.visit(tagFileVisitor); tagFileVisitor.postCheck(); return tagFileVisitor.getTagInfo(); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
private Class<?> loadTagFile(Compiler compiler, String tagFilePath, TagInfo tagInfo, PageInfo parentPageInfo) throws JasperException { JarResource tagJarResouce = null; if (tagFilePath.startsWith("/META-INF/")) { tagJarResouce = compiler.getCompilationContext().getTldLocation( tagInfo.getTagLibrary().getURI()).getJarResource(); } String wrapperUri; if (tagJarResouce == null) { wrapperUri = tagFilePath; } else { wrapperUri = tagJarResouce.getEntry(tagFilePath).toString(); } JspCompilationContext ctxt = compiler.getCompilationContext(); JspRuntimeContext rctxt = ctxt.getRuntimeContext(); JspServletWrapper wrapper = rctxt.getWrapper(wrapperUri); synchronized (rctxt) { if (wrapper == null) { wrapper = new JspServletWrapper(ctxt.getServletContext(), ctxt .getOptions(), tagFilePath, tagInfo, ctxt .getRuntimeContext(), tagJarResouce); rctxt.addWrapper(wrapperUri, wrapper); // Use same classloader and classpath for compiling tag files wrapper.getJspEngineContext().setClassLoader( ctxt.getClassLoader()); wrapper.getJspEngineContext().setClassPath(ctxt.getClassPath()); } else { // Make sure that JspCompilationContext gets the latest TagInfo // for the tag file. TagInfo instance was created the last // time the tag file was scanned for directives, and the tag // file may have been modified since then. wrapper.getJspEngineContext().setTagInfo(tagInfo); } Class<?> tagClazz; int tripCount = wrapper.incTripCount(); try { if (tripCount > 0) { // When tripCount is greater than zero, a circular // dependency exists. The circularly dependent tag // file is compiled in prototype mode, to avoid infinite // recursion. JspServletWrapper tempWrapper = new JspServletWrapper(ctxt .getServletContext(), ctxt.getOptions(), tagFilePath, tagInfo, ctxt.getRuntimeContext(), ctxt.getTagFileJarResource(tagFilePath)); // Use same classloader and classpath for compiling tag files tempWrapper.getJspEngineContext().setClassLoader( ctxt.getClassLoader()); tempWrapper.getJspEngineContext().setClassPath(ctxt.getClassPath()); tagClazz = tempWrapper.loadTagFilePrototype(); tempVector.add(tempWrapper.getJspEngineContext() .getCompiler()); } else { tagClazz = wrapper.loadTagFile(); } } finally { wrapper.decTripCount(); } // Add the dependents for this tag file to its parent's // Dependent list. The only reliable dependency information // can only be obtained from the tag instance. try { Object tagIns = tagClazz.newInstance(); if (tagIns instanceof JspSourceDependent) { Iterator<Entry<String,Long>> iter = ((JspSourceDependent) tagIns).getDependants().entrySet().iterator(); while (iter.hasNext()) { Entry<String,Long> entry = iter.next(); parentPageInfo.addDependant(entry.getKey(), entry.getValue()); } } } catch (Exception e) { // ignore errors } return tagClazz; } }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
Override public void visit(Node.CustomTag n) throws JasperException { TagFileInfo tagFileInfo = n.getTagFileInfo(); if (tagFileInfo != null) { String tagFilePath = tagFileInfo.getPath(); if (tagFilePath.startsWith("/META-INF/")) { // For tags in JARs, add the TLD and the tag as a dependency TldLocation location = compiler.getCompilationContext().getTldLocation( tagFileInfo.getTagInfo().getTagLibrary().getURI()); JarResource jarResource = location.getJarResource(); if (jarResource != null) { try { // Add TLD pageInfo.addDependant(jarResource.getEntry(location.getName()).toString(), Long.valueOf(jarResource.getJarFile().getEntry(location.getName()).getTime())); // Add Tag pageInfo.addDependant(jarResource.getEntry(tagFilePath.substring(1)).toString(), Long.valueOf(jarResource.getJarFile().getEntry(tagFilePath.substring(1)).getTime())); } catch (IOException ioe) { throw new JasperException(ioe); } } else { pageInfo.addDependant(tagFilePath, compiler.getCompilationContext().getLastModified( tagFilePath)); } } else { pageInfo.addDependant(tagFilePath, compiler.getCompilationContext().getLastModified( tagFilePath)); } Class<?> c = loadTagFile(compiler, tagFilePath, n.getTagInfo(), pageInfo); n.setTagHandlerClass(c); } visitBody(n); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
public void loadTagFiles(Compiler compiler, Node.Nodes page) throws JasperException { tempVector = new Vector<Compiler>(); page.visit(new TagFileLoaderVisitor(compiler)); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
public TldLocation getLocation(String uri) throws JasperException { if (!initialized) { init(); } return mappings.get(uri); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private synchronized void init() throws JasperException { if (initialized) return; try { tldScanWebXml(); tldScanResourcePaths(WEB_INF); JarScanner jarScanner = JarScannerFactory.getJarScanner(ctxt); if (jarScanner != null) { jarScanner.scan(ctxt, Thread.currentThread().getContextClassLoader(), new TldJarScannerCallback(), noTldJars); } initialized = true; } catch (Exception ex) { throw new JasperException(Localizer.getMessage( "jsp.error.internal.tldinit", ex.getMessage()), ex); } }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
public static void map(Node.Nodes page) throws JasperException { ELFunctionMapper map = new ELFunctionMapper(); map.ds = new StringBuilder(); map.ss = new StringBuilder(); page.visit(map.new ELFunctionVisitor()); // Append the declarations to the root node String ds = map.ds.toString(); if (ds.length() > 0) { Node root = page.getRoot(); new Node.Declaration(map.ss.toString(), null, root); new Node.Declaration("static {\n" + ds + "}\n", null, root); } }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.ParamAction n) throws JasperException { doMap(n.getValue()); visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.IncludeAction n) throws JasperException { doMap(n.getPage()); visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.ForwardAction n) throws JasperException { doMap(n.getPage()); visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.SetProperty n) throws JasperException { doMap(n.getValue()); visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.UseBean n) throws JasperException { doMap(n.getBeanName()); visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.PlugIn n) throws JasperException { doMap(n.getHeight()); doMap(n.getWidth()); visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.JspElement n) throws JasperException { Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { doMap(attrs[i]); } doMap(n.getNameAttribute()); visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.UninterpretedTag n) throws JasperException { Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { doMap(attrs[i]); } visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.CustomTag n) throws JasperException { Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { doMap(attrs[i]); } visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.ELExpression n) throws JasperException { doMap(n.getEL()); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
private void doMap(Node.JspAttribute attr) throws JasperException { if (attr != null) { doMap(attr.getEL()); } }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
private void doMap(ELNode.Nodes el) throws JasperException { // Only care about functions in ELNode's class Fvisitor extends ELNode.Visitor { ArrayList<ELNode.Function> funcs = new ArrayList<ELNode.Function>(); HashMap<String, String> keyMap = new HashMap<String, String>(); @Override public void visit(ELNode.Function n) throws JasperException { String key = n.getPrefix() + ":" + n.getName(); if (! keyMap.containsKey(key)) { keyMap.put(key,""); funcs.add(n); } } } if (el == null) { return; } // First locate all unique functions in this EL Fvisitor fv = new Fvisitor(); el.visit(fv); ArrayList<ELNode.Function> functions = fv.funcs; if (functions.size() == 0) { return; } // Reuse a previous map if possible String decName = matchMap(functions); if (decName != null) { el.setMapName(decName); return; } // Generate declaration for the map statically decName = getMapName(); ss.append("private static org.apache.jasper.runtime.ProtectedFunctionMapper " + decName + ";\n"); ds.append(" " + decName + "= "); ds.append("org.apache.jasper.runtime.ProtectedFunctionMapper"); // Special case if there is only one function in the map String funcMethod = null; if (functions.size() == 1) { funcMethod = ".getMapForFunction"; } else { ds.append(".getInstance();\n"); funcMethod = " " + decName + ".mapFunction"; } // Setup arguments for either getMapForFunction or mapFunction for (int i = 0; i < functions.size(); i++) { ELNode.Function f = functions.get(i); FunctionInfo funcInfo = f.getFunctionInfo(); String key = f.getPrefix()+ ":" + f.getName(); ds.append(funcMethod + "(\"" + key + "\", " + getCanonicalName(funcInfo.getFunctionClass()) + ".class, " + '\"' + f.getMethodName() + "\", " + "new Class[] {"); String params[] = f.getParameters(); for (int k = 0; k < params.length; k++) { if (k != 0) { ds.append(", "); } int iArray = params[k].indexOf('['); if (iArray < 0) { ds.append(params[k] + ".class"); } else { String baseType = params[k].substring(0, iArray); ds.append("java.lang.reflect.Array.newInstance("); ds.append(baseType); ds.append(".class,"); // Count the number of array dimension int aCount = 0; for (int jj = iArray; jj < params[k].length(); jj++ ) { if (params[k].charAt(jj) == '[') { aCount++; } } if (aCount == 1) { ds.append("0).getClass()"); } else { ds.append("new int[" + aCount + "]).getClass()"); } } } ds.append("});\n"); // Put the current name in the global function map gMap.put(f.getPrefix() + ':' + f.getName() + ':' + f.getUri(), decName); } el.setMapName(decName); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(ELNode.Function n) throws JasperException { String key = n.getPrefix() + ":" + n.getName(); if (! keyMap.containsKey(key)) { keyMap.put(key,""); funcs.add(n); } }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
private String getCanonicalName(String className) throws JasperException { Class<?> clazz; ClassLoader tccl; if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<ClassLoader> pa = new PrivilegedGetTccl(); tccl = AccessController.doPrivileged(pa); } else { tccl = Thread.currentThread().getContextClassLoader(); } try { clazz = Class.forName(className, false, tccl); } catch (ClassNotFoundException e) { throw new JasperException(e); } return clazz.getCanonicalName(); }
// in java/org/apache/jasper/compiler/JDTCompiler.java
Override protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception { long t1 = 0; if (log.isDebugEnabled()) { t1 = System.currentTimeMillis(); } final String sourceFile = ctxt.getServletJavaFileName(); final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath(); String packageName = ctxt.getServletPackageName(); final String targetClassName = ((packageName.length() != 0) ? (packageName + ".") : "") + ctxt.getServletClassName(); final ClassLoader classLoader = ctxt.getJspLoader(); String[] fileNames = new String[] {sourceFile}; String[] classNames = new String[] {targetClassName}; final ArrayList<JavacErrorDetail> problemList = new ArrayList<JavacErrorDetail>(); class CompilationUnit implements ICompilationUnit { private final String className; private final String sourceFile; CompilationUnit(String sourceFile, String className) { this.className = className; this.sourceFile = sourceFile; } @Override public char[] getFileName() { return sourceFile.toCharArray(); } @Override public char[] getContents() { char[] result = null; FileInputStream is = null; InputStreamReader isr = null; Reader reader = null; try { is = new FileInputStream(sourceFile); isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding()); reader = new BufferedReader(isr); char[] chars = new char[8192]; StringBuilder buf = new StringBuilder(); int count; while ((count = reader.read(chars, 0, chars.length)) > 0) { buf.append(chars, 0, count); } result = new char[buf.length()]; buf.getChars(0, result.length, result, 0); } catch (IOException e) { log.error("Compilation error", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) {/*Ignore*/} } if (isr != null) { try { isr.close(); } catch (IOException ioe) {/*Ignore*/} } if (is != null) { try { is.close(); } catch (IOException exc) {/*Ignore*/} } } return result; } @Override public char[] getMainTypeName() { int dot = className.lastIndexOf('.'); if (dot > 0) { return className.substring(dot + 1).toCharArray(); } return className.toCharArray(); } @Override public char[][] getPackageName() { StringTokenizer izer = new StringTokenizer(className, "."); char[][] result = new char[izer.countTokens()-1][]; for (int i = 0; i < result.length; i++) { String tok = izer.nextToken(); result[i] = tok.toCharArray(); } return result; } @SuppressWarnings("unused") // New method added to interface in // later JDT versions public boolean ignoreOptionalProblems() { return false; } }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void doVisit(Node n) throws JasperException { collectText(); }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void visit(Node.PageDirective n) throws JasperException { }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void visit(Node.TagDirective n) throws JasperException { }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void visit(Node.TaglibDirective n) throws JasperException { }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void visit(Node.AttributeDirective n) throws JasperException { }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void visit(Node.VariableDirective n) throws JasperException { }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void visitBody(Node n) throws JasperException { super.visitBody(n); collectText(); }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void visit(Node.TemplateText n) throws JasperException { if ((options.getTrimSpaces() || pageInfo.isTrimDirectiveWhitespaces()) && n.isAllSpace()) { n.setText(EMPTY_TEXT); return; } if (textNodeCount++ == 0) { firstTextNode = n; textBuffer = new StringBuilder(n.getText()); } else { // Append text to text buffer textBuffer.append(n.getText()); n.setText(EMPTY_TEXT); } }
// in java/org/apache/jasper/compiler/TextOptimizer.java
public static void concatenate(Compiler compiler, Node.Nodes page) throws JasperException { TextCatVisitor v = new TextCatVisitor(compiler); page.visit(v); // Cleanup, in case the page ends with a template text v.collectText(); }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setLanguage(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if (!"java".equalsIgnoreCase(value)) { if (pagedir) err.jspError(n, "jsp.error.page.language.nonjava"); else err.jspError(n, "jsp.error.tag.language.nonjava"); } language = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setBufferValue(String value, Node n, ErrorDispatcher err) throws JasperException { if ("none".equalsIgnoreCase(value)) buffer = 0; else { if (value == null || !value.endsWith("kb")) { if (n == null) { err.jspError("jsp.error.page.invalid.buffer"); } else { err.jspError(n, "jsp.error.page.invalid.buffer"); } } try { Integer k = new Integer(value.substring(0, value.length()-2)); buffer = k.intValue() * 1024; } catch (NumberFormatException e) { if (n == null) { err.jspError("jsp.error.page.invalid.buffer"); } else { err.jspError(n, "jsp.error.page.invalid.buffer"); } } } bufferValue = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setSession(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) isSession = true; else if ("false".equalsIgnoreCase(value)) isSession = false; else err.jspError(n, "jsp.error.page.invalid.session"); session = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setAutoFlush(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) isAutoFlush = true; else if ("false".equalsIgnoreCase(value)) isAutoFlush = false; else err.jspError(n, "jsp.error.autoFlush.invalid"); autoFlush = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setIsThreadSafe(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) isThreadSafe = true; else if ("false".equalsIgnoreCase(value)) isThreadSafe = false; else err.jspError(n, "jsp.error.page.invalid.isthreadsafe"); isThreadSafeValue = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setIsErrorPage(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) isErrorPage = true; else if ("false".equalsIgnoreCase(value)) isErrorPage = false; else err.jspError(n, "jsp.error.page.invalid.iserrorpage"); isErrorPageValue = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setIsELIgnored(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) isELIgnored = true; else if ("false".equalsIgnoreCase(value)) isELIgnored = false; else { if (pagedir) err.jspError(n, "jsp.error.page.invalid.iselignored"); else err.jspError(n, "jsp.error.tag.invalid.iselignored"); } isELIgnoredValue = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setDeferredSyntaxAllowedAsLiteral(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) deferredSyntaxAllowedAsLiteral = true; else if ("false".equalsIgnoreCase(value)) deferredSyntaxAllowedAsLiteral = false; else { if (pagedir) err.jspError(n, "jsp.error.page.invalid.deferredsyntaxallowedasliteral"); else err.jspError(n, "jsp.error.tag.invalid.deferredsyntaxallowedasliteral"); } deferredSyntaxAllowedAsLiteralValue = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setTrimDirectiveWhitespaces(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) trimDirectiveWhitespaces = true; else if ("false".equalsIgnoreCase(value)) trimDirectiveWhitespaces = false; else { if (pagedir) err.jspError(n, "jsp.error.page.invalid.trimdirectivewhitespaces"); else err.jspError(n, "jsp.error.tag.invalid.trimdirectivewhitespaces"); } trimDirectiveWhitespacesValue = value; }
// in java/org/apache/jasper/compiler/JspReader.java
boolean hasMoreInput() throws JasperException { if (current.cursor >= current.stream.length) { if (singleFile) return false; while (popFile()) { if (current.cursor < current.stream.length) return true; } return false; } return true; }
// in java/org/apache/jasper/compiler/JspReader.java
int nextChar() throws JasperException { if (!hasMoreInput()) return -1; int ch = current.stream[current.cursor]; current.cursor++; if (ch == '\n') { current.line++; current.col = 0; } else { current.col++; } return ch; }
// in java/org/apache/jasper/compiler/JspReader.java
String getText(Mark start, Mark stop) throws JasperException { Mark oldstart = mark(); reset(start); CharArrayWriter caw = new CharArrayWriter(); while (!stop.equals(mark())) caw.write(nextChar()); caw.close(); reset(oldstart); return caw.toString(); }
// in java/org/apache/jasper/compiler/JspReader.java
int peekChar() throws JasperException { if (!hasMoreInput()) return -1; return current.stream[current.cursor]; }
// in java/org/apache/jasper/compiler/JspReader.java
boolean matches(String string) throws JasperException { Mark mark = mark(); int ch = 0; int i = 0; do { ch = nextChar(); if (((char) ch) != string.charAt(i++)) { reset(mark); return false; } } while (i < string.length()); return true; }
// in java/org/apache/jasper/compiler/JspReader.java
boolean matchesETag(String tagName) throws JasperException { Mark mark = mark(); if (!matches("</" + tagName)) return false; skipSpaces(); if (nextChar() == '>') return true; reset(mark); return false; }
// in java/org/apache/jasper/compiler/JspReader.java
boolean matchesETagWithoutLessThan(String tagName) throws JasperException { Mark mark = mark(); if (!matches("/" + tagName)) return false; skipSpaces(); if (nextChar() == '>') return true; reset(mark); return false; }
// in java/org/apache/jasper/compiler/JspReader.java
boolean matchesOptionalSpacesFollowedBy( String s ) throws JasperException { Mark mark = mark(); skipSpaces(); boolean result = matches( s ); if( !result ) { reset( mark ); } return result; }
// in java/org/apache/jasper/compiler/JspReader.java
int skipSpaces() throws JasperException { int i = 0; while (hasMoreInput() && isSpace()) { i++; nextChar(); } return i; }
// in java/org/apache/jasper/compiler/JspReader.java
Mark skipUntil(String limit) throws JasperException { Mark ret = null; int limlen = limit.length(); int ch; skip: for (ret = mark(), ch = nextChar() ; ch != -1 ; ret = mark(), ch = nextChar()) { if (ch == limit.charAt(0)) { Mark restart = mark(); for (int i = 1 ; i < limlen ; i++) { if (peekChar() == limit.charAt(i)) nextChar(); else { reset(restart); continue skip; } } return ret; } } return null; }
// in java/org/apache/jasper/compiler/JspReader.java
Mark skipUntilIgnoreEsc(String limit) throws JasperException { Mark ret = null; int limlen = limit.length(); int ch; int prev = 'x'; // Doesn't matter skip: for (ret = mark(), ch = nextChar() ; ch != -1 ; ret = mark(), prev = ch, ch = nextChar()) { if (ch == '\\' && prev == '\\') { ch = 0; // Double \ is not an escape char anymore } else if (ch == limit.charAt(0) && prev != '\\') { for (int i = 1 ; i < limlen ; i++) { if (peekChar() == limit.charAt(i)) nextChar(); else continue skip; } return ret; } } return null; }
// in java/org/apache/jasper/compiler/JspReader.java
Mark skipUntilETag(String tag) throws JasperException { Mark ret = skipUntil("</" + tag); if (ret != null) { skipSpaces(); if (nextChar() != '>') ret = null; } return ret; }
// in java/org/apache/jasper/compiler/JspReader.java
final boolean isSpace() throws JasperException { // Note: If this logic changes, also update Node.TemplateText.rtrim() return peekChar() <= ' '; }
// in java/org/apache/jasper/compiler/JspReader.java
String parseToken(boolean quoted) throws JasperException { StringBuilder StringBuilder = new StringBuilder(); skipSpaces(); StringBuilder.setLength(0); if (!hasMoreInput()) { return ""; } int ch = peekChar(); if (quoted) { if (ch == '"' || ch == '\'') { char endQuote = ch == '"' ? '"' : '\''; // Consume the open quote: ch = nextChar(); for (ch = nextChar(); ch != -1 && ch != endQuote; ch = nextChar()) { if (ch == '\\') ch = nextChar(); StringBuilder.append((char) ch); } // Check end of quote, skip closing quote: if (ch == -1) { err.jspError(mark(), "jsp.error.quotes.unterminated"); } } else { err.jspError(mark(), "jsp.error.attr.quoted"); } } else { if (!isDelimiter()) { // Read value until delimiter is found: do { ch = nextChar(); // Take care of the quoting here. if (ch == '\\') { if (peekChar() == '"' || peekChar() == '\'' || peekChar() == '>' || peekChar() == '%') ch = nextChar(); } StringBuilder.append((char) ch); } while (!isDelimiter()); } } return StringBuilder.toString(); }
// in java/org/apache/jasper/compiler/JspReader.java
private boolean isDelimiter() throws JasperException { if (! isSpace()) { int ch = peekChar(); // Look for a single-char work delimiter: if (ch == '=' || ch == '>' || ch == '"' || ch == '\'' || ch == '/') { return true; } // Look for an end-of-comment or end-of-tag: if (ch == '-') { Mark mark = mark(); if (((ch = nextChar()) == '>') || ((ch == '-') && (nextChar() == '>'))) { reset(mark); return true; } else { reset(mark); return false; } } return false; } else { return true; } }
// in java/org/apache/jasper/compiler/JspReader.java
private void pushFile(String file, String encoding, InputStreamReader reader) throws JasperException { // Register the file String longName = file; int fileid = registerSourceFile(longName); if (fileid == -1) { // Bugzilla 37407: http://issues.apache.org/bugzilla/show_bug.cgi?id=37407 if(reader != null) { try { reader.close(); } catch (Exception any) { if(log.isDebugEnabled()) { log.debug("Exception closing reader: ", any); } } } err.jspError("jsp.error.file.already.registered", file); } currFileId = fileid; try { CharArrayWriter caw = new CharArrayWriter(); char buf[] = new char[1024]; for (int i = 0 ; (i = reader.read(buf)) != -1 ;) caw.write(buf, 0, i); caw.close(); if (current == null) { current = new Mark(this, caw.toCharArray(), fileid, getFile(fileid), master, encoding); } else { current.pushStream(caw.toCharArray(), fileid, getFile(fileid), longName, encoding); } }
// in java/org/apache/jasper/compiler/JspReader.java
private boolean popFile() throws JasperException { // Is stack created ? (will happen if the Jsp file we're looking at is // missing. if (current == null || currFileId < 0) { return false; } // Restore parser state: String fName = getFile(currFileId); currFileId = unregisterSourceFile(fName); if (currFileId < -1) { err.jspError("jsp.error.file.not.registered", fName); } Mark previous = current.popStream(); if (previous != null) { master = current.baseDir; current = previous; return true; } // Note that although the current file is undefined here, "current" // is not set to null just for convenience, for it maybe used to // set the current (undefined) position. return false; }
// in java/org/apache/jasper/compiler/Generator.java
private void generateDeclarations(Node.Nodes page) throws JasperException { class DeclarationVisitor extends Node.Visitor { private boolean getServletInfoGenerated = false; /* * Generates getServletInfo() method that returns the value of the * page directive's 'info' attribute, if present. * * The Validator has already ensured that if the translation unit * contains more than one page directive with an 'info' attribute, * their values match. */ @Override public void visit(Node.PageDirective n) throws JasperException { if (getServletInfoGenerated) { return; } String info = n.getAttributeValue("info"); if (info == null) return; getServletInfoGenerated = true; out.printil("public java.lang.String getServletInfo() {"); out.pushIndent(); out.printin("return "); out.print(quote(info)); out.println(";"); out.popIndent(); out.printil("}"); out.println(); } @Override public void visit(Node.Declaration n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printMultiLn(n.getText()); out.println(); n.setEndJavaLine(out.getJavaLine()); } // Custom Tags may contain declarations from tag plugins. @Override public void visit(Node.CustomTag n) throws JasperException { if (n.useTagPlugin()) { if (n.getAtSTag() != null) { n.getAtSTag().visit(this); } visitBody(n); if (n.getAtETag() != null) { n.getAtETag().visit(this); } } else { visitBody(n); } } } out.println(); page.visit(new DeclarationVisitor()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.PageDirective n) throws JasperException { if (getServletInfoGenerated) { return; } String info = n.getAttributeValue("info"); if (info == null) return; getServletInfoGenerated = true; out.printil("public java.lang.String getServletInfo() {"); out.pushIndent(); out.printin("return "); out.print(quote(info)); out.println(";"); out.popIndent(); out.printil("}"); out.println(); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.Declaration n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printMultiLn(n.getText()); out.println(); n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.CustomTag n) throws JasperException { if (n.useTagPlugin()) { if (n.getAtSTag() != null) { n.getAtSTag().visit(this); } visitBody(n); if (n.getAtETag() != null) { n.getAtETag().visit(this); } } else { visitBody(n); } }
// in java/org/apache/jasper/compiler/Generator.java
private void compileTagHandlerPoolList(Node.Nodes page) throws JasperException { class TagHandlerPoolVisitor extends Node.Visitor { private final Vector<String> names; /* * Constructor * * @param v Vector of tag handler pool names to populate */ TagHandlerPoolVisitor(Vector<String> v) { names = v; } /* * Gets the name of the tag handler pool for the given custom tag * and adds it to the list of tag handler pool names unless it is * already contained in it. */ @Override public void visit(Node.CustomTag n) throws JasperException { if (!n.implementsSimpleTag()) { String name = createTagHandlerPoolName(n.getPrefix(), n .getLocalName(), n.getAttributes(), n.getNamedAttributeNodes(), n.hasEmptyBody()); n.setTagHandlerPoolName(name); if (!names.contains(name)) { names.add(name); } } visitBody(n); } /* * Creates the name of the tag handler pool whose tag handlers may * be (re)used to service this action. * * @return The name of the tag handler pool */ private String createTagHandlerPoolName(String prefix, String shortName, Attributes attrs, Node.Nodes namedAttrs, boolean hasEmptyBody) { StringBuilder poolName = new StringBuilder(64); poolName.append("_jspx_tagPool_").append(prefix).append('_') .append(shortName); if (attrs != null) { String[] attrNames = new String[attrs.getLength() + namedAttrs.size()]; for (int i = 0; i < attrNames.length; i++) { attrNames[i] = attrs.getQName(i); } for (int i = 0; i < namedAttrs.size(); i++) { attrNames[attrs.getLength() + i] = ((NamedAttribute) namedAttrs.getNode(i)).getQName(); } Arrays.sort(attrNames, Collections.reverseOrder()); if (attrNames.length > 0) { poolName.append('&'); } for (int i = 0; i < attrNames.length; i++) { poolName.append('_'); poolName.append(attrNames[i]); } } if (hasEmptyBody) { poolName.append("_nobody"); } return JspUtil.makeJavaIdentifier(poolName.toString()); } } page.visit(new TagHandlerPoolVisitor(tagHandlerPoolNames)); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.CustomTag n) throws JasperException { if (!n.implementsSimpleTag()) { String name = createTagHandlerPoolName(n.getPrefix(), n .getLocalName(), n.getAttributes(), n.getNamedAttributeNodes(), n.hasEmptyBody()); n.setTagHandlerPoolName(name); if (!names.contains(name)) { names.add(name); } } visitBody(n); }
// in java/org/apache/jasper/compiler/Generator.java
private void declareTemporaryScriptingVars(Node.Nodes page) throws JasperException { class ScriptingVarVisitor extends Node.Visitor { private final Vector<String> vars; ScriptingVarVisitor() { vars = new Vector<String>(); } @Override public void visit(Node.CustomTag n) throws JasperException { // XXX - Actually there is no need to declare those // "_jspx_" + varName + "_" + nestingLevel variables when we are // inside a JspFragment. if (n.getCustomNestingLevel() > 0) { TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { String varName = varInfos[i].getVarName(); String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); if (!vars.contains(tmpVarName)) { vars.add(tmpVarName); out.printin(varInfos[i].getClassName()); out.print(" "); out.print(tmpVarName); out.print(" = "); out.print(null); out.println(";"); } } } else { for (int i = 0; i < tagVarInfos.length; i++) { String varName = tagVarInfos[i].getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); if (!vars.contains(tmpVarName)) { vars.add(tmpVarName); out.printin(tagVarInfos[i].getClassName()); out.print(" "); out.print(tmpVarName); out.print(" = "); out.print(null); out.println(";"); } } } } visitBody(n); } } page.visit(new ScriptingVarVisitor()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.CustomTag n) throws JasperException { // XXX - Actually there is no need to declare those // "_jspx_" + varName + "_" + nestingLevel variables when we are // inside a JspFragment. if (n.getCustomNestingLevel() > 0) { TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { String varName = varInfos[i].getVarName(); String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); if (!vars.contains(tmpVarName)) { vars.add(tmpVarName); out.printin(varInfos[i].getClassName()); out.print(" "); out.print(tmpVarName); out.print(" = "); out.print(null); out.println(";"); } } } else { for (int i = 0; i < tagVarInfos.length; i++) { String varName = tagVarInfos[i].getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); if (!vars.contains(tmpVarName)) { vars.add(tmpVarName); out.printin(tagVarInfos[i].getClassName()); out.print(" "); out.print(tmpVarName); out.print(" = "); out.print(null); out.println(";"); } } } } visitBody(n); }
// in java/org/apache/jasper/compiler/Generator.java
private void generatePreamble(Node.Nodes page) throws JasperException { String servletPackageName = ctxt.getServletPackageName(); String servletClassName = ctxt.getServletClassName(); String serviceMethodName = Constants.SERVICE_METHOD_NAME; // First the package name: genPreamblePackage(servletPackageName); // Generate imports genPreambleImports(); // Generate class declaration out.printin("public final class "); out.print(servletClassName); out.print(" extends "); out.println(pageInfo.getExtends()); out.printin(" implements org.apache.jasper.runtime.JspSourceDependent"); if (!pageInfo.isThreadSafe()) { out.println(","); out.printin(" javax.servlet.SingleThreadModel"); } out.println(" {"); out.pushIndent(); // Class body begins here generateDeclarations(page); // Static initializations here genPreambleStaticInitializers(); // Class variable declarations genPreambleClassVariableDeclarations(); // Methods here genPreambleMethods(); // Now the service method out.printin("public void "); out.print(serviceMethodName); out.println("(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)"); out.println(" throws java.io.IOException, javax.servlet.ServletException {"); out.pushIndent(); out.println(); // Local variable declarations out.printil("final javax.servlet.jsp.PageContext pageContext;"); if (pageInfo.isSession()) out.printil("javax.servlet.http.HttpSession session = null;"); if (pageInfo.isErrorPage()) { out.printil("java.lang.Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request);"); out.printil("if (exception != null) {"); out.pushIndent(); out.printil("response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);"); out.popIndent(); out.printil("}"); } out.printil("final javax.servlet.ServletContext application;"); out.printil("final javax.servlet.ServletConfig config;"); out.printil("javax.servlet.jsp.JspWriter out = null;"); out.printil("final java.lang.Object page = this;"); out.printil("javax.servlet.jsp.JspWriter _jspx_out = null;"); out.printil("javax.servlet.jsp.PageContext _jspx_page_context = null;"); out.println(); declareTemporaryScriptingVars(page); out.println(); out.printil("try {"); out.pushIndent(); out.printin("response.setContentType("); out.print(quote(pageInfo.getContentType())); out.println(");"); if (ctxt.getOptions().isXpoweredBy()) { out.printil("response.addHeader(\"X-Powered-By\", \"JSP/2.1\");"); } out.printil("pageContext = _jspxFactory.getPageContext(this, request, response,"); out.printin("\t\t\t"); out.print(quote(pageInfo.getErrorPage())); out.print(", " + pageInfo.isSession()); out.print(", " + pageInfo.getBuffer()); out.print(", " + pageInfo.isAutoFlush()); out.println(");"); out.printil("_jspx_page_context = pageContext;"); out.printil("application = pageContext.getServletContext();"); out.printil("config = pageContext.getServletConfig();"); if (pageInfo.isSession()) out.printil("session = pageContext.getSession();"); out.printil("out = pageContext.getOut();"); out.printil("_jspx_out = out;"); out.println(); }
// in java/org/apache/jasper/compiler/Generator.java
private void printParams(Node n, String pageParam, boolean literal) throws JasperException { class ParamVisitor extends Node.Visitor { String separator; ParamVisitor(String separator) { this.separator = separator; } @Override public void visit(Node.ParamAction n) throws JasperException { out.print(" + "); out.print(separator); out.print(" + "); out.print("org.apache.jasper.runtime.JspRuntimeLibrary." + "URLEncode(" + quote(n.getTextAttribute("name")) + ", request.getCharacterEncoding())"); out.print("+ \"=\" + "); out.print(attributeValue(n.getValue(), true, String.class)); // The separator is '&' after the second use separator = "\"&\""; } } String sep; if (literal) { sep = pageParam.indexOf('?') > 0 ? "\"&\"" : "\"?\""; } else { sep = "((" + pageParam + ").indexOf('?')>0? '&': '?')"; } if (n.getBody() != null) { n.getBody().visit(new ParamVisitor(sep)); } }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.ParamAction n) throws JasperException { out.print(" + "); out.print(separator); out.print(" + "); out.print("org.apache.jasper.runtime.JspRuntimeLibrary." + "URLEncode(" + quote(n.getTextAttribute("name")) + ", request.getCharacterEncoding())"); out.print("+ \"=\" + "); out.print(attributeValue(n.getValue(), true, String.class)); // The separator is '&' after the second use separator = "\"&\""; }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.Expression n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printin("out.print("); out.printMultiLn(n.getText()); out.println(");"); n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.Scriptlet n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printMultiLn(n.getText()); out.println(); n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.ELExpression n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); if (!pageInfo.isELIgnored() && (n.getEL() != null)) { out.printil("out.write(" + JspUtil.interpreterCall(this.isTagFile, n.getType() + "{" + n.getText() + "}", String.class, n.getEL().getMapName(), false) + ");"); } else { out.printil("out.write(" + quote(n.getType() + "{" + n.getText() + "}") + ");"); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.IncludeAction n) throws JasperException { String flush = n.getTextAttribute("flush"); Node.JspAttribute page = n.getPage(); boolean isFlush = false; // default to false; if ("true".equals(flush)) isFlush = true; n.setBeginJavaLine(out.getJavaLine()); String pageParam; if (page.isNamedAttribute()) { // If the page for jsp:include was specified via // jsp:attribute, first generate code to evaluate // that body. pageParam = generateNamedAttributeValue(page .getNamedAttributeNode()); } else { pageParam = attributeValue(page, false, String.class); } // If any of the params have their values specified by // jsp:attribute, prepare those values first. Node jspBody = findJspBody(n); if (jspBody != null) { prepareParams(jspBody); } else { prepareParams(n); } out.printin("org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, " + pageParam); printParams(n, pageParam, page.isLiteral()); out.println(", out, " + isFlush + ");"); n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
private void prepareParams(Node parent) throws JasperException { if (parent == null) return; Node.Nodes subelements = parent.getBody(); if (subelements != null) { for (int i = 0; i < subelements.size(); i++) { Node n = subelements.getNode(i); if (n instanceof Node.ParamAction) { Node.Nodes paramSubElements = n.getBody(); for (int j = 0; (paramSubElements != null) && (j < paramSubElements.size()); j++) { Node m = paramSubElements.getNode(j); if (m instanceof Node.NamedAttribute) { generateNamedAttributeValue((Node.NamedAttribute) m); } } } } }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.ForwardAction n) throws JasperException { Node.JspAttribute page = n.getPage(); n.setBeginJavaLine(out.getJavaLine()); out.printil("if (true) {"); // So that javac won't complain about out.pushIndent(); // codes after "return" String pageParam; if (page.isNamedAttribute()) { // If the page for jsp:forward was specified via // jsp:attribute, first generate code to evaluate // that body. pageParam = generateNamedAttributeValue(page .getNamedAttributeNode()); } else { pageParam = attributeValue(page, false, String.class); } // If any of the params have their values specified by // jsp:attribute, prepare those values first. Node jspBody = findJspBody(n); if (jspBody != null) { prepareParams(jspBody); } else { prepareParams(n); } out.printin("_jspx_page_context.forward("); out.print(pageParam); printParams(n, pageParam, page.isLiteral()); out.println(");"); if (isTagFile || isFragment) { out.printil("throw new javax.servlet.jsp.SkipPageException();"); } else { out.printil((methodNesting > 0) ? "return true;" : "return;"); } out.popIndent(); out.printil("}"); n.setEndJavaLine(out.getJavaLine()); // XXX Not sure if we can eliminate dead codes after this. }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.GetProperty n) throws JasperException { String name = n.getTextAttribute("name"); String property = n.getTextAttribute("property"); n.setBeginJavaLine(out.getJavaLine()); if (beanInfo.checkVariable(name)) { // Bean is defined using useBean, introspect at compile time Class<?> bean = beanInfo.getBeanType(name); String beanName = bean.getCanonicalName(); java.lang.reflect.Method meth = JspRuntimeLibrary .getReadMethod(bean, property); String methodName = meth.getName(); out.printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString(" + "(((" + beanName + ")_jspx_page_context.findAttribute(" + "\"" + name + "\"))." + methodName + "())));"); } else if (!STRICT_GET_PROPERTY || varInfoNames.contains(name)) { // The object is a custom action with an associated // VariableInfo entry for this name. // Get the class name and then introspect at runtime. out.printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString" + "(org.apache.jasper.runtime.JspRuntimeLibrary.handleGetProperty" + "(_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\")));"); } else { StringBuilder msg = new StringBuilder(); msg.append("file:"); msg.append(n.getStart()); msg.append(" jsp:getProperty for bean with name '"); msg.append(name); msg.append( "'. Name was not previously introduced as per JSP.5.3"); throw new JasperException(msg.toString()); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.SetProperty n) throws JasperException { String name = n.getTextAttribute("name"); String property = n.getTextAttribute("property"); String param = n.getTextAttribute("param"); Node.JspAttribute value = n.getValue(); n.setBeginJavaLine(out.getJavaLine()); if ("*".equals(property)) { out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspect(" + "_jspx_page_context.findAttribute(" + "\"" + name + "\"), request);"); } else if (value == null) { if (param == null) param = property; // default to same as property out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", request.getParameter(\"" + param + "\"), " + "request, \"" + param + "\", false);"); } else if (value.isExpression()) { out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.handleSetProperty(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\","); out.print(attributeValue(value, false, null)); out.println(");"); } else if (value.isELInterpreterInput()) { // We've got to resolve the very call to the interpreter // at runtime since we don't know what type to expect // in the general case; we thus can't hard-wire the call // into the generated code. (XXX We could, however, // optimize the case where the bean is exposed with // <jsp:useBean>, much as the code here does for // getProperty.) // The following holds true for the arguments passed to // JspRuntimeLibrary.handleSetPropertyExpression(): // - 'pageContext' is a VariableResolver. // - 'this' (either the generated Servlet or the generated tag // handler for Tag files) is a FunctionMapper. out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.handleSetPropertyExpression(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", " + quote(value.getValue()) + ", " + "_jspx_page_context, " + value.getEL().getMapName() + ");"); } else if (value.isNamedAttribute()) { // If the value for setProperty was specified via // jsp:attribute, first generate code to evaluate // that body. String valueVarName = generateNamedAttributeValue(value .getNamedAttributeNode()); out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", " + valueVarName + ", null, null, false);"); } else { out.printin("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", "); out.print(attributeValue(value, false, null)); out.println(", null, null, false);"); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.UseBean n) throws JasperException { String name = n.getTextAttribute("id"); String scope = n.getTextAttribute("scope"); String klass = n.getTextAttribute("class"); String type = n.getTextAttribute("type"); Node.JspAttribute beanName = n.getBeanName(); // If "class" is specified, try an instantiation at compile time boolean generateNew = false; String canonicalName = null; // Canonical name for klass if (klass != null) { try { Class<?> bean = ctxt.getClassLoader().loadClass(klass); if (klass.indexOf('$') >= 0) { // Obtain the canonical type name canonicalName = bean.getCanonicalName(); } else { canonicalName = klass; } int modifiers = bean.getModifiers(); if (!Modifier.isPublic(modifiers) || Modifier.isInterface(modifiers) || Modifier.isAbstract(modifiers)) { throw new Exception("Invalid bean class modifier"); } // Check that there is a 0 arg constructor bean.getConstructor(new Class[] {}); // At compile time, we have determined that the bean class // exists, with a public zero constructor, new() can be // used for bean instantiation. generateNew = true; } catch (Exception e) { // Cannot instantiate the specified class, either a // compilation error or a runtime error will be raised, // depending on a compiler flag. if (ctxt.getOptions() .getErrorOnUseBeanInvalidClassAttribute()) { err.jspError(n, "jsp.error.invalid.bean", klass); } if (canonicalName == null) { // Doing our best here to get a canonical name // from the binary name, should work 99.99% of time. canonicalName = klass.replace('$', '.'); } } if (type == null) { // if type is unspecified, use "class" as type of bean type = canonicalName; } } // JSP.5.1, Sematics, para 1 - lock not required for request or // page scope String scopename = "javax.servlet.jsp.PageContext.PAGE_SCOPE"; // Default to page String lock = null; if ("request".equals(scope)) { scopename = "javax.servlet.jsp.PageContext.REQUEST_SCOPE"; } else if ("session".equals(scope)) { scopename = "javax.servlet.jsp.PageContext.SESSION_SCOPE"; lock = "session"; } else if ("application".equals(scope)) { scopename = "javax.servlet.jsp.PageContext.APPLICATION_SCOPE"; lock = "application"; } n.setBeginJavaLine(out.getJavaLine()); // Declare bean out.printin(type); out.print(' '); out.print(name); out.println(" = null;"); // Lock (if required) while getting or creating bean if (lock != null) { out.printin("synchronized ("); out.print(lock); out.println(") {"); out.pushIndent(); } // Locate bean from context out.printin(name); out.print(" = ("); out.print(type); out.print(") _jspx_page_context.getAttribute("); out.print(quote(name)); out.print(", "); out.print(scopename); out.println(");"); // Create bean /* * Check if bean is already there */ out.printin("if ("); out.print(name); out.println(" == null){"); out.pushIndent(); if (klass == null && beanName == null) { /* * If both class name and beanName is not specified, the bean * must be found locally, otherwise it's an error */ out.printin("throw new java.lang.InstantiationException(\"bean "); out.print(name); out.println(" not found within scope\");"); } else { /* * Instantiate the bean if it is not in the specified scope. */ if (!generateNew) { String binaryName; if (beanName != null) { if (beanName.isNamedAttribute()) { // If the value for beanName was specified via // jsp:attribute, first generate code to evaluate // that body. binaryName = generateNamedAttributeValue(beanName .getNamedAttributeNode()); } else { binaryName = attributeValue(beanName, false, String.class); } } else { // Implies klass is not null binaryName = quote(klass); } out.printil("try {"); out.pushIndent(); out.printin(name); out.print(" = ("); out.print(type); out.print(") java.beans.Beans.instantiate("); out.print("this.getClass().getClassLoader(), "); out.print(binaryName); out.println(");"); out.popIndent(); /* * Note: Beans.instantiate throws ClassNotFoundException if * the bean class is abstract. */ out.printil("} catch (java.lang.ClassNotFoundException exc) {"); out.pushIndent(); out.printil("throw new InstantiationException(exc.getMessage());"); out.popIndent(); out.printil("} catch (java.lang.Exception exc) {"); out.pushIndent(); out.printin("throw new javax.servlet.ServletException("); out.print("\"Cannot create bean of class \" + "); out.print(binaryName); out.println(", exc);"); out.popIndent(); out.printil("}"); // close of try } else { // Implies klass is not null // Generate codes to instantiate the bean class out.printin(name); out.print(" = new "); out.print(canonicalName); out.println("();"); } /* * Set attribute for bean in the specified scope */ out.printin("_jspx_page_context.setAttribute("); out.print(quote(name)); out.print(", "); out.print(name); out.print(", "); out.print(scopename); out.println(");"); // Only visit the body when bean is instantiated visitBody(n); } out.popIndent(); out.printil("}"); // End of lock block if (lock != null) { out.popIndent(); out.printil("}"); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.PlugIn n) throws JasperException { /** * A visitor to handle &lt;jsp:param&gt; in a plugin */ class ParamVisitor extends Node.Visitor { private final boolean ie; ParamVisitor(boolean ie) { this.ie = ie; } @Override public void visit(Node.ParamAction n) throws JasperException { String name = n.getTextAttribute("name"); if (name.equalsIgnoreCase("object")) name = "java_object"; else if (name.equalsIgnoreCase("type")) name = "java_type"; n.setBeginJavaLine(out.getJavaLine()); // XXX - Fixed a bug here - value used to be output // inline, which is only okay if value is not an EL // expression. Also, key/value pairs for the // embed tag were not being generated correctly. // Double check that this is now the correct behavior. if (ie) { // We want something of the form // out.println( "<param name=\"blah\" // value=\"" + ... + "\">" ); out.printil("out.write( \"<param name=\\\"" + escape(name) + "\\\" value=\\\"\" + " + attributeValue(n.getValue(), false, String.class) + " + \"\\\">\" );"); out.printil("out.write(\"\\n\");"); } else { // We want something of the form // out.print( " blah=\"" + ... + "\"" ); out.printil("out.write( \" " + escape(name) + "=\\\"\" + " + attributeValue(n.getValue(), false, String.class) + " + \"\\\"\" );"); } n.setEndJavaLine(out.getJavaLine()); } } String type = n.getTextAttribute("type"); String code = n.getTextAttribute("code"); String name = n.getTextAttribute("name"); Node.JspAttribute height = n.getHeight(); Node.JspAttribute width = n.getWidth(); String hspace = n.getTextAttribute("hspace"); String vspace = n.getTextAttribute("vspace"); String align = n.getTextAttribute("align"); String iepluginurl = n.getTextAttribute("iepluginurl"); String nspluginurl = n.getTextAttribute("nspluginurl"); String codebase = n.getTextAttribute("codebase"); String archive = n.getTextAttribute("archive"); String jreversion = n.getTextAttribute("jreversion"); String widthStr = null; if (width != null) { if (width.isNamedAttribute()) { widthStr = generateNamedAttributeValue(width .getNamedAttributeNode()); } else { widthStr = attributeValue(width, false, String.class); } } String heightStr = null; if (height != null) { if (height.isNamedAttribute()) { heightStr = generateNamedAttributeValue(height .getNamedAttributeNode()); } else { heightStr = attributeValue(height, false, String.class); } } if (iepluginurl == null) iepluginurl = Constants.IE_PLUGIN_URL; if (nspluginurl == null) nspluginurl = Constants.NS_PLUGIN_URL; n.setBeginJavaLine(out.getJavaLine()); // If any of the params have their values specified by // jsp:attribute, prepare those values first. // Look for a params node and prepare its param subelements: Node.JspBody jspBody = findJspBody(n); if (jspBody != null) { Node.Nodes subelements = jspBody.getBody(); if (subelements != null) { for (int i = 0; i < subelements.size(); i++) { Node m = subelements.getNode(i); if (m instanceof Node.ParamsAction) { prepareParams(m); break; } } } } // XXX - Fixed a bug here - width and height can be set // dynamically. Double-check if this generation is correct. // IE style plugin // <object ...> // First compose the runtime output string String s0 = "<object" + makeAttr("classid", ctxt.getOptions().getIeClassId()) + makeAttr("name", name); String s1 = ""; if (width != null) { s1 = " + \" width=\\\"\" + " + widthStr + " + \"\\\"\""; } String s2 = ""; if (height != null) { s2 = " + \" height=\\\"\" + " + heightStr + " + \"\\\"\""; } String s3 = makeAttr("hspace", hspace) + makeAttr("vspace", vspace) + makeAttr("align", align) + makeAttr("codebase", iepluginurl) + '>'; // Then print the output string to the java file out.printil("out.write(" + quote(s0) + s1 + s2 + " + " + quote(s3) + ");"); out.printil("out.write(\"\\n\");"); // <param > for java_code s0 = "<param name=\"java_code\"" + makeAttr("value", code) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); // <param > for java_codebase if (codebase != null) { s0 = "<param name=\"java_codebase\"" + makeAttr("value", codebase) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); } // <param > for java_archive if (archive != null) { s0 = "<param name=\"java_archive\"" + makeAttr("value", archive) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); } // <param > for type s0 = "<param name=\"type\"" + makeAttr("value", "application/x-java-" + type + ((jreversion == null) ? "" : ";version=" + jreversion)) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); /* * generate a <param> for each <jsp:param> in the plugin body */ if (n.getBody() != null) n.getBody().visit(new ParamVisitor(true)); /* * Netscape style plugin part */ out.printil("out.write(" + quote("<comment>") + ");"); out.printil("out.write(\"\\n\");"); s0 = "<EMBED" + makeAttr("type", "application/x-java-" + type + ((jreversion == null) ? "" : ";version=" + jreversion)) + makeAttr("name", name); // s1 and s2 are the same as before. s3 = makeAttr("hspace", hspace) + makeAttr("vspace", vspace) + makeAttr("align", align) + makeAttr("pluginspage", nspluginurl) + makeAttr("java_code", code) + makeAttr("java_codebase", codebase) + makeAttr("java_archive", archive); out.printil("out.write(" + quote(s0) + s1 + s2 + " + " + quote(s3) + ");"); /* * Generate a 'attr = "value"' for each <jsp:param> in plugin body */ if (n.getBody() != null) n.getBody().visit(new ParamVisitor(false)); out.printil("out.write(" + quote("/>") + ");"); out.printil("out.write(\"\\n\");"); out.printil("out.write(" + quote("<noembed>") + ");"); out.printil("out.write(\"\\n\");"); /* * Fallback */ if (n.getBody() != null) { visitBody(n); out.printil("out.write(\"\\n\");"); } out.printil("out.write(" + quote("</noembed>") + ");"); out.printil("out.write(\"\\n\");"); out.printil("out.write(" + quote("</comment>") + ");"); out.printil("out.write(\"\\n\");"); out.printil("out.write(" + quote("</object>") + ");"); out.printil("out.write(\"\\n\");"); n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.ParamAction n) throws JasperException { String name = n.getTextAttribute("name"); if (name.equalsIgnoreCase("object")) name = "java_object"; else if (name.equalsIgnoreCase("type")) name = "java_type"; n.setBeginJavaLine(out.getJavaLine()); // XXX - Fixed a bug here - value used to be output // inline, which is only okay if value is not an EL // expression. Also, key/value pairs for the // embed tag were not being generated correctly. // Double check that this is now the correct behavior. if (ie) { // We want something of the form // out.println( "<param name=\"blah\" // value=\"" + ... + "\">" ); out.printil("out.write( \"<param name=\\\"" + escape(name) + "\\\" value=\\\"\" + " + attributeValue(n.getValue(), false, String.class) + " + \"\\\">\" );"); out.printil("out.write(\"\\n\");"); } else { // We want something of the form // out.print( " blah=\"" + ... + "\"" ); out.printil("out.write( \" " + escape(name) + "=\\\"\" + " + attributeValue(n.getValue(), false, String.class) + " + \"\\\"\" );"); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.NamedAttribute n) throws JasperException { // Don't visit body of this tag - we already did earlier. }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.CustomTag n) throws JasperException { // Use plugin to generate more efficient code if there is one. if (n.useTagPlugin()) { generateTagPlugin(n); return; } TagHandlerInfo handlerInfo = getTagHandlerInfo(n); // Create variable names String baseVar = createTagVarName(n.getQName(), n.getPrefix(), n .getLocalName()); String tagEvalVar = "_jspx_eval_" + baseVar; String tagHandlerVar = "_jspx_th_" + baseVar; String tagPushBodyCountVar = "_jspx_push_body_count_" + baseVar; // If the tag contains no scripting element, generate its codes // to a method. ServletWriter outSave = null; Node.ChildInfo ci = n.getChildInfo(); if (ci.isScriptless() && !ci.hasScriptingVars()) { // The tag handler and its body code can reside in a separate // method if it is scriptless and does not have any scripting // variable defined. String tagMethod = "_jspx_meth_" + baseVar; // Generate a call to this method out.printin("if ("); out.print(tagMethod); out.print("("); if (parent != null) { out.print(parent); out.print(", "); } out.print("_jspx_page_context"); if (pushBodyCountVar != null) { out.print(", "); out.print(pushBodyCountVar); } out.println("))"); out.pushIndent(); out.printil((methodNesting > 0) ? "return true;" : "return;"); out.popIndent(); // Set up new buffer for the method outSave = out; /* * For fragments, their bodies will be generated in fragment * helper classes, and the Java line adjustments will be done * there, hence they are set to null here to avoid double * adjustments. */ GenBuffer genBuffer = new GenBuffer(n, n.implementsSimpleTag() ? null : n.getBody()); methodsBuffered.add(genBuffer); out = genBuffer.getOut(); methodNesting++; // Generate code for method declaration out.println(); out.pushIndent(); out.printin("private boolean "); out.print(tagMethod); out.print("("); if (parent != null) { out.print("javax.servlet.jsp.tagext.JspTag "); out.print(parent); out.print(", "); } out.print("javax.servlet.jsp.PageContext _jspx_page_context"); if (pushBodyCountVar != null) { out.print(", int[] "); out.print(pushBodyCountVar); } out.println(")"); out.printil(" throws java.lang.Throwable {"); out.pushIndent(); // Initialize local variables used in this method. if (!isTagFile) { out.printil("javax.servlet.jsp.PageContext pageContext = _jspx_page_context;"); } out.printil("javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();"); generateLocalVariables(out, n); } // Add the named objects to the list of 'introduced' names to enable // a later test as per JSP.5.3 VariableInfo[] infos = n.getVariableInfos(); if (infos != null && infos.length > 0) { for (int i = 0; i < infos.length; i++) { VariableInfo info = infos[i]; if (info != null && info.getVarName() != null) pageInfo.getVarInfoNames().add(info.getVarName()); } } TagVariableInfo[] tagInfos = n.getTagVariableInfos(); if (tagInfos != null && tagInfos.length > 0) { for (int i = 0; i < tagInfos.length; i++) { TagVariableInfo tagInfo = tagInfos[i]; if (tagInfo != null) { String name = tagInfo.getNameGiven(); if (name == null) { String nameFromAttribute = tagInfo.getNameFromAttribute(); name = n.getAttributeValue(nameFromAttribute); } pageInfo.getVarInfoNames().add(name); } } } if (n.implementsSimpleTag()) { generateCustomDoTag(n, handlerInfo, tagHandlerVar); } else { /* * Classic tag handler: Generate code for start element, body, * and end element */ generateCustomStart(n, handlerInfo, tagHandlerVar, tagEvalVar, tagPushBodyCountVar); // visit body String tmpParent = parent; parent = tagHandlerVar; boolean isSimpleTagParentSave = isSimpleTagParent; isSimpleTagParent = false; String tmpPushBodyCountVar = null; if (n.implementsTryCatchFinally()) { tmpPushBodyCountVar = pushBodyCountVar; pushBodyCountVar = tagPushBodyCountVar; } boolean tmpIsSimpleTagHandler = isSimpleTagHandler; isSimpleTagHandler = false; visitBody(n); parent = tmpParent; isSimpleTagParent = isSimpleTagParentSave; if (n.implementsTryCatchFinally()) { pushBodyCountVar = tmpPushBodyCountVar; } isSimpleTagHandler = tmpIsSimpleTagHandler; generateCustomEnd(n, tagHandlerVar, tagEvalVar, tagPushBodyCountVar); } if (ci.isScriptless() && !ci.hasScriptingVars()) { // Generate end of method if (methodNesting > 0) { out.printil("return false;"); } out.popIndent(); out.printil("}"); out.popIndent(); methodNesting--; // restore previous writer out = outSave; } }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.UninterpretedTag n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); /* * Write begin tag */ out.printin("out.write(\"<"); out.print(n.getQName()); Attributes attrs = n.getNonTaglibXmlnsAttributes(); if (attrs != null) { for (int i = 0; i < attrs.getLength(); i++) { out.print(" "); out.print(attrs.getQName(i)); out.print("="); out.print(DOUBLE_QUOTE); out.print(attrs.getValue(i).replace("\"", "&quot;")); out.print(DOUBLE_QUOTE); } } attrs = n.getAttributes(); if (attrs != null) { Node.JspAttribute[] jspAttrs = n.getJspAttributes(); for (int i = 0; i < attrs.getLength(); i++) { out.print(" "); out.print(attrs.getQName(i)); out.print("="); if (jspAttrs[i].isELInterpreterInput()) { out.print("\\\"\" + "); out.print(attributeValue(jspAttrs[i], false, String.class)); out.print(" + \"\\\""); } else { out.print(DOUBLE_QUOTE); out.print(attrs.getValue(i).replace("\"", "&quot;")); out.print(DOUBLE_QUOTE); } } } if (n.getBody() != null) { out.println(">\");"); // Visit tag body visitBody(n); /* * Write end tag */ out.printin("out.write(\"</"); out.print(n.getQName()); out.println(">\");"); } else { out.println("/>\");"); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.JspElement n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); // Compute attribute value string for XML-style and named // attributes Hashtable<String,String> map = new Hashtable<String,String>(); Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { String value = null; String nvp = null; if (attrs[i].isNamedAttribute()) { NamedAttribute attr = attrs[i].getNamedAttributeNode(); Node.JspAttribute omitAttr = attr.getOmit(); String omit; if (omitAttr == null) { omit = "false"; } else { omit = attributeValue(omitAttr, false, boolean.class); if ("true".equals(omit)) { continue; } } value = generateNamedAttributeValue( attrs[i].getNamedAttributeNode()); if ("false".equals(omit)) { nvp = " + \" " + attrs[i].getName() + "=\\\"\" + " + value + " + \"\\\"\""; } else { nvp = " + (java.lang.Boolean.valueOf(" + omit + ")?\"\":\" " + attrs[i].getName() + "=\\\"\" + " + value + " + \"\\\"\")"; } } else { value = attributeValue(attrs[i], false, Object.class); nvp = " + \" " + attrs[i].getName() + "=\\\"\" + " + value + " + \"\\\"\""; } map.put(attrs[i].getName(), nvp); } // Write begin tag, using XML-style 'name' attribute as the // element name String elemName = attributeValue(n.getNameAttribute(), false, String.class); out.printin("out.write(\"<\""); out.print(" + " + elemName); // Write remaining attributes Enumeration<String> enumeration = map.keys(); while (enumeration.hasMoreElements()) { String attrName = enumeration.nextElement(); out.print(map.get(attrName)); } // Does the <jsp:element> have nested tags other than // <jsp:attribute> boolean hasBody = false; Node.Nodes subelements = n.getBody(); if (subelements != null) { for (int i = 0; i < subelements.size(); i++) { Node subelem = subelements.getNode(i); if (!(subelem instanceof Node.NamedAttribute)) { hasBody = true; break; } } } if (hasBody) { out.println(" + \">\");"); // Smap should not include the body n.setEndJavaLine(out.getJavaLine()); // Visit tag body visitBody(n); // Write end tag out.printin("out.write(\"</\""); out.print(" + " + elemName); out.println(" + \">\");"); } else { out.println(" + \"/>\");"); n.setEndJavaLine(out.getJavaLine()); } }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.TemplateText n) throws JasperException { String text = n.getText(); int textSize = text.length(); if (textSize == 0) { return; } if (textSize <= 3) { // Special case small text strings n.setBeginJavaLine(out.getJavaLine()); int lineInc = 0; for (int i = 0; i < textSize; i++) { char ch = text.charAt(i); out.printil("out.write(" + quote(ch) + ");"); if (i > 0) { n.addSmap(lineInc); } if (ch == '\n') { lineInc++; } } n.setEndJavaLine(out.getJavaLine()); return; } if (ctxt.getOptions().genStringAsCharArray()) { // Generate Strings as char arrays, for performance ServletWriter caOut; if (charArrayBuffer == null) { charArrayBuffer = new GenBuffer(); caOut = charArrayBuffer.getOut(); caOut.pushIndent(); textMap = new HashMap<String,String>(); } else { caOut = charArrayBuffer.getOut(); } // UTF-8 is up to 4 bytes per character // String constants are limited to 64k bytes // Limit string constants here to 16k characters int textIndex = 0; int textLength = text.length(); while (textIndex < textLength) { int len = 0; if (textLength - textIndex > 16384) { len = 16384; } else { len = textLength - textIndex; } String output = text.substring(textIndex, textIndex + len); String charArrayName = textMap.get(output); if (charArrayName == null) { charArrayName = "_jspx_char_array_" + charArrayCount++; textMap.put(output, charArrayName); caOut.printin("static char[] "); caOut.print(charArrayName); caOut.print(" = "); caOut.print(quote(output)); caOut.println(".toCharArray();"); } n.setBeginJavaLine(out.getJavaLine()); out.printil("out.write(" + charArrayName + ");"); n.setEndJavaLine(out.getJavaLine()); textIndex = textIndex + len; } return; } n.setBeginJavaLine(out.getJavaLine()); out.printin(); StringBuilder sb = new StringBuilder("out.write(\""); int initLength = sb.length(); int count = JspUtil.CHUNKSIZE; int srcLine = 0; // relative to starting source line for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); --count; switch (ch) { case '"': sb.append('\\').append('\"'); break; case '\\': sb.append('\\').append('\\'); break; case '\r': sb.append('\\').append('r'); break; case '\n': sb.append('\\').append('n'); srcLine++; if (breakAtLF || count < 0) { // Generate an out.write() when see a '\n' in template sb.append("\");"); out.println(sb.toString()); if (i < text.length() - 1) { out.printin(); } sb.setLength(initLength); count = JspUtil.CHUNKSIZE; } // add a Smap for this line n.addSmap(srcLine); break; case '\t': // Not sure we need this sb.append('\\').append('t'); break; default: sb.append(ch); } } if (sb.length() > initLength) { sb.append("\");"); out.println(sb.toString()); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.JspBody n) throws JasperException { if (n.getBody() != null) { if (isSimpleTagHandler) { out.printin(simpleTagHandlerVar); out.print(".setJspBody("); generateJspFragment(n, simpleTagHandlerVar); out.println(");"); } else { visitBody(n); } } }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.InvokeAction n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); // Copy virtual page scope of tag file to page scope of invoking // page out.printil("((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke();"); String varReaderAttr = n.getTextAttribute("varReader"); String varAttr = n.getTextAttribute("var"); if (varReaderAttr != null || varAttr != null) { out.printil("_jspx_sout = new java.io.StringWriter();"); } else { out.printil("_jspx_sout = null;"); } // Invoke fragment, unless fragment is null out.printin("if ("); out.print(toGetterMethod(n.getTextAttribute("fragment"))); out.println(" != null) {"); out.pushIndent(); out.printin(toGetterMethod(n.getTextAttribute("fragment"))); out.println(".invoke(_jspx_sout);"); out.popIndent(); out.printil("}"); // Store varReader in appropriate scope if (varReaderAttr != null || varAttr != null) { String scopeName = n.getTextAttribute("scope"); out.printin("_jspx_page_context.setAttribute("); if (varReaderAttr != null) { out.print(quote(varReaderAttr)); out.print(", new java.io.StringReader(_jspx_sout.toString())"); } else { out.print(quote(varAttr)); out.print(", _jspx_sout.toString()"); } if (scopeName != null) { out.print(", "); out.print(getScopeConstant(scopeName)); } out.println(");"); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.DoBodyAction n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); // Copy virtual page scope of tag file to page scope of invoking // page out.printil("((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke();"); // Invoke body String varReaderAttr = n.getTextAttribute("varReader"); String varAttr = n.getTextAttribute("var"); if (varReaderAttr != null || varAttr != null) { out.printil("_jspx_sout = new java.io.StringWriter();"); } else { out.printil("_jspx_sout = null;"); } out.printil("if (getJspBody() != null)"); out.pushIndent(); out.printil("getJspBody().invoke(_jspx_sout);"); out.popIndent(); // Store varReader in appropriate scope if (varReaderAttr != null || varAttr != null) { String scopeName = n.getTextAttribute("scope"); out.printin("_jspx_page_context.setAttribute("); if (varReaderAttr != null) { out.print(quote(varReaderAttr)); out.print(", new java.io.StringReader(_jspx_sout.toString())"); } else { out.print(quote(varAttr)); out.print(", _jspx_sout.toString()"); } if (scopeName != null) { out.print(", "); out.print(getScopeConstant(scopeName)); } out.println(");"); } // Restore EL context out.printil("jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,getJspContext());"); n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.AttributeGenerator n) throws JasperException { Node.CustomTag tag = n.getTag(); Node.JspAttribute[] attrs = tag.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { if (attrs[i].getName().equals(n.getName())) { out.print(evaluateAttribute(getTagHandlerInfo(tag), attrs[i], tag, null)); break; } } }
// in java/org/apache/jasper/compiler/Generator.java
private TagHandlerInfo getTagHandlerInfo(Node.CustomTag n) throws JasperException { Hashtable<String,TagHandlerInfo> handlerInfosByShortName = handlerInfos.get(n.getPrefix()); if (handlerInfosByShortName == null) { handlerInfosByShortName = new Hashtable<String,TagHandlerInfo>(); handlerInfos.put(n.getPrefix(), handlerInfosByShortName); } TagHandlerInfo handlerInfo = handlerInfosByShortName.get(n.getLocalName()); if (handlerInfo == null) { handlerInfo = new TagHandlerInfo(n, n.getTagHandlerClass(), err); handlerInfosByShortName.put(n.getLocalName(), handlerInfo); } return handlerInfo; }
// in java/org/apache/jasper/compiler/Generator.java
private void generateTagPlugin(Node.CustomTag n) throws JasperException { if (n.getAtSTag() != null) { n.getAtSTag().visit(this); } visitBody(n); if (n.getAtETag() != null) { n.getAtETag().visit(this); } }
// in java/org/apache/jasper/compiler/Generator.java
private void generateCustomStart(Node.CustomTag n, TagHandlerInfo handlerInfo, String tagHandlerVar, String tagEvalVar, String tagPushBodyCountVar) throws JasperException { Class<?> tagHandlerClass = handlerInfo.getTagHandlerClass(); out.printin("// "); out.println(n.getQName()); n.setBeginJavaLine(out.getJavaLine()); // Declare AT_BEGIN scripting variables declareScriptingVars(n, VariableInfo.AT_BEGIN); saveScriptingVars(n, VariableInfo.AT_BEGIN); String tagHandlerClassName = tagHandlerClass.getCanonicalName(); if (isPoolingEnabled && !(n.implementsJspIdConsumer())) { out.printin(tagHandlerClassName); out.print(" "); out.print(tagHandlerVar); out.print(" = "); out.print("("); out.print(tagHandlerClassName); out.print(") "); out.print(n.getTagHandlerPoolName()); out.print(".get("); out.print(tagHandlerClassName); out.println(".class);"); } else { writeNewInstance(tagHandlerVar, tagHandlerClassName); } // includes setting the context generateSetters(n, tagHandlerVar, handlerInfo, false); // JspIdConsumer (after context has been set) if (n.implementsJspIdConsumer()) { out.printin(tagHandlerVar); out.print(".setJspId(\""); out.print(createJspId()); out.println("\");"); } if (n.implementsTryCatchFinally()) { out.printin("int[] "); out.print(tagPushBodyCountVar); out.println(" = new int[] { 0 };"); out.printil("try {"); out.pushIndent(); } out.printin("int "); out.print(tagEvalVar); out.print(" = "); out.print(tagHandlerVar); out.println(".doStartTag();"); if (!n.implementsBodyTag()) { // Synchronize AT_BEGIN scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); } if (!n.hasEmptyBody()) { out.printin("if ("); out.print(tagEvalVar); out.println(" != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {"); out.pushIndent(); // Declare NESTED scripting variables declareScriptingVars(n, VariableInfo.NESTED); saveScriptingVars(n, VariableInfo.NESTED); if (n.implementsBodyTag()) { out.printin("if ("); out.print(tagEvalVar); out.println(" != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {"); // Assume EVAL_BODY_BUFFERED out.pushIndent(); out.printil("out = _jspx_page_context.pushBody();"); if (n.implementsTryCatchFinally()) { out.printin(tagPushBodyCountVar); out.println("[0]++;"); } else if (pushBodyCountVar != null) { out.printin(pushBodyCountVar); out.println("[0]++;"); } out.printin(tagHandlerVar); out.println(".setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);"); out.printin(tagHandlerVar); out.println(".doInitBody();"); out.popIndent(); out.printil("}"); // Synchronize AT_BEGIN and NESTED scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); syncScriptingVars(n, VariableInfo.NESTED); } else { // Synchronize NESTED scripting variables syncScriptingVars(n, VariableInfo.NESTED); } if (n.implementsIterationTag()) { out.printil("do {"); out.pushIndent(); } } // Map the Java lines that handles start of custom tags to the // JSP line for this tag n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
private void generateCustomDoTag(Node.CustomTag n, TagHandlerInfo handlerInfo, String tagHandlerVar) throws JasperException { Class<?> tagHandlerClass = handlerInfo.getTagHandlerClass(); n.setBeginJavaLine(out.getJavaLine()); out.printin("// "); out.println(n.getQName()); // Declare AT_BEGIN scripting variables declareScriptingVars(n, VariableInfo.AT_BEGIN); saveScriptingVars(n, VariableInfo.AT_BEGIN); String tagHandlerClassName = tagHandlerClass.getCanonicalName(); writeNewInstance(tagHandlerVar, tagHandlerClassName); generateSetters(n, tagHandlerVar, handlerInfo, true); // JspIdConsumer (after context has been set) if (n.implementsJspIdConsumer()) { out.printin(tagHandlerVar); out.print(".setJspId(\""); out.print(createJspId()); out.println("\");"); } // Set the body if (findJspBody(n) == null) { /* * Encapsulate body of custom tag invocation in JspFragment and * pass it to tag handler's setJspBody(), unless tag body is * empty */ if (!n.hasEmptyBody()) { out.printin(tagHandlerVar); out.print(".setJspBody("); generateJspFragment(n, tagHandlerVar); out.println(");"); } } else { /* * Body of tag is the body of the <jsp:body> element. The visit * method for that element is going to encapsulate that * element's body in a JspFragment and pass it to the tag * handler's setJspBody() */ String tmpTagHandlerVar = simpleTagHandlerVar; simpleTagHandlerVar = tagHandlerVar; boolean tmpIsSimpleTagHandler = isSimpleTagHandler; isSimpleTagHandler = true; visitBody(n); simpleTagHandlerVar = tmpTagHandlerVar; isSimpleTagHandler = tmpIsSimpleTagHandler; } out.printin(tagHandlerVar); out.println(".doTag();"); restoreScriptingVars(n, VariableInfo.AT_BEGIN); // Synchronize AT_BEGIN scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); // Declare and synchronize AT_END scripting variables declareScriptingVars(n, VariableInfo.AT_END); syncScriptingVars(n, VariableInfo.AT_END); // Resource injection writeDestroyInstance(tagHandlerVar); n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
private void generateSetters(Node.CustomTag n, String tagHandlerVar, TagHandlerInfo handlerInfo, boolean simpleTag) throws JasperException { // Set context if (simpleTag) { // Generate alias map String aliasMapVar = null; if (n.isTagFile()) { aliasMapVar = generateAliasMap(n, tagHandlerVar); } out.printin(tagHandlerVar); if (aliasMapVar == null) { out.println(".setJspContext(_jspx_page_context);"); } else { out.print(".setJspContext(_jspx_page_context, "); out.print(aliasMapVar); out.println(");"); } } else { out.printin(tagHandlerVar); out.println(".setPageContext(_jspx_page_context);"); } // Set parent if (isTagFile && parent == null) { out.printin(tagHandlerVar); out.print(".setParent("); out.print("new javax.servlet.jsp.tagext.TagAdapter("); out.print("(javax.servlet.jsp.tagext.SimpleTag) this ));"); } else if (!simpleTag) { out.printin(tagHandlerVar); out.print(".setParent("); if (parent != null) { if (isSimpleTagParent) { out.print("new javax.servlet.jsp.tagext.TagAdapter("); out.print("(javax.servlet.jsp.tagext.SimpleTag) "); out.print(parent); out.println("));"); } else { out.print("(javax.servlet.jsp.tagext.Tag) "); out.print(parent); out.println(");"); } } else { out.println("null);"); } } else { // The setParent() method need not be called if the value being // passed is null, since SimpleTag instances are not reused if (parent != null) { out.printin(tagHandlerVar); out.print(".setParent("); out.print(parent); out.println(");"); } } // need to handle deferred values and methods Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { String attrValue = evaluateAttribute(handlerInfo, attrs[i], n, tagHandlerVar); Mark m = n.getStart(); out.printil("// "+m.getFile()+"("+m.getLineNumber()+","+m.getColumnNumber()+") "+ attrs[i].getTagAttributeInfo()); if (attrs[i].isDynamic()) { out.printin(tagHandlerVar); out.print("."); out.print("setDynamicAttribute("); String uri = attrs[i].getURI(); if ("".equals(uri) || (uri == null)) { out.print("null"); } else { out.print("\"" + attrs[i].getURI() + "\""); } out.print(", \""); out.print(attrs[i].getLocalName()); out.print("\", "); out.print(attrValue); out.println(");"); } else { out.printin(tagHandlerVar); out.print("."); out.print(handlerInfo.getSetterMethod( attrs[i].getLocalName()).getName()); out.print("("); out.print(attrValue); out.println(");"); } } }
// in java/org/apache/jasper/compiler/Generator.java
private void generateJspFragment(Node n, String tagHandlerVar) throws JasperException { // XXX - A possible optimization here would be to check to see // if the only child of the parent node is TemplateText. If so, // we know there won't be any parameters, etc, so we can // generate a low-overhead JspFragment that just echoes its // body. The implementation of this fragment can come from // the org.apache.jasper.runtime package as a support class. FragmentHelperClass.Fragment fragment = fragmentHelperClass .openFragment(n, methodNesting); ServletWriter outSave = out; out = fragment.getGenBuffer().getOut(); String tmpParent = parent; parent = "_jspx_parent"; boolean isSimpleTagParentSave = isSimpleTagParent; isSimpleTagParent = true; boolean tmpIsFragment = isFragment; isFragment = true; String pushBodyCountVarSave = pushBodyCountVar; if (pushBodyCountVar != null) { // Use a fixed name for push body count, to simplify code gen pushBodyCountVar = "_jspx_push_body_count"; } visitBody(n); out = outSave; parent = tmpParent; isSimpleTagParent = isSimpleTagParentSave; isFragment = tmpIsFragment; pushBodyCountVar = pushBodyCountVarSave; fragmentHelperClass.closeFragment(fragment, methodNesting); // XXX - Need to change pageContext to jspContext if // we're not in a place where pageContext is defined (e.g. // in a fragment or in a tag file. out.print("new " + fragmentHelperClass.getClassName() + "( " + fragment.getId() + ", _jspx_page_context, " + tagHandlerVar + ", " + pushBodyCountVar + ")"); }
// in java/org/apache/jasper/compiler/Generator.java
public String generateNamedAttributeValue(Node.NamedAttribute n) throws JasperException { String varName = n.getTemporaryVariableName(); // If the only body element for this named attribute node is // template text, we need not generate an extra call to // pushBody and popBody. Maybe we can further optimize // here by getting rid of the temporary variable, but in // reality it looks like javac does this for us. Node.Nodes body = n.getBody(); if (body != null) { boolean templateTextOptimization = false; if (body.size() == 1) { Node bodyElement = body.getNode(0); if (bodyElement instanceof Node.TemplateText) { templateTextOptimization = true; out.printil("java.lang.String " + varName + " = " + quote(((Node.TemplateText) bodyElement) .getText()) + ";"); } } // XXX - Another possible optimization would be for // lone EL expressions (no need to pushBody here either). if (!templateTextOptimization) { out.printil("out = _jspx_page_context.pushBody();"); visitBody(n); out.printil("java.lang.String " + varName + " = " + "((javax.servlet.jsp.tagext.BodyContent)" + "out).getString();"); out.printil("out = _jspx_page_context.popBody();"); } } else { // Empty body must be treated as "" out.printil("java.lang.String " + varName + " = \"\";"); } return varName; }
// in java/org/apache/jasper/compiler/Generator.java
public String generateNamedAttributeJspFragment(Node.NamedAttribute n, String tagHandlerVar) throws JasperException { String varName = n.getTemporaryVariableName(); out.printin("javax.servlet.jsp.tagext.JspFragment " + varName + " = "); generateJspFragment(n, tagHandlerVar); out.println(";"); return varName; }
// in java/org/apache/jasper/compiler/Generator.java
private static void generateLocalVariables(ServletWriter out, Node n) throws JasperException { Node.ChildInfo ci; if (n instanceof Node.CustomTag) { ci = ((Node.CustomTag) n).getChildInfo(); } else if (n instanceof Node.JspBody) { ci = ((Node.JspBody) n).getChildInfo(); } else if (n instanceof Node.NamedAttribute) { ci = ((Node.NamedAttribute) n).getChildInfo(); } else { // Cannot access err since this method is static, but at // least flag an error. throw new JasperException("Unexpected Node Type"); // err.getString( // "jsp.error.internal.unexpected_node_type" ) ); } if (ci.hasUseBean()) { out.printil("javax.servlet.http.HttpSession session = _jspx_page_context.getSession();"); out.printil("javax.servlet.ServletContext application = _jspx_page_context.getServletContext();"); } if (ci.hasUseBean() || ci.hasIncludeAction() || ci.hasSetProperty() || ci.hasParamAction()) { out.printil("javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest)_jspx_page_context.getRequest();"); } if (ci.hasIncludeAction()) { out.printil("javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse)_jspx_page_context.getResponse();"); } }
// in java/org/apache/jasper/compiler/Generator.java
public static void generate(ServletWriter out, Compiler compiler, Node.Nodes page) throws JasperException { Generator gen = new Generator(out, compiler); if (gen.isPoolingEnabled) { gen.compileTagHandlerPoolList(page); } gen.generateCommentHeader(); if (gen.ctxt.isTagFile()) { JasperTagInfo tagInfo = (JasperTagInfo) gen.ctxt.getTagInfo(); gen.generateTagHandlerPreamble(tagInfo, page); if (gen.ctxt.isPrototypeMode()) { return; } gen.generateXmlProlog(page); gen.fragmentHelperClass.generatePreamble(); page.visit(gen.new GenerateVisitor(gen.ctxt.isTagFile(), out, gen.methodsBuffered, gen.fragmentHelperClass)); gen.generateTagHandlerPostamble(tagInfo); } else { gen.generatePreamble(page); gen.generateXmlProlog(page); gen.fragmentHelperClass.generatePreamble(); page.visit(gen.new GenerateVisitor(gen.ctxt.isTagFile(), out, gen.methodsBuffered, gen.fragmentHelperClass)); gen.generatePostamble(); } }
// in java/org/apache/jasper/compiler/Generator.java
private void generateTagHandlerPreamble(JasperTagInfo tagInfo, Node.Nodes tag) throws JasperException { // Generate package declaration String className = tagInfo.getTagClassName(); int lastIndex = className.lastIndexOf('.'); if (lastIndex != -1) { String pkgName = className.substring(0, lastIndex); genPreamblePackage(pkgName); className = className.substring(lastIndex + 1); } // Generate imports genPreambleImports(); // Generate class declaration out.printin("public final class "); out.println(className); out.printil(" extends javax.servlet.jsp.tagext.SimpleTagSupport"); out.printin(" implements org.apache.jasper.runtime.JspSourceDependent"); if (tagInfo.hasDynamicAttributes()) { out.println(","); out.printin(" javax.servlet.jsp.tagext.DynamicAttributes"); } out.println(" {"); out.println(); out.pushIndent(); /* * Class body begins here */ generateDeclarations(tag); // Static initializations here genPreambleStaticInitializers(); out.printil("private javax.servlet.jsp.JspContext jspContext;"); // Declare writer used for storing result of fragment/body invocation // if 'varReader' or 'var' attribute is specified out.printil("private java.io.Writer _jspx_sout;"); // Class variable declarations genPreambleClassVariableDeclarations(); generateSetJspContext(tagInfo); // Tag-handler specific declarations generateTagHandlerAttributes(tagInfo); if (tagInfo.hasDynamicAttributes()) generateSetDynamicAttribute(); // Methods here genPreambleMethods(); // Now the doTag() method out.printil("public void doTag() throws javax.servlet.jsp.JspException, java.io.IOException {"); if (ctxt.isPrototypeMode()) { out.printil("}"); out.popIndent(); out.printil("}"); return; } out.pushIndent(); /* * According to the spec, 'pageContext' must not be made available as an * implicit object in tag files. Declare _jspx_page_context, so we can * share the code generator with JSPs. */ out.printil("javax.servlet.jsp.PageContext _jspx_page_context = (javax.servlet.jsp.PageContext)jspContext;"); // Declare implicit objects. out.printil("javax.servlet.http.HttpServletRequest request = " + "(javax.servlet.http.HttpServletRequest) _jspx_page_context.getRequest();"); out.printil("javax.servlet.http.HttpServletResponse response = " + "(javax.servlet.http.HttpServletResponse) _jspx_page_context.getResponse();"); out.printil("javax.servlet.http.HttpSession session = _jspx_page_context.getSession();"); out.printil("javax.servlet.ServletContext application = _jspx_page_context.getServletContext();"); out.printil("javax.servlet.ServletConfig config = _jspx_page_context.getServletConfig();"); out.printil("javax.servlet.jsp.JspWriter out = jspContext.getOut();"); out.printil("_jspInit(config);"); // set current JspContext on ELContext out.printil("jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,jspContext);"); generatePageScopedVariables(tagInfo); declareTemporaryScriptingVars(tag); out.println(); out.printil("try {"); out.pushIndent(); }
// in java/org/apache/jasper/compiler/Generator.java
public void adjustJavaLines(final int offset) { if (node != null) { adjustJavaLine(node, offset); } if (body != null) { try { body.visit(new Node.Visitor() { @Override public void doVisit(Node n) { adjustJavaLine(n, offset); } @Override public void visit(Node.CustomTag n) throws JasperException { Node.Nodes b = n.getBody(); if (b != null && !b.isGeneratedInBuffer()) { // Don't adjust lines for the nested tags that // are also generated in buffers, because the // adjustments will be done elsewhere. b.visit(this); } } }); } catch (JasperException ex) { // Ignore } }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.CustomTag n) throws JasperException { Node.Nodes b = n.getBody(); if (b != null && !b.isGeneratedInBuffer()) { // Don't adjust lines for the nested tags that // are also generated in buffers, because the // adjustments will be done elsewhere. b.visit(this); } }
// in java/org/apache/jasper/compiler/Generator.java
public Fragment openFragment(Node parent, int methodNesting) throws JasperException { Fragment result = new Fragment(fragments.size(), parent); fragments.add(result); this.used = true; parent.setInnerClassName(className); ServletWriter out = result.getGenBuffer().getOut(); out.pushIndent(); out.pushIndent(); // XXX - Returns boolean because if a tag is invoked from // within this fragment, the Generator sometimes might // generate code like "return true". This is ignored for now, // meaning only the fragment is skipped. The JSR-152 // expert group is currently discussing what to do in this case. // See comment in closeFragment() if (methodNesting > 0) { out.printin("public boolean invoke"); } else { out.printin("public void invoke"); } out.println(result.getId() + "( " + "javax.servlet.jsp.JspWriter out ) "); out.pushIndent(); // Note: Throwable required because methods like _jspx_meth_* // throw Throwable. out.printil("throws java.lang.Throwable"); out.popIndent(); out.printil("{"); out.pushIndent(); generateLocalVariables(out, parent); return result; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
public static Node.Nodes parse( ParserController pc, String path, JarFile jarFile, Node parent, boolean isTagFile, boolean directivesOnly, String pageEnc, String jspConfigPageEnc, boolean isEncodingSpecifiedInProlog, boolean isBomPresent) throws JasperException { JspDocumentParser jspDocParser = new JspDocumentParser(pc, path, isTagFile, directivesOnly); Node.Nodes pageNodes = null; try { // Create dummy root and initialize it with given page encodings Node.Root dummyRoot = new Node.Root(null, parent, true); dummyRoot.setPageEncoding(pageEnc); dummyRoot.setJspConfigPageEncoding(jspConfigPageEnc); dummyRoot.setIsEncodingSpecifiedInProlog( isEncodingSpecifiedInProlog); dummyRoot.setIsBomPresent(isBomPresent); jspDocParser.current = dummyRoot; if (parent == null) { jspDocParser.addInclude( dummyRoot, jspDocParser.pageInfo.getIncludePrelude()); } else { jspDocParser.isTop = false; } // Parse the input SAXParser saxParser = getSAXParser(false, jspDocParser); InputStream inStream = null; try { inStream = JspUtil.getInputStream(path, jarFile, jspDocParser.ctxt); saxParser.parse(new InputSource(inStream), jspDocParser); } catch (EnableDTDValidationException e) { saxParser = getSAXParser(true, jspDocParser); jspDocParser.isValidating = true; if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } inStream = JspUtil.getInputStream(path, jarFile, jspDocParser.ctxt); saxParser.parse(new InputSource(inStream), jspDocParser); } finally { if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } } if (parent == null) { jspDocParser.addInclude( dummyRoot, jspDocParser.pageInfo.getIncludeCoda()); } // Create Node.Nodes from dummy root pageNodes = new Node.Nodes(dummyRoot); } catch (IOException ioe) { jspDocParser.err.jspError("jsp.error.data.file.read", path, ioe); } catch (SAXParseException e) { jspDocParser.err.jspError (new Mark(jspDocParser.ctxt, path, e.getLineNumber(), e.getColumnNumber()), e.getMessage()); } catch (Exception e) { jspDocParser.err.jspError(e); } return pageNodes; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private TagLibraryInfo getTaglibInfo(String prefix, String uri) throws JasperException { TagLibraryInfo result = null; if (uri.startsWith(URN_JSPTAGDIR)) { // uri (of the form "urn:jsptagdir:path") references tag file dir String tagdir = uri.substring(URN_JSPTAGDIR.length()); result = new ImplicitTagLibraryInfo( ctxt, parserController, pageInfo, prefix, tagdir, err); } else { // uri references TLD file boolean isPlainUri = false; if (uri.startsWith(URN_JSPTLD)) { // uri is of the form "urn:jsptld:path" uri = uri.substring(URN_JSPTLD.length()); } else { isPlainUri = true; } TldLocation location = ctxt.getTldLocation(uri); if (location != null || !isPlainUri) { if (ctxt.getOptions().isCaching()) { result = ctxt.getOptions().getCache().get(uri); } if (result == null) { /* * If the uri value is a plain uri, a translation error must * not be generated if the uri is not found in the taglib map. * Instead, any actions in the namespace defined by the uri * value must be treated as uninterpreted. */ result = new TagLibraryInfoImpl( ctxt, parserController, pageInfo, prefix, uri, location, err, null); if (ctxt.getOptions().isCaching()) { ctxt.getOptions().getCache().put(uri, result); } } } } return result; }
// in java/org/apache/jasper/compiler/TagPluginManager.java
public void apply(Node.Nodes page, ErrorDispatcher err, PageInfo pageInfo) throws JasperException { init(err); if (tagPlugins == null || tagPlugins.size() == 0) { return; } this.pageInfo = pageInfo; page.visit(new Node.Visitor() { @Override public void visit(Node.CustomTag n) throws JasperException { invokePlugin(n); visitBody(n); } }); }
// in java/org/apache/jasper/compiler/TagPluginManager.java
Override public void visit(Node.CustomTag n) throws JasperException { invokePlugin(n); visitBody(n); }
// in java/org/apache/jasper/compiler/TagPluginManager.java
private void init(ErrorDispatcher err) throws JasperException { if (initialized) return; InputStream is = ctxt.getResourceAsStream(TAG_PLUGINS_XML); if (is == null) return; TreeNode root = (new ParserUtils()).parseXMLDocument(TAG_PLUGINS_XML, is); if (root == null) { return; } if (!TAG_PLUGINS_ROOT_ELEM.equals(root.getName())) { err.jspError("jsp.error.plugin.wrongRootElement", TAG_PLUGINS_XML, TAG_PLUGINS_ROOT_ELEM); } tagPlugins = new HashMap<String, TagPlugin>(); Iterator<TreeNode> pluginList = root.findChildren("tag-plugin"); while (pluginList.hasNext()) { TreeNode pluginNode = pluginList.next(); TreeNode tagClassNode = pluginNode.findChild("tag-class"); if (tagClassNode == null) { // Error return; } String tagClass = tagClassNode.getBody().trim(); TreeNode pluginClassNode = pluginNode.findChild("plugin-class"); if (pluginClassNode == null) { // Error return; } String pluginClassStr = pluginClassNode.getBody(); TagPlugin tagPlugin = null; try { Class<?> pluginClass = Class.forName(pluginClassStr); tagPlugin = (TagPlugin) pluginClass.newInstance(); } catch (Exception e) { throw new JasperException(e); } if (tagPlugin == null) { return; } tagPlugins.put(tagClass, tagPlugin); } initialized = true; }
// in java/org/apache/jasper/compiler/ScriptingVariabler.java
Override public void visit(Node.CustomTag n) throws JasperException { n.setCustomTagParent(parent); Node.CustomTag tmpParent = parent; parent = n; visitBody(n); parent = tmpParent; n.setNumCount(new Integer(count++)); }
// in java/org/apache/jasper/compiler/ScriptingVariabler.java
Override public void visit(Node.CustomTag n) throws JasperException { setScriptingVars(n, VariableInfo.AT_BEGIN); setScriptingVars(n, VariableInfo.NESTED); visitBody(n); setScriptingVars(n, VariableInfo.AT_END); }
// in java/org/apache/jasper/compiler/ScriptingVariabler.java
private void setScriptingVars(Node.CustomTag n, int scope) throws JasperException { TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if (tagVarInfos.length == 0 && varInfos.length == 0) { return; } List<Object> vec = new ArrayList<Object>(); Integer ownRange = null; Node.CustomTag parent = n.getCustomTagParent(); if (scope == VariableInfo.AT_BEGIN || scope == VariableInfo.AT_END) { if (parent == null) ownRange = MAX_SCOPE; else ownRange = parent.getNumCount(); } else { // NESTED ownRange = n.getNumCount(); } if (varInfos.length > 0) { for (int i=0; i<varInfos.length; i++) { if (varInfos[i].getScope() != scope || !varInfos[i].getDeclare()) { continue; } String varName = varInfos[i].getVarName(); Integer currentRange = scriptVars.get(varName); if (currentRange == null || ownRange.compareTo(currentRange) > 0) { scriptVars.put(varName, ownRange); vec.add(varInfos[i]); } } } else { for (int i=0; i<tagVarInfos.length; i++) { if (tagVarInfos[i].getScope() != scope || !tagVarInfos[i].getDeclare()) { continue; } String varName = tagVarInfos[i].getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); if (varName == null) { err.jspError(n, "jsp.error.scripting.variable.missing_name", tagVarInfos[i].getNameFromAttribute()); } } Integer currentRange = scriptVars.get(varName); if (currentRange == null || ownRange.compareTo(currentRange) > 0) { scriptVars.put(varName, ownRange); vec.add(tagVarInfos[i]); } } } n.setScriptingVars(vec, scope); }
// in java/org/apache/jasper/compiler/ScriptingVariabler.java
public static void set(Node.Nodes page, ErrorDispatcher err) throws JasperException { page.visit(new CustomTagCounter()); page.visit(new ScriptingVariableVisitor(err)); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.Root n) throws JasperException { visitBody(n); if (n == root) { /* * Top-level page. * * Add * xmlns:jsp="http://java.sun.com/JSP/Page" * attribute only if not already present. */ if (!JSP_URI.equals(rootAttrs.getValue("xmlns:jsp"))) { rootAttrs.addAttribute("", "", "xmlns:jsp", "CDATA", JSP_URI); } if (pageInfo.isJspPrefixHijacked()) { /* * 'jsp' prefix has been hijacked, that is, bound to a * namespace other than the JSP namespace. This means that * when adding an 'id' attribute to each element, we can't * use the 'jsp' prefix. Therefore, create a new prefix * (one that is unique across the translation unit) for use * by the 'id' attribute, and bind it to the JSP namespace */ jspIdPrefix += "jsp"; while (pageInfo.containsPrefix(jspIdPrefix)) { jspIdPrefix += "jsp"; } rootAttrs.addAttribute("", "", "xmlns:" + jspIdPrefix, "CDATA", JSP_URI); } root.setAttributes(rootAttrs); } }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.JspRoot n) throws JasperException { addAttributes(n.getTaglibAttributes()); addAttributes(n.getNonTaglibXmlnsAttributes()); addAttributes(n.getAttributes()); visitBody(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.TaglibDirective n) throws JasperException { Attributes attrs = n.getAttributes(); if (attrs != null) { String qName = "xmlns:" + attrs.getValue("prefix"); /* * According to javadocs of org.xml.sax.helpers.AttributesImpl, * the addAttribute method does not check to see if the * specified attribute is already contained in the list: This * is the application's responsibility! */ if (rootAttrs.getIndex(qName) == -1) { String location = attrs.getValue("uri"); if (location != null) { if (location.startsWith("/")) { location = URN_JSPTLD + location; } rootAttrs.addAttribute("", "", qName, "CDATA", location); } else { location = attrs.getValue("tagdir"); rootAttrs.addAttribute("", "", qName, "CDATA", URN_JSPTAGDIR + location); } } } }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.Root n) throws JasperException { if (n == this.root) { // top-level page appendXmlProlog(); appendTag(n); } else { boolean resetDefaultNSSave = resetDefaultNS; if (n.isXmlSyntax()) { resetDefaultNS = true; } visitBody(n); resetDefaultNS = resetDefaultNSSave; } }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.JspRoot n) throws JasperException { visitBody(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.PageDirective n) throws JasperException { appendPageDirective(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.IncludeDirective n) throws JasperException { // expand in place visitBody(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.Comment n) throws JasperException { // Comments are ignored in XML view }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.Declaration n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.Expression n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.Scriptlet n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.JspElement n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.ELExpression n) throws JasperException { if (!n.getRoot().isXmlSyntax()) { buf.append("<").append(JSP_TEXT_ACTION); buf.append(" "); buf.append(jspIdPrefix); buf.append(":id=\""); buf.append(jspId++).append("\">"); } buf.append("${"); buf.append(JspUtil.escapeXml(n.getText())); buf.append("}"); if (!n.getRoot().isXmlSyntax()) { buf.append(JSP_TEXT_ACTION_END); } buf.append("\n"); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.IncludeAction n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.ForwardAction n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.GetProperty n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.SetProperty n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.ParamAction n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.ParamsAction n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.FallBackAction n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.UseBean n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.PlugIn n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.NamedAttribute n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.JspBody n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.CustomTag n) throws JasperException { boolean resetDefaultNSSave = resetDefaultNS; appendTag(n, resetDefaultNS); resetDefaultNS = resetDefaultNSSave; }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.UninterpretedTag n) throws JasperException { boolean resetDefaultNSSave = resetDefaultNS; appendTag(n, resetDefaultNS); resetDefaultNS = resetDefaultNSSave; }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.JspText n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.DoBodyAction n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.InvokeAction n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.TagDirective n) throws JasperException { appendTagDirective(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.AttributeDirective n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.VariableDirective n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.TemplateText n) throws JasperException { /* * If the template text came from a JSP page written in JSP syntax, * create a jsp:text element for it (JSP 5.3.2). */ appendText(n.getText(), !n.getRoot().isXmlSyntax()); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
private void appendTag(Node n) throws JasperException { appendTag(n, false); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
private void appendTag(Node n, boolean addDefaultNS) throws JasperException { Node.Nodes body = n.getBody(); String text = n.getText(); buf.append("<").append(n.getQName()); buf.append("\n"); printAttributes(n, addDefaultNS); buf.append(" ").append(jspIdPrefix).append(":id").append("=\""); buf.append(jspId++).append("\"\n"); if (ROOT_ACTION.equals(n.getLocalName()) || body != null || text != null) { buf.append(">\n"); if (ROOT_ACTION.equals(n.getLocalName())) { if (compiler.getCompilationContext().isTagFile()) { appendTagDirective(); } else { appendPageDirective(); } } if (body != null) { body.visit(this); } else { appendText(text, false); } buf.append("</" + n.getQName() + ">\n"); } else { buf.append("/>\n"); } }
// in java/org/apache/jasper/compiler/PageDataImpl.java
private void appendTagDirective(Node.TagDirective n) throws JasperException { boolean append = false; Attributes attrs = n.getAttributes(); int len = (attrs == null) ? 0 : attrs.getLength(); for (int i=0; i<len; i++) { @SuppressWarnings("null") // If attrs==null, len == 0 String attrName = attrs.getQName(i); if (!"pageEncoding".equals(attrName)) { append = true; break; } } if (!append) { return; } appendTag(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.IncludeDirective n) throws JasperException { // Since pageDirectiveSeen flag only applies to the Current page // save it here and restore it after the file is included. boolean pageEncodingSeenSave = pageEncodingSeen; pageEncodingSeen = false; visitBody(n); pageEncodingSeen = pageEncodingSeenSave; }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.PageDirective n) throws JasperException { JspUtil.checkAttributes("Page directive", n, pageDirectiveAttrs, err); // JSP.2.10.1 Attributes attrs = n.getAttributes(); for (int i = 0; attrs != null && i < attrs.getLength(); i++) { String attr = attrs.getQName(i); String value = attrs.getValue(i); if ("language".equals(attr)) { if (pageInfo.getLanguage(false) == null) { pageInfo.setLanguage(value, n, err, true); } else if (!pageInfo.getLanguage(false).equals(value)) { err.jspError(n, "jsp.error.page.conflict.language", pageInfo.getLanguage(false), value); } } else if ("extends".equals(attr)) { if (pageInfo.getExtends(false) == null) { pageInfo.setExtends(value, n); } else if (!pageInfo.getExtends(false).equals(value)) { err.jspError(n, "jsp.error.page.conflict.extends", pageInfo.getExtends(false), value); } } else if ("contentType".equals(attr)) { if (pageInfo.getContentType() == null) { pageInfo.setContentType(value); } else if (!pageInfo.getContentType().equals(value)) { err.jspError(n, "jsp.error.page.conflict.contenttype", pageInfo.getContentType(), value); } } else if ("session".equals(attr)) { if (pageInfo.getSession() == null) { pageInfo.setSession(value, n, err); } else if (!pageInfo.getSession().equals(value)) { err.jspError(n, "jsp.error.page.conflict.session", pageInfo.getSession(), value); } } else if ("buffer".equals(attr)) { if (pageInfo.getBufferValue() == null) { pageInfo.setBufferValue(value, n, err); } else if (!pageInfo.getBufferValue().equals(value)) { err.jspError(n, "jsp.error.page.conflict.buffer", pageInfo.getBufferValue(), value); } } else if ("autoFlush".equals(attr)) { if (pageInfo.getAutoFlush() == null) { pageInfo.setAutoFlush(value, n, err); } else if (!pageInfo.getAutoFlush().equals(value)) { err.jspError(n, "jsp.error.page.conflict.autoflush", pageInfo.getAutoFlush(), value); } } else if ("isThreadSafe".equals(attr)) { if (pageInfo.getIsThreadSafe() == null) { pageInfo.setIsThreadSafe(value, n, err); } else if (!pageInfo.getIsThreadSafe().equals(value)) { err.jspError(n, "jsp.error.page.conflict.isthreadsafe", pageInfo.getIsThreadSafe(), value); } } else if ("isELIgnored".equals(attr)) { if (pageInfo.getIsELIgnored() == null) { pageInfo.setIsELIgnored(value, n, err, true); } else if (!pageInfo.getIsELIgnored().equals(value)) { err.jspError(n, "jsp.error.page.conflict.iselignored", pageInfo.getIsELIgnored(), value); } } else if ("isErrorPage".equals(attr)) { if (pageInfo.getIsErrorPage() == null) { pageInfo.setIsErrorPage(value, n, err); } else if (!pageInfo.getIsErrorPage().equals(value)) { err.jspError(n, "jsp.error.page.conflict.iserrorpage", pageInfo.getIsErrorPage(), value); } } else if ("errorPage".equals(attr)) { if (pageInfo.getErrorPage() == null) { pageInfo.setErrorPage(value); } else if (!pageInfo.getErrorPage().equals(value)) { err.jspError(n, "jsp.error.page.conflict.errorpage", pageInfo.getErrorPage(), value); } } else if ("info".equals(attr)) { if (pageInfo.getInfo() == null) { pageInfo.setInfo(value); } else if (!pageInfo.getInfo().equals(value)) { err.jspError(n, "jsp.error.page.conflict.info", pageInfo.getInfo(), value); } } else if ("pageEncoding".equals(attr)) { if (pageEncodingSeen) err.jspError(n, "jsp.error.page.multi.pageencoding"); // 'pageEncoding' can occur at most once per file pageEncodingSeen = true; String actual = comparePageEncodings(value, n); n.getRoot().setPageEncoding(actual); } else if ("deferredSyntaxAllowedAsLiteral".equals(attr)) { if (pageInfo.getDeferredSyntaxAllowedAsLiteral() == null) { pageInfo.setDeferredSyntaxAllowedAsLiteral(value, n, err, true); } else if (!pageInfo.getDeferredSyntaxAllowedAsLiteral() .equals(value)) { err .jspError( n, "jsp.error.page.conflict.deferredsyntaxallowedasliteral", pageInfo .getDeferredSyntaxAllowedAsLiteral(), value); } } else if ("trimDirectiveWhitespaces".equals(attr)) { if (pageInfo.getTrimDirectiveWhitespaces() == null) { pageInfo.setTrimDirectiveWhitespaces(value, n, err, true); } else if (!pageInfo.getTrimDirectiveWhitespaces().equals( value)) { err .jspError( n, "jsp.error.page.conflict.trimdirectivewhitespaces", pageInfo.getTrimDirectiveWhitespaces(), value); } } } // Check for bad combinations if (pageInfo.getBuffer() == 0 && !pageInfo.isAutoFlush()) err.jspError(n, "jsp.error.page.badCombo"); // Attributes for imports for this node have been processed by // the parsers, just add them to pageInfo. pageInfo.addImports(n.getImports()); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.TagDirective n) throws JasperException { // Note: Most of the validation is done in TagFileProcessor // when it created a TagInfo object from the // tag file in which the directive appeared. // This method does additional processing to collect page info Attributes attrs = n.getAttributes(); for (int i = 0; attrs != null && i < attrs.getLength(); i++) { String attr = attrs.getQName(i); String value = attrs.getValue(i); if ("language".equals(attr)) { if (pageInfo.getLanguage(false) == null) { pageInfo.setLanguage(value, n, err, false); } else if (!pageInfo.getLanguage(false).equals(value)) { err.jspError(n, "jsp.error.tag.conflict.language", pageInfo.getLanguage(false), value); } } else if ("isELIgnored".equals(attr)) { if (pageInfo.getIsELIgnored() == null) { pageInfo.setIsELIgnored(value, n, err, false); } else if (!pageInfo.getIsELIgnored().equals(value)) { err.jspError(n, "jsp.error.tag.conflict.iselignored", pageInfo.getIsELIgnored(), value); } } else if ("pageEncoding".equals(attr)) { if (pageEncodingSeen) err.jspError(n, "jsp.error.tag.multi.pageencoding"); pageEncodingSeen = true; compareTagEncodings(value, n); n.getRoot().setPageEncoding(value); } else if ("deferredSyntaxAllowedAsLiteral".equals(attr)) { if (pageInfo.getDeferredSyntaxAllowedAsLiteral() == null) { pageInfo.setDeferredSyntaxAllowedAsLiteral(value, n, err, false); } else if (!pageInfo.getDeferredSyntaxAllowedAsLiteral() .equals(value)) { err .jspError( n, "jsp.error.tag.conflict.deferredsyntaxallowedasliteral", pageInfo .getDeferredSyntaxAllowedAsLiteral(), value); } } else if ("trimDirectiveWhitespaces".equals(attr)) { if (pageInfo.getTrimDirectiveWhitespaces() == null) { pageInfo.setTrimDirectiveWhitespaces(value, n, err, false); } else if (!pageInfo.getTrimDirectiveWhitespaces().equals( value)) { err .jspError( n, "jsp.error.tag.conflict.trimdirectivewhitespaces", pageInfo.getTrimDirectiveWhitespaces(), value); } } } // Attributes for imports for this node have been processed by // the parsers, just add them to pageInfo. pageInfo.addImports(n.getImports()); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.AttributeDirective n) throws JasperException { // Do nothing, since this attribute directive has already been // validated by TagFileProcessor when it created a TagInfo object // from the tag file in which the directive appeared }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.VariableDirective n) throws JasperException { // Do nothing, since this variable directive has already been // validated by TagFileProcessor when it created a TagInfo object // from the tag file in which the directive appeared }
// in java/org/apache/jasper/compiler/Validator.java
private String comparePageEncodings(String thePageDirEnc, Node.PageDirective pageDir) throws JasperException { Node.Root root = pageDir.getRoot(); String configEnc = root.getJspConfigPageEncoding(); String pageDirEnc = thePageDirEnc.toUpperCase(Locale.ENGLISH); /* * Compare the 'pageEncoding' attribute of the page directive with * the encoding specified in the JSP config element whose URL * pattern matches this page. Treat "UTF-16", "UTF-16BE", and * "UTF-16LE" as identical. */ if (configEnc != null) { configEnc = configEnc.toUpperCase(Locale.ENGLISH); if (!pageDirEnc.equals(configEnc) && (!pageDirEnc.startsWith("UTF-16") || !configEnc .startsWith("UTF-16"))) { err.jspError(pageDir, "jsp.error.config_pagedir_encoding_mismatch", configEnc, pageDirEnc); } else { return configEnc; } } /* * Compare the 'pageEncoding' attribute of the page directive with * the encoding specified in the XML prolog (only for XML syntax, * and only if JSP document contains XML prolog with encoding * declaration). Treat "UTF-16", "UTF-16BE", and "UTF-16LE" as * identical. */ if ((root.isXmlSyntax() && root.isEncodingSpecifiedInProlog()) || root.isBomPresent()) { String pageEnc = root.getPageEncoding().toUpperCase(Locale.ENGLISH); if (!pageDirEnc.equals(pageEnc) && (!pageDirEnc.startsWith("UTF-16") || !pageEnc .startsWith("UTF-16"))) { err.jspError(pageDir, "jsp.error.prolog_pagedir_encoding_mismatch", pageEnc, pageDirEnc); } else { return pageEnc; } } return pageDirEnc; }
// in java/org/apache/jasper/compiler/Validator.java
private void compareTagEncodings(String thePageDirEnc, Node.TagDirective pageDir) throws JasperException { Node.Root root = pageDir.getRoot(); String pageDirEnc = thePageDirEnc.toUpperCase(Locale.ENGLISH); /* * Compare the 'pageEncoding' attribute of the page directive with * the encoding specified in the XML prolog (only for XML syntax, * and only if JSP document contains XML prolog with encoding * declaration). Treat "UTF-16", "UTF-16BE", and "UTF-16LE" as * identical. */ if ((root.isXmlSyntax() && root.isEncodingSpecifiedInProlog()) || root.isBomPresent()) { String pageEnc = root.getPageEncoding().toUpperCase(Locale.ENGLISH); if (!pageDirEnc.equals(pageEnc) && (!pageDirEnc.startsWith("UTF-16") || !pageEnc .startsWith("UTF-16"))) { err.jspError(pageDir, "jsp.error.prolog_pagedir_encoding_mismatch", pageEnc, pageDirEnc); } } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.JspRoot n) throws JasperException { JspUtil.checkAttributes("Jsp:root", n, jspRootAttrs, err); String version = n.getTextAttribute("version"); if (!version.equals("1.2") && !version.equals("2.0") && !version.equals("2.1") && !version.equals("2.2")) { err.jspError(n, "jsp.error.jsproot.version.invalid", version); } visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.IncludeDirective n) throws JasperException { JspUtil.checkAttributes("Include directive", n, includeDirectiveAttrs, err); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.TaglibDirective n) throws JasperException { JspUtil.checkAttributes("Taglib directive", n, taglibDirectiveAttrs, err); // Either 'uri' or 'tagdir' attribute must be specified String uri = n.getAttributeValue("uri"); String tagdir = n.getAttributeValue("tagdir"); if (uri == null && tagdir == null) { err.jspError(n, "jsp.error.taglibDirective.missing.location"); } if (uri != null && tagdir != null) { err .jspError(n, "jsp.error.taglibDirective.both_uri_and_tagdir"); } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.ParamAction n) throws JasperException { JspUtil.checkAttributes("Param action", n, paramActionAttrs, err); // make sure the value of the 'name' attribute is not a // request-time expression throwErrorIfExpression(n, "name", "jsp:param"); n.setValue(getJspAttribute(null, "value", null, null, n .getAttributeValue("value"), n, false)); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.ParamsAction n) throws JasperException { // Make sure we've got at least one nested jsp:param Node.Nodes subElems = n.getBody(); if (subElems == null) { err.jspError(n, "jsp.error.params.emptyBody"); } visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.IncludeAction n) throws JasperException { JspUtil.checkAttributes("Include action", n, includeActionAttrs, err); n.setPage(getJspAttribute(null, "page", null, null, n .getAttributeValue("page"), n, false)); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.ForwardAction n) throws JasperException { JspUtil.checkAttributes("Forward", n, forwardActionAttrs, err); n.setPage(getJspAttribute(null, "page", null, null, n .getAttributeValue("page"), n, false)); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.GetProperty n) throws JasperException { JspUtil.checkAttributes("GetProperty", n, getPropertyAttrs, err); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.SetProperty n) throws JasperException { JspUtil.checkAttributes("SetProperty", n, setPropertyAttrs, err); String property = n.getTextAttribute("property"); String param = n.getTextAttribute("param"); String value = n.getAttributeValue("value"); n.setValue(getJspAttribute(null, "value", null, null, value, n, false)); boolean valueSpecified = n.getValue() != null; if ("*".equals(property)) { if (param != null || valueSpecified) err.jspError(n, "jsp.error.setProperty.invalid"); } else if (param != null && valueSpecified) { err.jspError(n, "jsp.error.setProperty.invalid"); } visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.UseBean n) throws JasperException { JspUtil.checkAttributes("UseBean", n, useBeanAttrs, err); String name = n.getTextAttribute("id"); String scope = n.getTextAttribute("scope"); JspUtil.checkScope(scope, n, err); String className = n.getTextAttribute("class"); String type = n.getTextAttribute("type"); BeanRepository beanInfo = pageInfo.getBeanRepository(); if (className == null && type == null) err.jspError(n, "jsp.error.usebean.missingType"); if (beanInfo.checkVariable(name)) err.jspError(n, "jsp.error.usebean.duplicate"); if ("session".equals(scope) && !pageInfo.isSession()) err.jspError(n, "jsp.error.usebean.noSession"); Node.JspAttribute jattr = getJspAttribute(null, "beanName", null, null, n.getAttributeValue("beanName"), n, false); n.setBeanName(jattr); if (className != null && jattr != null) err.jspError(n, "jsp.error.usebean.notBoth"); if (className == null) className = type; beanInfo.addBean(n, name, className, scope); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.PlugIn n) throws JasperException { JspUtil.checkAttributes("Plugin", n, plugInAttrs, err); throwErrorIfExpression(n, "type", "jsp:plugin"); throwErrorIfExpression(n, "code", "jsp:plugin"); throwErrorIfExpression(n, "codebase", "jsp:plugin"); throwErrorIfExpression(n, "align", "jsp:plugin"); throwErrorIfExpression(n, "archive", "jsp:plugin"); throwErrorIfExpression(n, "hspace", "jsp:plugin"); throwErrorIfExpression(n, "jreversion", "jsp:plugin"); throwErrorIfExpression(n, "name", "jsp:plugin"); throwErrorIfExpression(n, "vspace", "jsp:plugin"); throwErrorIfExpression(n, "nspluginurl", "jsp:plugin"); throwErrorIfExpression(n, "iepluginurl", "jsp:plugin"); String type = n.getTextAttribute("type"); if (type == null) err.jspError(n, "jsp.error.plugin.notype"); if (!type.equals("bean") && !type.equals("applet")) err.jspError(n, "jsp.error.plugin.badtype"); if (n.getTextAttribute("code") == null) err.jspError(n, "jsp.error.plugin.nocode"); Node.JspAttribute width = getJspAttribute(null, "width", null, null, n.getAttributeValue("width"), n, false); n.setWidth(width); Node.JspAttribute height = getJspAttribute(null, "height", null, null, n.getAttributeValue("height"), n, false); n.setHeight(height); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.NamedAttribute n) throws JasperException { JspUtil.checkAttributes("Attribute", n, attributeAttrs, err); n.setOmit(getJspAttribute(null, "omit", null, null, n .getAttributeValue("omit"), n, true)); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.JspBody n) throws JasperException { visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.Declaration n) throws JasperException { if (pageInfo.isScriptingInvalid()) { err.jspError(n.getStart(), "jsp.error.no.scriptlets"); } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.Expression n) throws JasperException { if (pageInfo.isScriptingInvalid()) { err.jspError(n.getStart(), "jsp.error.no.scriptlets"); } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.Scriptlet n) throws JasperException { if (pageInfo.isScriptingInvalid()) { err.jspError(n.getStart(), "jsp.error.no.scriptlets"); } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.ELExpression n) throws JasperException { // exit if we are ignoring EL all together if (pageInfo.isELIgnored()) return; // JSP.2.2 - '#{' not allowed in template text if (n.getType() == '#') { if (!pageInfo.isDeferredSyntaxAllowedAsLiteral()) { err.jspError(n, "jsp.error.el.template.deferred"); } else { return; } } // build expression StringBuilder expr = this.getBuffer(); expr.append(n.getType()).append('{').append(n.getText()) .append('}'); ELNode.Nodes el = ELParser.parse(expr.toString(), pageInfo .isDeferredSyntaxAllowedAsLiteral()); // validate/prepare expression prepareExpression(el, n, expr.toString()); // store it n.setEL(el); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.UninterpretedTag n) throws JasperException { if (n.getNamedAttributeNodes().size() != 0) { err.jspError(n, "jsp.error.namedAttribute.invalidUse"); } Attributes attrs = n.getAttributes(); if (attrs != null) { int attrSize = attrs.getLength(); Node.JspAttribute[] jspAttrs = new Node.JspAttribute[attrSize]; for (int i = 0; i < attrSize; i++) { // JSP.2.2 - '#{' not allowed in template text String value = attrs.getValue(i); if (!pageInfo.isDeferredSyntaxAllowedAsLiteral()) { if (containsDeferredSyntax(value)) { err.jspError(n, "jsp.error.el.template.deferred"); } } jspAttrs[i] = getJspAttribute(null, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), value, n, false); } n.setJspAttributes(jspAttrs); } visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.CustomTag n) throws JasperException { TagInfo tagInfo = n.getTagInfo(); if (tagInfo == null) { err.jspError(n, "jsp.error.missing.tagInfo", n.getQName()); } /* * The bodycontent of a SimpleTag cannot be JSP. */ if (n.implementsSimpleTag() && tagInfo.getBodyContent().equalsIgnoreCase( TagInfo.BODY_CONTENT_JSP)) { err.jspError(n, "jsp.error.simpletag.badbodycontent", tagInfo .getTagClassName()); } /* * If the tag handler declares in the TLD that it supports dynamic * attributes, it also must implement the DynamicAttributes * interface. */ if (tagInfo.hasDynamicAttributes() && !n.implementsDynamicAttributes()) { err.jspError(n, "jsp.error.dynamic.attributes.not.implemented", n.getQName()); } /* * Make sure all required attributes are present, either as * attributes or named attributes (<jsp:attribute>). Also make sure * that the same attribute is not specified in both attributes or * named attributes. */ TagAttributeInfo[] tldAttrs = tagInfo.getAttributes(); String customActionUri = n.getURI(); Attributes attrs = n.getAttributes(); int attrsSize = (attrs == null) ? 0 : attrs.getLength(); for (int i = 0; i < tldAttrs.length; i++) { String attr = null; if (attrs != null) { attr = attrs.getValue(tldAttrs[i].getName()); if (attr == null) { attr = attrs.getValue(customActionUri, tldAttrs[i] .getName()); } } Node.NamedAttribute na = n.getNamedAttributeNode(tldAttrs[i] .getName()); if (tldAttrs[i].isRequired() && attr == null && na == null) { err.jspError(n, "jsp.error.missing_attribute", tldAttrs[i] .getName(), n.getLocalName()); } if (attr != null && na != null) { err.jspError(n, "jsp.error.duplicate.name.jspattribute", tldAttrs[i].getName()); } } Node.Nodes naNodes = n.getNamedAttributeNodes(); int jspAttrsSize = naNodes.size() + attrsSize; Node.JspAttribute[] jspAttrs = null; if (jspAttrsSize > 0) { jspAttrs = new Node.JspAttribute[jspAttrsSize]; } Hashtable<String, Object> tagDataAttrs = new Hashtable<String, Object>(attrsSize); checkXmlAttributes(n, jspAttrs, tagDataAttrs); checkNamedAttributes(n, jspAttrs, attrsSize, tagDataAttrs); TagData tagData = new TagData(tagDataAttrs); // JSP.C1: It is a (translation time) error for an action that // has one or more variable subelements to have a TagExtraInfo // class that returns a non-null object. TagExtraInfo tei = tagInfo.getTagExtraInfo(); if (tei != null && tei.getVariableInfo(tagData) != null && tei.getVariableInfo(tagData).length > 0 && tagInfo.getTagVariableInfos().length > 0) { err.jspError("jsp.error.non_null_tei_and_var_subelems", n .getQName()); } n.setTagData(tagData); n.setJspAttributes(jspAttrs); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.JspElement n) throws JasperException { Attributes attrs = n.getAttributes(); if (attrs == null) { err.jspError(n, "jsp.error.jspelement.missing.name"); } @SuppressWarnings("null") // Exception will have been thrown above int xmlAttrLen = attrs.getLength(); Node.Nodes namedAttrs = n.getNamedAttributeNodes(); // XML-style 'name' attribute, which is mandatory, must not be // included in JspAttribute array int jspAttrSize = xmlAttrLen - 1 + namedAttrs.size(); Node.JspAttribute[] jspAttrs = new Node.JspAttribute[jspAttrSize]; int jspAttrIndex = 0; // Process XML-style attributes for (int i = 0; i < xmlAttrLen; i++) { if ("name".equals(attrs.getLocalName(i))) { n.setNameAttribute(getJspAttribute(null, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs .getValue(i), n, false)); } else { if (jspAttrIndex < jspAttrSize) { jspAttrs[jspAttrIndex++] = getJspAttribute(null, attrs .getQName(i), attrs.getURI(i), attrs .getLocalName(i), attrs.getValue(i), n, false); } } } if (n.getNameAttribute() == null) { err.jspError(n, "jsp.error.jspelement.missing.name"); } // Process named attributes for (int i = 0; i < namedAttrs.size(); i++) { Node.NamedAttribute na = (Node.NamedAttribute) namedAttrs .getNode(i); jspAttrs[jspAttrIndex++] = new Node.JspAttribute(na, null, false); } n.setJspAttributes(jspAttrs); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.JspOutput n) throws JasperException { JspUtil.checkAttributes("jsp:output", n, jspOutputAttrs, err); if (n.getBody() != null) { err.jspError(n, "jsp.error.jspoutput.nonemptybody"); } String omitXmlDecl = n.getAttributeValue("omit-xml-declaration"); String doctypeName = n.getAttributeValue("doctype-root-element"); String doctypePublic = n.getAttributeValue("doctype-public"); String doctypeSystem = n.getAttributeValue("doctype-system"); String omitXmlDeclOld = pageInfo.getOmitXmlDecl(); String doctypeNameOld = pageInfo.getDoctypeName(); String doctypePublicOld = pageInfo.getDoctypePublic(); String doctypeSystemOld = pageInfo.getDoctypeSystem(); if (omitXmlDecl != null && omitXmlDeclOld != null && !omitXmlDecl.equals(omitXmlDeclOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "omit-xml-declaration", omitXmlDeclOld, omitXmlDecl); } if (doctypeName != null && doctypeNameOld != null && !doctypeName.equals(doctypeNameOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "doctype-root-element", doctypeNameOld, doctypeName); } if (doctypePublic != null && doctypePublicOld != null && !doctypePublic.equals(doctypePublicOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "doctype-public", doctypePublicOld, doctypePublic); } if (doctypeSystem != null && doctypeSystemOld != null && !doctypeSystem.equals(doctypeSystemOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "doctype-system", doctypeSystemOld, doctypeSystem); } if (doctypeName == null && doctypeSystem != null || doctypeName != null && doctypeSystem == null) { err.jspError(n, "jsp.error.jspoutput.doctypenamesystem"); } if (doctypePublic != null && doctypeSystem == null) { err.jspError(n, "jsp.error.jspoutput.doctypepulicsystem"); } if (omitXmlDecl != null) { pageInfo.setOmitXmlDecl(omitXmlDecl); } if (doctypeName != null) { pageInfo.setDoctypeName(doctypeName); } if (doctypeSystem != null) { pageInfo.setDoctypeSystem(doctypeSystem); } if (doctypePublic != null) { pageInfo.setDoctypePublic(doctypePublic); } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.InvokeAction n) throws JasperException { JspUtil.checkAttributes("Invoke", n, invokeAttrs, err); String scope = n.getTextAttribute("scope"); JspUtil.checkScope(scope, n, err); String var = n.getTextAttribute("var"); String varReader = n.getTextAttribute("varReader"); if (scope != null && var == null && varReader == null) { err.jspError(n, "jsp.error.missing_var_or_varReader"); } if (var != null && varReader != null) { err.jspError(n, "jsp.error.var_and_varReader"); } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.DoBodyAction n) throws JasperException { JspUtil.checkAttributes("DoBody", n, doBodyAttrs, err); String scope = n.getTextAttribute("scope"); JspUtil.checkScope(scope, n, err); String var = n.getTextAttribute("var"); String varReader = n.getTextAttribute("varReader"); if (scope != null && var == null && varReader == null) { err.jspError(n, "jsp.error.missing_var_or_varReader"); } if (var != null && varReader != null) { err.jspError(n, "jsp.error.var_and_varReader"); } }
// in java/org/apache/jasper/compiler/Validator.java
private void checkXmlAttributes(Node.CustomTag n, Node.JspAttribute[] jspAttrs, Hashtable<String, Object> tagDataAttrs) throws JasperException { TagInfo tagInfo = n.getTagInfo(); if (tagInfo == null) { err.jspError(n, "jsp.error.missing.tagInfo", n.getQName()); } TagAttributeInfo[] tldAttrs = tagInfo.getAttributes(); Attributes attrs = n.getAttributes(); for (int i = 0; attrs != null && i < attrs.getLength(); i++) { boolean found = false; boolean runtimeExpression = ((n.getRoot().isXmlSyntax() && attrs.getValue(i).startsWith("%=")) || (!n.getRoot().isXmlSyntax() && attrs.getValue(i).startsWith("<%="))); boolean elExpression = false; boolean deferred = false; double libraryVersion = Double.parseDouble( tagInfo.getTagLibrary().getRequiredVersion()); boolean deferredSyntaxAllowedAsLiteral = pageInfo.isDeferredSyntaxAllowedAsLiteral() || libraryVersion < 2.1; ELNode.Nodes el = null; if (!runtimeExpression && !pageInfo.isELIgnored()) { el = ELParser.parse(attrs.getValue(i), deferredSyntaxAllowedAsLiteral); Iterator<ELNode> nodes = el.iterator(); while (nodes.hasNext()) { ELNode node = nodes.next(); if (node instanceof ELNode.Root) { if (((ELNode.Root) node).getType() == '$') { if (elExpression && deferred) { err.jspError(n, "jsp.error.attribute.deferredmix"); } elExpression = true; } else if (((ELNode.Root) node).getType() == '#') { if (elExpression && !deferred) { err.jspError(n, "jsp.error.attribute.deferredmix"); } elExpression = true; deferred = true; } } } } boolean expression = runtimeExpression || elExpression; for (int j = 0; tldAttrs != null && j < tldAttrs.length; j++) { if (attrs.getLocalName(i).equals(tldAttrs[j].getName()) && (attrs.getURI(i) == null || attrs.getURI(i).length() == 0 || attrs .getURI(i).equals(n.getURI()))) { TagAttributeInfo tldAttr = tldAttrs[j]; if (tldAttr.canBeRequestTime() || tldAttr.isDeferredMethod() || tldAttr.isDeferredValue()) { // JSP 2.1 if (!expression) { String expectedType = null; if (tldAttr.isDeferredMethod()) { // The String literal must be castable to what is declared as type // for the attribute String m = tldAttr.getMethodSignature(); if (m != null) { m = m.trim(); int rti = m.indexOf(' '); if (rti > 0) { expectedType = m.substring(0, rti).trim(); } } else { expectedType = "java.lang.Object"; } if ("void".equals(expectedType)) { // Can't specify a literal for a // deferred method with an expected type // of void - JSP.2.3.4 err.jspError(n, "jsp.error.literal_with_void", tldAttr.getName()); } } if (tldAttr.isDeferredValue()) { // The String literal must be castable to what is declared as type // for the attribute expectedType = tldAttr.getExpectedTypeName(); } if (expectedType != null) { Class<?> expectedClass = String.class; try { expectedClass = JspUtil.toClass(expectedType, loader); } catch (ClassNotFoundException e) { err.jspError (n, "jsp.error.unknown_attribute_type", tldAttr.getName(), expectedType); } // Check casting - not possible for all types if (String.class.equals(expectedClass) || expectedClass == Long.TYPE || expectedClass == Double.TYPE || expectedClass == Byte.TYPE || expectedClass == Short.TYPE || expectedClass == Integer.TYPE || expectedClass == Float.TYPE || Number.class.isAssignableFrom(expectedClass) || Character.class.equals(expectedClass) || Character.TYPE == expectedClass || Boolean.class.equals(expectedClass) || Boolean.TYPE == expectedClass || expectedClass.isEnum()) { try { expressionFactory.coerceToType(attrs.getValue(i), expectedClass); } catch (Exception e) { err.jspError (n, "jsp.error.coerce_to_type", tldAttr.getName(), expectedType, attrs.getValue(i)); } } } jspAttrs[i] = new Node.JspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs .getLocalName(i), attrs.getValue(i), false, null, false); } else { if (deferred && !tldAttr.isDeferredMethod() && !tldAttr.isDeferredValue()) { // No deferred expressions allowed for this attribute err.jspError(n, "jsp.error.attribute.custom.non_rt_with_expr", tldAttr.getName()); } if (!deferred && !tldAttr.canBeRequestTime()) { // Only deferred expressions are allowed for this attribute err.jspError(n, "jsp.error.attribute.custom.non_rt_with_expr", tldAttr.getName()); } if (elExpression) { // El expression validateFunctions(el, n); jspAttrs[i] = new Node.JspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs.getValue(i), false, el, false); ELContextImpl ctx = new ELContextImpl(); ctx.setFunctionMapper(getFunctionMapper(el)); try { jspAttrs[i].validateEL(this.pageInfo.getExpressionFactory(), ctx); } catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", attrs.getValue(i), e.toString()); } } else { // Runtime expression jspAttrs[i] = getJspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs .getValue(i), n, false); } } } else { // Attribute does not accept any expressions. // Make sure its value does not contain any. if (expression) { err.jspError(n, "jsp.error.attribute.custom.non_rt_with_expr", tldAttr.getName()); } jspAttrs[i] = new Node.JspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs .getLocalName(i), attrs.getValue(i), false, null, false); } if (expression) { tagDataAttrs.put(attrs.getQName(i), TagData.REQUEST_TIME_VALUE); } else { tagDataAttrs.put(attrs.getQName(i), attrs .getValue(i)); } found = true; break; } } if (!found) { if (tagInfo.hasDynamicAttributes()) { jspAttrs[i] = getJspAttribute(null, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs .getValue(i), n, true); } else { err.jspError(n, "jsp.error.bad_attribute", attrs .getQName(i), n.getLocalName()); } } } }
// in java/org/apache/jasper/compiler/Validator.java
private void checkNamedAttributes(Node.CustomTag n, Node.JspAttribute[] jspAttrs, int start, Hashtable<String, Object> tagDataAttrs) throws JasperException { TagInfo tagInfo = n.getTagInfo(); if (tagInfo == null) { err.jspError(n, "jsp.error.missing.tagInfo", n.getQName()); } TagAttributeInfo[] tldAttrs = tagInfo.getAttributes(); Node.Nodes naNodes = n.getNamedAttributeNodes(); for (int i = 0; i < naNodes.size(); i++) { Node.NamedAttribute na = (Node.NamedAttribute) naNodes .getNode(i); boolean found = false; for (int j = 0; j < tldAttrs.length; j++) { /* * See above comment about namespace matches. For named * attributes, we use the prefix instead of URI as the match * criterion, because in the case of a JSP document, we'd * have to keep track of which namespaces are in scope when * parsing a named attribute, in order to determine the URI * that the prefix of the named attribute's name matches to. */ String attrPrefix = na.getPrefix(); if (na.getLocalName().equals(tldAttrs[j].getName()) && (attrPrefix == null || attrPrefix.length() == 0 || attrPrefix .equals(n.getPrefix()))) { jspAttrs[start + i] = new Node.JspAttribute(na, tldAttrs[j], false); NamedAttributeVisitor nav = null; if (na.getBody() != null) { nav = new NamedAttributeVisitor(); na.getBody().visit(nav); } if (nav != null && nav.hasDynamicContent()) { tagDataAttrs.put(na.getName(), TagData.REQUEST_TIME_VALUE); } else { tagDataAttrs.put(na.getName(), na.getText()); } found = true; break; } } if (!found) { if (tagInfo.hasDynamicAttributes()) { jspAttrs[start + i] = new Node.JspAttribute(na, null, true); } else { err.jspError(n, "jsp.error.bad_attribute", na.getName(), n.getLocalName()); } } } }
// in java/org/apache/jasper/compiler/Validator.java
private Node.JspAttribute getJspAttribute(TagAttributeInfo tai, String qName, String uri, String localName, String value, Node n, boolean dynamic) throws JasperException { Node.JspAttribute result = null; // XXX Is it an error to see "%=foo%" in non-Xml page? // (We won't see "<%=foo%> in xml page because '<' is not a // valid attribute value in xml). if (value != null) { if (n.getRoot().isXmlSyntax() && value.startsWith("%=")) { result = new Node.JspAttribute(tai, qName, uri, localName, value.substring(2, value.length() - 1), true, null, dynamic); } else if (!n.getRoot().isXmlSyntax() && value.startsWith("<%=")) { result = new Node.JspAttribute(tai, qName, uri, localName, value.substring(3, value.length() - 2), true, null, dynamic); } else if (pageInfo.isELIgnored()) { result = new Node.JspAttribute(tai, qName, uri, localName, value, false, null, dynamic); } else { // The attribute can contain expressions but is not a // scriptlet expression; thus, we want to run it through // the expression interpreter // validate expression syntax if string contains // expression(s) ELNode.Nodes el = ELParser.parse(value, pageInfo .isDeferredSyntaxAllowedAsLiteral()); if (el.containsEL()) { validateFunctions(el, n); result = new Node.JspAttribute(tai, qName, uri, localName, value, false, el, dynamic); ELContextImpl ctx = new ELContextImpl(); ctx.setFunctionMapper(getFunctionMapper(el)); try { result.validateEL(this.pageInfo .getExpressionFactory(), ctx); } catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", value, e .toString()); } } else { result = new Node.JspAttribute(tai, qName, uri, localName, value, false, null, dynamic); } } } else { // Value is null. Check for any NamedAttribute subnodes // that might contain the value for this attribute. // Otherwise, the attribute wasn't found so we return null. Node.NamedAttribute namedAttributeNode = n .getNamedAttributeNode(qName); if (namedAttributeNode != null) { result = new Node.JspAttribute(namedAttributeNode, tai, dynamic); } } return result; }
// in java/org/apache/jasper/compiler/Validator.java
private void throwErrorIfExpression(Node n, String attrName, String actionName) throws JasperException { if (n.getAttributes() != null && n.getAttributes().getValue(attrName) != null && isExpression(n, n.getAttributes().getValue(attrName), true)) { err.jspError(n, "jsp.error.attribute.standard.non_rt_with_expr", attrName, actionName); } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void doVisit(Node n) throws JasperException { if (!(n instanceof Node.JspText) && !(n instanceof Node.TemplateText)) { hasDynamicContent = true; } visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
private void validateFunctions(ELNode.Nodes el, Node n) throws JasperException { class FVVisitor extends ELNode.Visitor { Node n; FVVisitor(Node n) { this.n = n; } @Override public void visit(ELNode.Function func) throws JasperException { String prefix = func.getPrefix(); String function = func.getName(); String uri = null; if (n.getRoot().isXmlSyntax()) { uri = findUri(prefix, n); } else if (prefix != null) { uri = pageInfo.getURI(prefix); } if (uri == null) { if (prefix == null) { err.jspError(n, "jsp.error.noFunctionPrefix", function); } else { err.jspError(n, "jsp.error.attribute.invalidPrefix", prefix); } } TagLibraryInfo taglib = pageInfo.getTaglib(uri); FunctionInfo funcInfo = null; if (taglib != null) { funcInfo = taglib.getFunction(function); } if (funcInfo == null) { err.jspError(n, "jsp.error.noFunction", function); } // Skip TLD function uniqueness check. Done by Schema ? func.setUri(uri); func.setFunctionInfo(funcInfo); processSignature(func); } } el.visit(new FVVisitor(n)); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(ELNode.Function func) throws JasperException { String prefix = func.getPrefix(); String function = func.getName(); String uri = null; if (n.getRoot().isXmlSyntax()) { uri = findUri(prefix, n); } else if (prefix != null) { uri = pageInfo.getURI(prefix); } if (uri == null) { if (prefix == null) { err.jspError(n, "jsp.error.noFunctionPrefix", function); } else { err.jspError(n, "jsp.error.attribute.invalidPrefix", prefix); } } TagLibraryInfo taglib = pageInfo.getTaglib(uri); FunctionInfo funcInfo = null; if (taglib != null) { funcInfo = taglib.getFunction(function); } if (funcInfo == null) { err.jspError(n, "jsp.error.noFunction", function); } // Skip TLD function uniqueness check. Done by Schema ? func.setUri(uri); func.setFunctionInfo(funcInfo); processSignature(func); }
// in java/org/apache/jasper/compiler/Validator.java
private void prepareExpression(ELNode.Nodes el, Node n, String expr) throws JasperException { validateFunctions(el, n); // test it out ELContextImpl ctx = new ELContextImpl(); ctx.setFunctionMapper(this.getFunctionMapper(el)); ExpressionFactory ef = this.pageInfo.getExpressionFactory(); try { ef.createValueExpression(ctx, expr, Object.class); } catch (ELException e) { } }
// in java/org/apache/jasper/compiler/Validator.java
private void processSignature(ELNode.Function func) throws JasperException { func.setMethodName(getMethod(func)); func.setParameters(getParameters(func)); }
// in java/org/apache/jasper/compiler/Validator.java
private String getMethod(ELNode.Function func) throws JasperException { FunctionInfo funcInfo = func.getFunctionInfo(); String signature = funcInfo.getFunctionSignature(); int start = signature.indexOf(' '); if (start < 0) { err.jspError("jsp.error.tld.fn.invalid.signature", func .getPrefix(), func.getName()); } int end = signature.indexOf('('); if (end < 0) { err.jspError( "jsp.error.tld.fn.invalid.signature.parenexpected", func.getPrefix(), func.getName()); } return signature.substring(start + 1, end).trim(); }
// in java/org/apache/jasper/compiler/Validator.java
private String[] getParameters(ELNode.Function func) throws JasperException { FunctionInfo funcInfo = func.getFunctionInfo(); String signature = funcInfo.getFunctionSignature(); ArrayList<String> params = new ArrayList<String>(); // Signature is of the form // <return-type> S <method-name S? '(' // < <arg-type> ( ',' <arg-type> )* )? ')' int start = signature.indexOf('(') + 1; boolean lastArg = false; while (true) { int p = signature.indexOf(',', start); if (p < 0) { p = signature.indexOf(')', start); if (p < 0) { err.jspError("jsp.error.tld.fn.invalid.signature", func .getPrefix(), func.getName()); } lastArg = true; } String arg = signature.substring(start, p).trim(); if (!"".equals(arg)) { params.add(arg); } if (lastArg) { break; } start = p + 1; } return params.toArray(new String[params.size()]); }
// in java/org/apache/jasper/compiler/Validator.java
private FunctionMapper getFunctionMapper(ELNode.Nodes el) throws JasperException { class ValidateFunctionMapper extends FunctionMapper { private HashMap<String, Method> fnmap = new HashMap<String, Method>(); public void mapFunction(String fnQName, Method method) { fnmap.put(fnQName, method); } @Override public Method resolveFunction(String prefix, String localName) { return this.fnmap.get(prefix + ":" + localName); } } class MapperELVisitor extends ELNode.Visitor { ValidateFunctionMapper fmapper; MapperELVisitor(ValidateFunctionMapper fmapper) { this.fmapper = fmapper; } @Override public void visit(ELNode.Function n) throws JasperException { Class<?> c = null; Method method = null; try { c = loader.loadClass(n.getFunctionInfo() .getFunctionClass()); } catch (ClassNotFoundException e) { err.jspError("jsp.error.function.classnotfound", n .getFunctionInfo().getFunctionClass(), n .getPrefix() + ':' + n.getName(), e.getMessage()); } String paramTypes[] = n.getParameters(); int size = paramTypes.length; Class<?> params[] = new Class[size]; int i = 0; try { for (i = 0; i < size; i++) { params[i] = JspUtil.toClass(paramTypes[i], loader); } method = c.getDeclaredMethod(n.getMethodName(), params); } catch (ClassNotFoundException e) { err.jspError("jsp.error.signature.classnotfound", paramTypes[i], n.getPrefix() + ':' + n.getName(), e.getMessage()); } catch (NoSuchMethodException e) { err.jspError("jsp.error.noFunctionMethod", n .getMethodName(), n.getName(), c.getName()); } fmapper.mapFunction(n.getPrefix() + ':' + n.getName(), method); } } ValidateFunctionMapper fmapper = new ValidateFunctionMapper(); el.visit(new MapperELVisitor(fmapper)); return fmapper; }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(ELNode.Function n) throws JasperException { Class<?> c = null; Method method = null; try { c = loader.loadClass(n.getFunctionInfo() .getFunctionClass()); } catch (ClassNotFoundException e) { err.jspError("jsp.error.function.classnotfound", n .getFunctionInfo().getFunctionClass(), n .getPrefix() + ':' + n.getName(), e.getMessage()); } String paramTypes[] = n.getParameters(); int size = paramTypes.length; Class<?> params[] = new Class[size]; int i = 0; try { for (i = 0; i < size; i++) { params[i] = JspUtil.toClass(paramTypes[i], loader); } method = c.getDeclaredMethod(n.getMethodName(), params); } catch (ClassNotFoundException e) { err.jspError("jsp.error.signature.classnotfound", paramTypes[i], n.getPrefix() + ':' + n.getName(), e.getMessage()); } catch (NoSuchMethodException e) { err.jspError("jsp.error.noFunctionMethod", n .getMethodName(), n.getName(), c.getName()); } fmapper.mapFunction(n.getPrefix() + ':' + n.getName(), method); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.CustomTag n) throws JasperException { TagInfo tagInfo = n.getTagInfo(); if (tagInfo == null) { err.jspError(n, "jsp.error.missing.tagInfo", n.getQName()); } ValidationMessage[] errors = tagInfo.validate(n.getTagData()); if (errors != null && errors.length != 0) { StringBuilder errMsg = new StringBuilder(); errMsg.append("<h3>"); errMsg.append(Localizer.getMessage( "jsp.error.tei.invalid.attributes", n.getQName())); errMsg.append("</h3>"); for (int i = 0; i < errors.length; i++) { errMsg.append("<p>"); if (errors[i].getId() != null) { errMsg.append(errors[i].getId()); errMsg.append(": "); } errMsg.append(errors[i].getMessage()); errMsg.append("</p>"); } err.jspError(n, errMsg.toString()); } visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
public static void validateDirectives(Compiler compiler, Node.Nodes page) throws JasperException { page.visit(new DirectiveVisitor(compiler)); }
// in java/org/apache/jasper/compiler/Validator.java
public static void validateExDirectives(Compiler compiler, Node.Nodes page) throws JasperException { // Determine the default output content type PageInfo pageInfo = compiler.getPageInfo(); String contentType = pageInfo.getContentType(); if (contentType == null || contentType.indexOf("charset=") < 0) { boolean isXml = page.getRoot().isXmlSyntax(); String defaultType; if (contentType == null) { defaultType = isXml ? "text/xml" : "text/html"; } else { defaultType = contentType; } String charset = null; if (isXml) { charset = "UTF-8"; } else { if (!page.getRoot().isDefaultPageEncoding()) { charset = page.getRoot().getPageEncoding(); } } if (charset != null) { pageInfo.setContentType(defaultType + ";charset=" + charset); } else { pageInfo.setContentType(defaultType); } } /* * Validate all other nodes. This validation step includes checking a * custom tag's mandatory and optional attributes against information in * the TLD (first validation step for custom tags according to * JSP.10.5). */ page.visit(new ValidateVisitor(compiler)); /* * Invoke TagLibraryValidator classes of all imported tags (second * validation step for custom tags according to JSP.10.5). */ validateXmlView(new PageDataImpl(page, compiler), compiler); /* * Invoke TagExtraInfo method isValid() for all imported tags (third * validation step for custom tags according to JSP.10.5). */ page.visit(new TagExtraInfoVisitor(compiler)); }
// in java/org/apache/jasper/compiler/Validator.java
private static void validateXmlView(PageData xmlView, Compiler compiler) throws JasperException { StringBuilder errMsg = null; ErrorDispatcher errDisp = compiler.getErrorDispatcher(); for (Iterator<TagLibraryInfo> iter = compiler.getPageInfo().getTaglibs().iterator(); iter.hasNext();) { Object o = iter.next(); if (!(o instanceof TagLibraryInfoImpl)) continue; TagLibraryInfoImpl tli = (TagLibraryInfoImpl) o; ValidationMessage[] errors = tli.validate(xmlView); if ((errors != null) && (errors.length != 0)) { if (errMsg == null) { errMsg = new StringBuilder(); } errMsg.append("<h3>"); errMsg.append(Localizer.getMessage( "jsp.error.tlv.invalid.page", tli.getShortName(), compiler.getPageInfo().getJspFile())); errMsg.append("</h3>"); for (int i = 0; i < errors.length; i++) { if (errors[i] != null) { errMsg.append("<p>"); errMsg.append(errors[i].getId()); errMsg.append(": "); errMsg.append(errors[i].getMessage()); errMsg.append("</p>"); } } } } if (errMsg != null) { errDisp.jspError(errMsg.toString()); } }
// in java/org/apache/jasper/compiler/Dumper.java
private void dumpBody(Node n) throws JasperException { Node.Nodes page = n.getBody(); if (page != null) { // indent++; page.visit(this); // indent--; } }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.PageDirective n) throws JasperException { printAttributes("<%@ page", n.getAttributes(), "%>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.TaglibDirective n) throws JasperException { printAttributes("<%@ taglib", n.getAttributes(), "%>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.IncludeDirective n) throws JasperException { printAttributes("<%@ include", n.getAttributes(), "%>"); dumpBody(n); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.Comment n) throws JasperException { printString("<%--", n.getText(), "--%>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.Declaration n) throws JasperException { printString("<%!", n.getText(), "%>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.Expression n) throws JasperException { printString("<%=", n.getText(), "%>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.Scriptlet n) throws JasperException { printString("<%", n.getText(), "%>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.IncludeAction n) throws JasperException { printAttributes("<jsp:include", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:include>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.ForwardAction n) throws JasperException { printAttributes("<jsp:forward", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:forward>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.GetProperty n) throws JasperException { printAttributes("<jsp:getProperty", n.getAttributes(), "/>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.SetProperty n) throws JasperException { printAttributes("<jsp:setProperty", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:setProperty>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.UseBean n) throws JasperException { printAttributes("<jsp:useBean", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:useBean>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.PlugIn n) throws JasperException { printAttributes("<jsp:plugin", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:plugin>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.ParamsAction n) throws JasperException { printAttributes("<jsp:params", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:params>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.ParamAction n) throws JasperException { printAttributes("<jsp:param", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:param>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.NamedAttribute n) throws JasperException { printAttributes("<jsp:attribute", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:attribute>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.JspBody n) throws JasperException { printAttributes("<jsp:body", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:body>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.ELExpression n) throws JasperException { printString( "${" + n.getText() + "}" ); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.CustomTag n) throws JasperException { printAttributes("<" + n.getQName(), n.getAttributes(), ">"); dumpBody(n); printString("</" + n.getQName() + ">"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.UninterpretedTag n) throws JasperException { String tag = n.getQName(); printAttributes("<"+tag, n.getAttributes(), ">"); dumpBody(n); printString("</" + tag + ">"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.TemplateText n) throws JasperException { printString(n.getText()); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(String errCode) throws JasperException { dispatch(null, errCode, null, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Mark where, String errCode) throws JasperException { dispatch(where, errCode, null, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Node n, String errCode) throws JasperException { dispatch(n.getStart(), errCode, null, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(String errCode, String arg) throws JasperException { dispatch(null, errCode, new Object[] {arg}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Mark where, String errCode, String arg) throws JasperException { dispatch(where, errCode, new Object[] {arg}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Node n, String errCode, String arg) throws JasperException { dispatch(n.getStart(), errCode, new Object[] {arg}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(String errCode, String arg1, String arg2) throws JasperException { dispatch(null, errCode, new Object[] {arg1, arg2}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(String errCode, String arg1, String arg2, String arg3) throws JasperException { dispatch(null, errCode, new Object[] {arg1, arg2, arg3}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Mark where, String errCode, String arg1, String arg2) throws JasperException { dispatch(where, errCode, new Object[] {arg1, arg2}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Mark where, String errCode, String arg1, String arg2, String arg3) throws JasperException { dispatch(where, errCode, new Object[] {arg1, arg2, arg3}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Node n, String errCode, String arg1, String arg2) throws JasperException { dispatch(n.getStart(), errCode, new Object[] {arg1, arg2}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Node n, String errCode, String arg1, String arg2, String arg3) throws JasperException { dispatch(n.getStart(), errCode, new Object[] {arg1, arg2, arg3}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Exception e) throws JasperException { dispatch(null, null, null, e); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(String errCode, String arg, Exception e) throws JasperException { dispatch(null, errCode, new Object[] {arg}, e); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Node n, String errCode, String arg, Exception e) throws JasperException { dispatch(n.getStart(), errCode, new Object[] {arg}, e); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public static JavacErrorDetail[] parseJavacErrors(String errMsg, String fname, Node.Nodes page) throws JasperException, IOException { return parseJavacMessage(errMsg, fname, page); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void javacError(JavacErrorDetail[] javacErrors) throws JasperException { errHandler.javacError(javacErrors); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void javacError(String errorReport, Exception e) throws JasperException { errHandler.javacError(errorReport, e); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
private void dispatch(Mark where, String errCode, Object[] args, Exception e) throws JasperException { String file = null; String errMsg = null; int line = -1; int column = -1; boolean hasLocation = false; // Localize if (errCode != null) { errMsg = Localizer.getMessage(errCode, args); } else if (e != null) { // give a hint about what's wrong errMsg = e.getMessage(); } // Get error location if (where != null) { if (jspcMode) { // Get the full URL of the resource that caused the error try { file = where.getURL().toString(); } catch (MalformedURLException me) { // Fallback to using context-relative path file = where.getFile(); } } else { // Get the context-relative resource path, so as to not // disclose any local filesystem details file = where.getFile(); } line = where.getLineNumber(); column = where.getColumnNumber(); hasLocation = true; } // Get nested exception Exception nestedEx = e; if ((e instanceof SAXException) && (((SAXException) e).getException() != null)) { nestedEx = ((SAXException) e).getException(); } if (hasLocation) { errHandler.jspError(file, line, column, errMsg, nestedEx); } else { errHandler.jspError(errMsg, nestedEx); } }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
private static JavacErrorDetail[] parseJavacMessage( String errMsg, String fname, Node.Nodes page) throws IOException, JasperException { ArrayList<JavacErrorDetail> errors = new ArrayList<JavacErrorDetail>(); StringBuilder errMsgBuf = null; int lineNum = -1; JavacErrorDetail javacError = null; BufferedReader reader = new BufferedReader(new StringReader(errMsg)); /* * Parse compilation errors. Each compilation error consists of a file * path and error line number, followed by a number of lines describing * the error. */ String line = null; while ((line = reader.readLine()) != null) { /* * Error line number is delimited by set of colons. * Ignore colon following drive letter on Windows (fromIndex = 2). * XXX Handle deprecation warnings that don't have line info */ int beginColon = line.indexOf(':', 2); int endColon = line.indexOf(':', beginColon + 1); if ((beginColon >= 0) && (endColon >= 0)) { if (javacError != null) { // add previous error to error vector errors.add(javacError); } String lineNumStr = line.substring(beginColon + 1, endColon); try { lineNum = Integer.parseInt(lineNumStr); } catch (NumberFormatException e) { lineNum = -1; } errMsgBuf = new StringBuilder(); javacError = createJavacError(fname, page, errMsgBuf, lineNum); } // Ignore messages preceding first error if (errMsgBuf != null) { errMsgBuf.append(line); errMsgBuf.append(Constants.NEWLINE); } } // Add last error to error vector if (javacError != null) { errors.add(javacError); } reader.close(); JavacErrorDetail[] errDetails = null; if (errors.size() > 0) { errDetails = new JavacErrorDetail[errors.size()]; errors.toArray(errDetails); } return errDetails; }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public static JavacErrorDetail createJavacError(String fname, Node.Nodes page, StringBuilder errMsgBuf, int lineNum) throws JasperException { return createJavacError(fname, page, errMsgBuf, lineNum, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public static JavacErrorDetail createJavacError(String fname, Node.Nodes page, StringBuilder errMsgBuf, int lineNum, JspCompilationContext ctxt) throws JasperException { JavacErrorDetail javacError; // Attempt to map javac error line number to line in JSP page ErrorVisitor errVisitor = new ErrorVisitor(lineNum); page.visit(errVisitor); Node errNode = errVisitor.getJspSourceNode(); if ((errNode != null) && (errNode.getStart() != null)) { // If this is a scriplet node then there is a one to one mapping // between JSP lines and Java lines if (errVisitor.getJspSourceNode() instanceof Node.Scriptlet) { javacError = new JavacErrorDetail( fname, lineNum, errNode.getStart().getFile(), errNode.getStart().getLineNumber() + lineNum - errVisitor.getJspSourceNode().getBeginJavaLine(), errMsgBuf, ctxt); } else { javacError = new JavacErrorDetail( fname, lineNum, errNode.getStart().getFile(), errNode.getStart().getLineNumber(), errMsgBuf, ctxt); } } else { /* * javac error line number cannot be mapped to JSP page * line number. For example, this is the case if a * scriptlet is missing a closing brace, which causes * havoc with the try-catch-finally block that the code * generator places around all generated code: As a result * of this, the javac error line numbers will be outside * the range of begin and end java line numbers that were * generated for the scriptlet, and therefore cannot be * mapped to the start line number of the scriptlet in the * JSP page. * Include just the javac error info in the error detail. */ javacError = new JavacErrorDetail( fname, lineNum, errMsgBuf); } return javacError; }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
Override public void doVisit(Node n) throws JasperException { if ((lineNum >= n.getBeginJavaLine()) && (lineNum < n.getEndJavaLine())) { found = n; } }
// in java/org/apache/jasper/compiler/AntCompiler.java
Override protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception { long t1 = 0; if (log.isDebugEnabled()) { t1 = System.currentTimeMillis(); } String javaEncoding = ctxt.getOptions().getJavaEncoding(); String javaFileName = ctxt.getServletJavaFileName(); String classpath = ctxt.getClassPath(); String sep = System.getProperty("path.separator"); StringBuilder errorReport = new StringBuilder(); StringBuilder info=new StringBuilder(); info.append("Compile: javaFileName=" + javaFileName + "\n" ); info.append(" classpath=" + classpath + "\n" ); // Start capturing the System.err output for this thread SystemLogHandler.setThread(); // Initializing javac task getProject(); Javac javac = (Javac) project.createTask("javac"); // Initializing classpath Path path = new Path(project); path.setPath(System.getProperty("java.class.path")); info.append(" cp=" + System.getProperty("java.class.path") + "\n"); StringTokenizer tokenizer = new StringTokenizer(classpath, sep); while (tokenizer.hasMoreElements()) { String pathElement = tokenizer.nextToken(); File repository = new File(pathElement); path.setLocation(repository); info.append(" cp=" + repository + "\n"); } if( log.isDebugEnabled() ) log.debug( "Using classpath: " + System.getProperty("java.class.path") + sep + classpath); // Initializing sourcepath Path srcPath = new Path(project); srcPath.setLocation(options.getScratchDir()); info.append(" work dir=" + options.getScratchDir() + "\n"); // Initialize and set java extensions String exts = System.getProperty("java.ext.dirs"); if (exts != null) { Path extdirs = new Path(project); extdirs.setPath(exts); javac.setExtdirs(extdirs); info.append(" extension dir=" + exts + "\n"); } // Add endorsed directories if any are specified and we're forking // See Bugzilla 31257 if(ctxt.getOptions().getFork()) { String endorsed = System.getProperty("java.endorsed.dirs"); if(endorsed != null) { Javac.ImplementationSpecificArgument endorsedArg = javac.createCompilerArg(); endorsedArg.setLine("-J-Djava.endorsed.dirs=" + quotePathList(endorsed)); info.append(" endorsed dir=" + quotePathList(endorsed) + "\n"); } else { info.append(" no endorsed dirs specified\n"); } } // Configure the compiler object javac.setEncoding(javaEncoding); javac.setClasspath(path); javac.setDebug(ctxt.getOptions().getClassDebugInfo()); javac.setSrcdir(srcPath); javac.setTempdir(options.getScratchDir()); javac.setOptimize(! ctxt.getOptions().getClassDebugInfo() ); javac.setFork(ctxt.getOptions().getFork()); info.append(" srcDir=" + srcPath + "\n" ); // Set the Java compiler to use if (options.getCompiler() != null) { javac.setCompiler(options.getCompiler()); info.append(" compiler=" + options.getCompiler() + "\n"); } if (options.getCompilerTargetVM() != null) { javac.setTarget(options.getCompilerTargetVM()); info.append(" compilerTargetVM=" + options.getCompilerTargetVM() + "\n"); } if (options.getCompilerSourceVM() != null) { javac.setSource(options.getCompilerSourceVM()); info.append(" compilerSourceVM=" + options.getCompilerSourceVM() + "\n"); } // Build includes path PatternSet.NameEntry includes = javac.createInclude(); includes.setName(ctxt.getJavaPath()); info.append(" include="+ ctxt.getJavaPath() + "\n" ); BuildException be = null; try { if (ctxt.getOptions().getFork()) { javac.execute(); } else { synchronized(javacLock) { javac.execute(); } } } catch (BuildException e) { be = e; log.error(Localizer.getMessage("jsp.error.javac"), e); log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString()); } errorReport.append(logger.getReport()); // Stop capturing the System.err output for this thread String errorCapture = SystemLogHandler.unsetThread(); if (errorCapture != null) { errorReport.append(Constants.NEWLINE); errorReport.append(errorCapture); } if (!ctxt.keepGenerated()) { File javaFile = new File(javaFileName); javaFile.delete(); } if (be != null) { String errorReportString = errorReport.toString(); log.error(Localizer.getMessage("jsp.error.compilation", javaFileName, errorReportString)); JavacErrorDetail[] javacErrors = ErrorDispatcher.parseJavacErrors( errorReportString, javaFileName, pageNodes); if (javacErrors != null) { errDispatcher.javacError(javacErrors); } else { errDispatcher.javacError(errorReportString, be); } } if( log.isDebugEnabled() ) { long t2 = System.currentTimeMillis(); log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2-t1) + "ms"); } logger = null; project = null; if (ctxt.isPrototypeMode()) { return; } // JSR45 Support if (! options.isSmapSuppressed()) { SmapUtil.installSmap(smap); } }
// in java/org/apache/jasper/compiler/JspConfig.java
private void processWebDotXml() throws JasperException { WebXml webXml = null; try { webXml = new WebXml(ctxt); TreeNode webApp = null; if (webXml.getInputSource() != null) { ParserUtils pu = new ParserUtils(); webApp = pu.parseXMLDocument(webXml.getSystemId(), webXml.getInputSource()); } if (webApp == null || getVersion(webApp) < 2.4) { defaultIsELIgnored = "true"; defaultDeferedSyntaxAllowedAsLiteral = "true"; return; } if (getVersion(webApp) < 2.5) { defaultDeferedSyntaxAllowedAsLiteral = "true"; } TreeNode jspConfig = webApp.findChild("jsp-config"); if (jspConfig == null) { return; } jspProperties = new Vector<JspPropertyGroup>(); Iterator<TreeNode> jspPropertyList = jspConfig.findChildren("jsp-property-group"); while (jspPropertyList.hasNext()) { TreeNode element = jspPropertyList.next(); Iterator<TreeNode> list = element.findChildren(); Vector<String> urlPatterns = new Vector<String>(); String pageEncoding = null; String scriptingInvalid = null; String elIgnored = null; String isXml = null; Vector<String> includePrelude = new Vector<String>(); Vector<String> includeCoda = new Vector<String>(); String deferredSyntaxAllowedAsLiteral = null; String trimDirectiveWhitespaces = null; String defaultContentType = null; String buffer = null; String errorOnUndeclaredNamespace = null; while (list.hasNext()) { element = list.next(); String tname = element.getName(); if ("url-pattern".equals(tname)) urlPatterns.addElement( element.getBody() ); else if ("page-encoding".equals(tname)) pageEncoding = element.getBody(); else if ("is-xml".equals(tname)) isXml = element.getBody(); else if ("el-ignored".equals(tname)) elIgnored = element.getBody(); else if ("scripting-invalid".equals(tname)) scriptingInvalid = element.getBody(); else if ("include-prelude".equals(tname)) includePrelude.addElement(element.getBody()); else if ("include-coda".equals(tname)) includeCoda.addElement(element.getBody()); else if ("deferred-syntax-allowed-as-literal".equals(tname)) deferredSyntaxAllowedAsLiteral = element.getBody(); else if ("trim-directive-whitespaces".equals(tname)) trimDirectiveWhitespaces = element.getBody(); else if ("default-content-type".equals(tname)) defaultContentType = element.getBody(); else if ("buffer".equals(tname)) buffer = element.getBody(); else if ("error-on-undeclared-namespace".equals(tname)) errorOnUndeclaredNamespace = element.getBody(); } if (urlPatterns.size() == 0) { continue; } // Add one JspPropertyGroup for each URL Pattern. This makes // the matching logic easier. for( int p = 0; p < urlPatterns.size(); p++ ) { String urlPattern = urlPatterns.elementAt( p ); String path = null; String extension = null; if (urlPattern.indexOf('*') < 0) { // Exact match path = urlPattern; } else { int i = urlPattern.lastIndexOf('/'); String file; if (i >= 0) { path = urlPattern.substring(0,i+1); file = urlPattern.substring(i+1); } else { file = urlPattern; } // pattern must be "*", or of the form "*.jsp" if (file.equals("*")) { extension = "*"; } else if (file.startsWith("*.")) { extension = file.substring(file.indexOf('.')+1); } // The url patterns are reconstructed as the following: // path != null, extension == null: / or /foo/bar.ext // path == null, extension != null: *.ext // path != null, extension == "*": /foo/* boolean isStar = "*".equals(extension); if ((path == null && (extension == null || isStar)) || (path != null && !isStar)) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage( "jsp.warning.bad.urlpattern.propertygroup", urlPattern)); } continue; } } JspProperty property = new JspProperty(isXml, elIgnored, scriptingInvalid, pageEncoding, includePrelude, includeCoda, deferredSyntaxAllowedAsLiteral, trimDirectiveWhitespaces, defaultContentType, buffer, errorOnUndeclaredNamespace); JspPropertyGroup propertyGroup = new JspPropertyGroup(path, extension, property); jspProperties.addElement(propertyGroup); } } } catch (Exception ex) { throw new JasperException(ex); } finally { if (webXml != null) { webXml.close(); } } }
// in java/org/apache/jasper/compiler/JspConfig.java
private void init() throws JasperException { if (!initialized) { synchronized (this) { if (!initialized) { processWebDotXml(); defaultJspProperty = new JspProperty(defaultIsXml, defaultIsELIgnored, defaultIsScriptingInvalid, null, null, null, defaultDeferedSyntaxAllowedAsLiteral, defaultTrimDirectiveWhitespaces, defaultDefaultContentType, defaultBuffer, defaultErrorOnUndeclaredNamespace); initialized = true; } } } }
// in java/org/apache/jasper/compiler/JspConfig.java
public JspProperty findJspProperty(String uri) throws JasperException { init(); // JSP Configuration settings do not apply to tag files if (jspProperties == null || uri.endsWith(".tag") || uri.endsWith(".tagx")) { return defaultJspProperty; } String uriPath = null; int index = uri.lastIndexOf('/'); if (index >=0 ) { uriPath = uri.substring(0, index+1); } String uriExtension = null; index = uri.lastIndexOf('.'); if (index >=0) { uriExtension = uri.substring(index+1); } Vector<String> includePreludes = new Vector<String>(); Vector<String> includeCodas = new Vector<String>(); JspPropertyGroup isXmlMatch = null; JspPropertyGroup elIgnoredMatch = null; JspPropertyGroup scriptingInvalidMatch = null; JspPropertyGroup pageEncodingMatch = null; JspPropertyGroup deferedSyntaxAllowedAsLiteralMatch = null; JspPropertyGroup trimDirectiveWhitespacesMatch = null; JspPropertyGroup defaultContentTypeMatch = null; JspPropertyGroup bufferMatch = null; JspPropertyGroup errorOnUndeclaredNamespaceMatch = null; Iterator<JspPropertyGroup> iter = jspProperties.iterator(); while (iter.hasNext()) { JspPropertyGroup jpg = iter.next(); JspProperty jp = jpg.getJspProperty(); // (arrays will be the same length) String extension = jpg.getExtension(); String path = jpg.getPath(); if (extension == null) { // exact match pattern: /a/foo.jsp if (!uri.equals(path)) { // not matched; continue; } } else { // Matching patterns *.ext or /p/* if (path != null && uriPath != null && ! uriPath.startsWith(path)) { // not matched continue; } if (!extension.equals("*") && !extension.equals(uriExtension)) { // not matched continue; } } // We have a match // Add include-preludes and include-codas if (jp.getIncludePrelude() != null) { includePreludes.addAll(jp.getIncludePrelude()); } if (jp.getIncludeCoda() != null) { includeCodas.addAll(jp.getIncludeCoda()); } // If there is a previous match for the same property, remember // the one that is more restrictive. if (jp.isXml() != null) { isXmlMatch = selectProperty(isXmlMatch, jpg); } if (jp.isELIgnored() != null) { elIgnoredMatch = selectProperty(elIgnoredMatch, jpg); } if (jp.isScriptingInvalid() != null) { scriptingInvalidMatch = selectProperty(scriptingInvalidMatch, jpg); } if (jp.getPageEncoding() != null) { pageEncodingMatch = selectProperty(pageEncodingMatch, jpg); } if (jp.isDeferedSyntaxAllowedAsLiteral() != null) { deferedSyntaxAllowedAsLiteralMatch = selectProperty(deferedSyntaxAllowedAsLiteralMatch, jpg); } if (jp.isTrimDirectiveWhitespaces() != null) { trimDirectiveWhitespacesMatch = selectProperty(trimDirectiveWhitespacesMatch, jpg); } if (jp.getDefaultContentType() != null) { defaultContentTypeMatch = selectProperty(defaultContentTypeMatch, jpg); } if (jp.getBuffer() != null) { bufferMatch = selectProperty(bufferMatch, jpg); } if (jp.isErrorOnUndeclaredNamespace() != null) { errorOnUndeclaredNamespaceMatch = selectProperty(errorOnUndeclaredNamespaceMatch, jpg); } } String isXml = defaultIsXml; String isELIgnored = defaultIsELIgnored; String isScriptingInvalid = defaultIsScriptingInvalid; String pageEncoding = null; String isDeferedSyntaxAllowedAsLiteral = defaultDeferedSyntaxAllowedAsLiteral; String isTrimDirectiveWhitespaces = defaultTrimDirectiveWhitespaces; String defaultContentType = defaultDefaultContentType; String buffer = defaultBuffer; String errorOnUndelcaredNamespace = defaultErrorOnUndeclaredNamespace; if (isXmlMatch != null) { isXml = isXmlMatch.getJspProperty().isXml(); } if (elIgnoredMatch != null) { isELIgnored = elIgnoredMatch.getJspProperty().isELIgnored(); } if (scriptingInvalidMatch != null) { isScriptingInvalid = scriptingInvalidMatch.getJspProperty().isScriptingInvalid(); } if (pageEncodingMatch != null) { pageEncoding = pageEncodingMatch.getJspProperty().getPageEncoding(); } if (deferedSyntaxAllowedAsLiteralMatch != null) { isDeferedSyntaxAllowedAsLiteral = deferedSyntaxAllowedAsLiteralMatch.getJspProperty().isDeferedSyntaxAllowedAsLiteral(); } if (trimDirectiveWhitespacesMatch != null) { isTrimDirectiveWhitespaces = trimDirectiveWhitespacesMatch.getJspProperty().isTrimDirectiveWhitespaces(); } if (defaultContentTypeMatch != null) { defaultContentType = defaultContentTypeMatch.getJspProperty().getDefaultContentType(); } if (bufferMatch != null) { buffer = bufferMatch.getJspProperty().getBuffer(); } if (errorOnUndeclaredNamespaceMatch != null) { errorOnUndelcaredNamespace = errorOnUndeclaredNamespaceMatch.getJspProperty().isErrorOnUndeclaredNamespace(); } return new JspProperty(isXml, isELIgnored, isScriptingInvalid, pageEncoding, includePreludes, includeCodas, isDeferedSyntaxAllowedAsLiteral, isTrimDirectiveWhitespaces, defaultContentType, buffer, errorOnUndelcaredNamespace); }
// in java/org/apache/jasper/compiler/JspConfig.java
public boolean isJspPage(String uri) throws JasperException { init(); if (jspProperties == null) { return false; } String uriPath = null; int index = uri.lastIndexOf('/'); if (index >=0 ) { uriPath = uri.substring(0, index+1); } String uriExtension = null; index = uri.lastIndexOf('.'); if (index >=0) { uriExtension = uri.substring(index+1); } Iterator<JspPropertyGroup> iter = jspProperties.iterator(); while (iter.hasNext()) { JspPropertyGroup jpg = iter.next(); String extension = jpg.getExtension(); String path = jpg.getPath(); if (extension == null) { if (uri.equals(path)) { // There is an exact match return true; } } else { if ((path == null || path.equals(uriPath)) && (extension.equals("*") || extension.equals(uriExtension))) { // Matches *, *.ext, /p/*, or /p/*.ext return true; } } } return false; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public Class<?> loadTagFile() throws JasperException { try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; ctxt.compile(); } } else { if (compileException != null) { throw compileException; } } if (reload) { tagHandlerClass = ctxt.load(); reload = false; } } catch (FileNotFoundException ex) { throw new JasperException(ex); } return tagHandlerClass; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public Class<?> loadTagFilePrototype() throws JasperException { ctxt.setPrototypeMode(true); try { return loadTagFile(); } finally { ctxt.setPrototypeMode(false); } }
// in java/org/apache/jasper/JspCompilationContext.java
public TldLocation getTldLocation(String uri) throws JasperException { TldLocation location = getOptions().getTldLocationsCache().getLocation(uri); return location; }
// in java/org/apache/jasper/JspCompilationContext.java
public void compile() throws JasperException, FileNotFoundException { createCompiler(); if (jspCompiler.isOutDated()) { if (isRemoved()) { throw new FileNotFoundException(jspUri); } try { jspCompiler.removeGeneratedFiles(); jspLoader = null; jspCompiler.compile(); jsw.setReload(true); jsw.setCompilationException(null); } catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; } catch (FileNotFoundException fnfe) { // Re-throw to let caller handle this - will result in a 404 throw fnfe; } catch (Exception ex) { JasperException je = new JasperException( Localizer.getMessage("jsp.error.unable.compile"), ex); // Cache compilation exception jsw.setCompilationException(je); throw je; } } }
// in java/org/apache/jasper/JspCompilationContext.java
public Class<?> load() throws JasperException { try { getJspLoader(); String name = getFQCN(); servletClass = jspLoader.loadClass(name); } catch (ClassNotFoundException cex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.load"), cex); } catch (Exception ex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); } removed = 0; return servletClass; }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
public TreeNode parseXMLDocument(String location, InputSource is) throws JasperException { Document document = null; // Perform an XML parse of this document, via JAXP try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(validating); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(entityResolver); builder.setErrorHandler(errorHandler); document = builder.parse(is); } catch (ParserConfigurationException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), ex); } catch (SAXParseException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); } catch (SAXException sx) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), sx); } catch (IOException io) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), io); } // Convert the resulting document to a graph of TreeNodes return (convert(null, document.getDocumentElement())); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
public TreeNode parseXMLDocument(String uri, InputStream is) throws JasperException { return (parseXMLDocument(uri, new InputSource(is))); }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public static Object[] getEncoding(String fname, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err) throws IOException, JasperException { InputStream inStream = JspUtil.getInputStream(fname, jarFile, ctxt); XMLEncodingDetector detector = new XMLEncodingDetector(); Object[] ret = detector.getEncoding(inStream, err); inStream.close(); return ret; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private Object[] getEncoding(InputStream in, ErrorDispatcher err) throws IOException, JasperException { this.stream = in; this.err=err; createInitialReader(); scanXMLDecl(); return new Object[] { this.encoding, Boolean.valueOf(this.isEncodingSetInProlog), Boolean.valueOf(this.isBomPresent), Integer.valueOf(this.skip) }; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void createInitialReader() throws IOException, JasperException { // wrap this stream in RewindableInputStream stream = new RewindableInputStream(stream); // perform auto-detect of encoding if necessary if (encoding == null) { // read first four bytes and determine encoding final byte[] b4 = new byte[4]; int count = 0; for (; count<4; count++ ) { b4[count] = (byte)stream.read(); } if (count == 4) { Object [] encodingDesc = getEncodingName(b4, count); encoding = (String)(encodingDesc[0]); isBigEndian = (Boolean)(encodingDesc[1]); if (encodingDesc.length > 3) { isBomPresent = ((Boolean)(encodingDesc[2])).booleanValue(); skip = ((Integer)(encodingDesc[3])).intValue(); } else { isBomPresent = true; skip = ((Integer)(encodingDesc[2])).intValue(); } stream.reset(); // Special case UTF-8 files with BOM created by Microsoft // tools. It's more efficient to consume the BOM than make // the reader perform extra checks. -Ac if (count > 2 && encoding.equals("UTF-8")) { int b0 = b4[0] & 0xFF; int b1 = b4[1] & 0xFF; int b2 = b4[2] & 0xFF; if (b0 == 0xEF && b1 == 0xBB && b2 == 0xBF) { // ignore first three bytes... long skipped = stream.skip(3); if (skipped != 3) { throw new IOException(Localizer.getMessage( "xmlParser.skipBomFail")); } } } reader = createReader(stream, encoding, isBigEndian); } else { reader = createReader(stream, encoding, isBigEndian); } } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private Reader createReader(InputStream inputStream, String encoding, Boolean isBigEndian) throws IOException, JasperException { // normalize encoding name if (encoding == null) { encoding = "UTF-8"; } // try to use an optimized reader String ENCODING = encoding.toUpperCase(Locale.ENGLISH); if (ENCODING.equals("UTF-8")) { return new UTF8Reader(inputStream, fBufferSize); } if (ENCODING.equals("US-ASCII")) { return new ASCIIReader(inputStream, fBufferSize); } if (ENCODING.equals("ISO-10646-UCS-4")) { if (isBigEndian != null) { boolean isBE = isBigEndian.booleanValue(); if (isBE) { return new UCSReader(inputStream, UCSReader.UCS4BE); } else { return new UCSReader(inputStream, UCSReader.UCS4LE); } } else { err.jspError("jsp.error.xml.encodingByteOrderUnsupported", encoding); } } if (ENCODING.equals("ISO-10646-UCS-2")) { if (isBigEndian != null) { // sould never happen with this encoding... boolean isBE = isBigEndian.booleanValue(); if (isBE) { return new UCSReader(inputStream, UCSReader.UCS2BE); } else { return new UCSReader(inputStream, UCSReader.UCS2LE); } } else { err.jspError("jsp.error.xml.encodingByteOrderUnsupported", encoding); } } // check for valid name boolean validIANA = XMLChar.isValidIANAEncoding(encoding); boolean validJava = XMLChar.isValidJavaEncoding(encoding); if (!validIANA || (fAllowJavaEncodings && !validJava)) { err.jspError("jsp.error.xml.encodingDeclInvalid", encoding); // NOTE: AndyH suggested that, on failure, we use ISO Latin 1 // because every byte is a valid ISO Latin 1 character. // It may not translate correctly but if we failed on // the encoding anyway, then we're expecting the content // of the document to be bad. This will just prevent an // invalid UTF-8 sequence to be detected. This is only // important when continue-after-fatal-error is turned // on. -Ac encoding = "ISO-8859-1"; } // try to use a Java reader String javaEncoding = EncodingMap.getIANA2JavaMapping(ENCODING); if (javaEncoding == null) { if (fAllowJavaEncodings) { javaEncoding = encoding; } else { err.jspError("jsp.error.xml.encodingDeclInvalid", encoding); // see comment above. javaEncoding = "ISO8859_1"; } } return new InputStreamReader(inputStream, javaEncoding); }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanXMLDecl() throws IOException, JasperException { if (skipString("<?xml")) { // NOTE: special case where document starts with a PI // whose name starts with "xml" (e.g. "xmlfoo") if (XMLChar.isName(peekChar())) { fStringBuffer.clear(); fStringBuffer.append("xml"); while (XMLChar.isName(peekChar())) { fStringBuffer.append((char)scanChar()); } String target = fSymbolTable.addSymbol(fStringBuffer.ch, fStringBuffer.offset, fStringBuffer.length); scanPIData(target, fString); } // standard XML declaration else { scanXMLDeclOrTextDecl(false); } } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanXMLDeclOrTextDecl(boolean scanningTextDecl) throws IOException, JasperException { // scan decl scanXMLDeclOrTextDecl(scanningTextDecl, fStrings); // pseudo-attribute values String encodingPseudoAttr = fStrings[1]; // set encoding on reader if (encodingPseudoAttr != null) { isEncodingSetInProlog = true; encoding = encodingPseudoAttr; } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanXMLDeclOrTextDecl(boolean scanningTextDecl, String[] pseudoAttributeValues) throws IOException, JasperException { // pseudo-attribute values String version = null; String encoding = null; String standalone = null; // scan pseudo-attributes final int STATE_VERSION = 0; final int STATE_ENCODING = 1; final int STATE_STANDALONE = 2; final int STATE_DONE = 3; int state = STATE_VERSION; boolean dataFoundForTarget = false; boolean sawSpace = skipSpaces(); while (peekChar() != '?') { dataFoundForTarget = true; String name = scanPseudoAttribute(scanningTextDecl, fString); switch (state) { case STATE_VERSION: { if (name == fVersionSymbol) { if (!sawSpace) { reportFatalError(scanningTextDecl ? "jsp.error.xml.spaceRequiredBeforeVersionInTextDecl" : "jsp.error.xml.spaceRequiredBeforeVersionInXMLDecl", null); } version = fString.toString(); state = STATE_ENCODING; if (!version.equals("1.0")) { // REVISIT: XML REC says we should throw an error // in such cases. // some may object the throwing of fatalError. err.jspError("jsp.error.xml.versionNotSupported", version); } } else if (name == fEncodingSymbol) { if (!scanningTextDecl) { err.jspError("jsp.error.xml.versionInfoRequired"); } if (!sawSpace) { reportFatalError(scanningTextDecl ? "jsp.error.xml.spaceRequiredBeforeEncodingInTextDecl" : "jsp.error.xml.spaceRequiredBeforeEncodingInXMLDecl", null); } encoding = fString.toString(); state = scanningTextDecl ? STATE_DONE : STATE_STANDALONE; } else { if (scanningTextDecl) { err.jspError("jsp.error.xml.encodingDeclRequired"); } else { err.jspError("jsp.error.xml.versionInfoRequired"); } } break; } case STATE_ENCODING: { if (name == fEncodingSymbol) { if (!sawSpace) { reportFatalError(scanningTextDecl ? "jsp.error.xml.spaceRequiredBeforeEncodingInTextDecl" : "jsp.error.xml.spaceRequiredBeforeEncodingInXMLDecl", null); } encoding = fString.toString(); state = scanningTextDecl ? STATE_DONE : STATE_STANDALONE; // TODO: check encoding name; set encoding on // entity scanner } else if (!scanningTextDecl && name == fStandaloneSymbol) { if (!sawSpace) { err.jspError("jsp.error.xml.spaceRequiredBeforeStandalone"); } standalone = fString.toString(); state = STATE_DONE; if (!standalone.equals("yes") && !standalone.equals("no")) { err.jspError("jsp.error.xml.sdDeclInvalid"); } } else { err.jspError("jsp.error.xml.encodingDeclRequired"); } break; } case STATE_STANDALONE: { if (name == fStandaloneSymbol) { if (!sawSpace) { err.jspError("jsp.error.xml.spaceRequiredBeforeStandalone"); } standalone = fString.toString(); state = STATE_DONE; if (!standalone.equals("yes") && !standalone.equals("no")) { err.jspError("jsp.error.xml.sdDeclInvalid"); } } else { err.jspError("jsp.error.xml.encodingDeclRequired"); } break; } default: { err.jspError("jsp.error.xml.noMorePseudoAttributes"); } } sawSpace = skipSpaces(); } // REVISIT: should we remove this error reporting? if (scanningTextDecl && state != STATE_DONE) { err.jspError("jsp.error.xml.morePseudoAttributes"); } // If there is no data in the xml or text decl then we fail to report // error for version or encoding info above. if (scanningTextDecl) { if (!dataFoundForTarget && encoding == null) { err.jspError("jsp.error.xml.encodingDeclRequired"); } } else { if (!dataFoundForTarget && version == null) { err.jspError("jsp.error.xml.versionInfoRequired"); } } // end if (!skipChar('?')) { err.jspError("jsp.error.xml.xmlDeclUnterminated"); } if (!skipChar('>')) { err.jspError("jsp.error.xml.xmlDeclUnterminated"); } // fill in return array pseudoAttributeValues[0] = version; pseudoAttributeValues[1] = encoding; pseudoAttributeValues[2] = standalone; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public String scanPseudoAttribute(boolean scanningTextDecl, XMLString value) throws IOException, JasperException { String name = scanName(); if (name == null) { err.jspError("jsp.error.xml.pseudoAttrNameExpected"); } skipSpaces(); if (!skipChar('=')) { reportFatalError(scanningTextDecl ? "jsp.error.xml.eqRequiredInTextDecl" : "jsp.error.xml.eqRequiredInXMLDecl", name); } skipSpaces(); int quote = peekChar(); if (quote != '\'' && quote != '"') { reportFatalError(scanningTextDecl ? "jsp.error.xml.quoteRequiredInTextDecl" : "jsp.error.xml.quoteRequiredInXMLDecl" , name); } scanChar(); int c = scanLiteral(quote, value); if (c != quote) { fStringBuffer2.clear(); do { fStringBuffer2.append(value); if (c != -1) { if (c == '&' || c == '%' || c == '<' || c == ']') { fStringBuffer2.append((char)scanChar()); } else if (XMLChar.isHighSurrogate(c)) { scanSurrogates(fStringBuffer2); } else if (XMLChar.isInvalid(c)) { String key = scanningTextDecl ? "jsp.error.xml.invalidCharInTextDecl" : "jsp.error.xml.invalidCharInXMLDecl"; reportFatalError(key, Integer.toString(c, 16)); scanChar(); } } c = scanLiteral(quote, value); } while (c != quote); fStringBuffer2.append(value); value.setValues(fStringBuffer2); } if (!skipChar(quote)) { reportFatalError(scanningTextDecl ? "jsp.error.xml.closeQuoteMissingInTextDecl" : "jsp.error.xml.closeQuoteMissingInXMLDecl", name); } // return return name; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanPIData(String target, XMLString data) throws IOException, JasperException { // check target if (target.length() == 3) { char c0 = Character.toLowerCase(target.charAt(0)); char c1 = Character.toLowerCase(target.charAt(1)); char c2 = Character.toLowerCase(target.charAt(2)); if (c0 == 'x' && c1 == 'm' && c2 == 'l') { err.jspError("jsp.error.xml.reservedPITarget"); } } // spaces if (!skipSpaces()) { if (skipString("?>")) { // we found the end, there is no data data.clear(); return; } else { // if there is data there should be some space err.jspError("jsp.error.xml.spaceRequiredInPI"); } } fStringBuffer.clear(); // data if (scanData("?>", fStringBuffer)) { do { int c = peekChar(); if (c != -1) { if (XMLChar.isHighSurrogate(c)) { scanSurrogates(fStringBuffer); } else if (XMLChar.isInvalid(c)) { err.jspError("jsp.error.xml.invalidCharInPI", Integer.toHexString(c)); scanChar(); } } } while (scanData("?>", fStringBuffer)); } data.setValues(fStringBuffer); }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private boolean scanSurrogates(XMLStringBuffer buf) throws IOException, JasperException { int high = scanChar(); int low = peekChar(); if (!XMLChar.isLowSurrogate(low)) { err.jspError("jsp.error.xml.invalidCharInContent", Integer.toString(high, 16)); return false; } scanChar(); // convert surrogates to supplemental character int c = XMLChar.supplemental((char)high, (char)low); // supplemental character must be a valid XML character if (!XMLChar.isValid(c)) { err.jspError("jsp.error.xml.invalidCharInContent", Integer.toString(c, 16)); return false; } // fill in the buffer buf.append((char)high); buf.append((char)low); return true; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void reportFatalError(String msgId, String arg) throws JasperException { err.jspError(msgId, arg); }
// in java/org/apache/jasper/JspC.java
public void setArgs(String[] arg) throws JasperException { args = arg; String tok; dieLevel = NO_DIE_LEVEL; while ((tok = nextArg()) != null) { if (tok.equals(SWITCH_VERBOSE)) { verbose = true; showSuccess = true; listErrors = true; } else if (tok.equals(SWITCH_OUTPUT_DIR)) { tok = nextArg(); setOutputDir( tok ); } else if (tok.equals(SWITCH_PACKAGE_NAME)) { targetPackage = nextArg(); } else if (tok.equals(SWITCH_COMPILE)) { compile=true; } else if (tok.equals(SWITCH_CLASS_NAME)) { targetClassName = nextArg(); } else if (tok.equals(SWITCH_URI_BASE)) { uriBase=nextArg(); } else if (tok.equals(SWITCH_URI_ROOT)) { setUriroot( nextArg()); } else if (tok.equals(SWITCH_FILE_WEBAPP)) { setUriroot( nextArg()); } else if ( tok.equals( SHOW_SUCCESS ) ) { showSuccess = true; } else if ( tok.equals( LIST_ERRORS ) ) { listErrors = true; } else if (tok.equals(SWITCH_WEBAPP_INC)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = INC_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = ALL_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML_ENCODING)) { setWebXmlEncoding(nextArg()); } else if (tok.equals(SWITCH_ADD_WEBAPP_XML_MAPPINGS)) { setAddWebXmlMappings(true); } else if (tok.equals(SWITCH_MAPPED)) { mappedFile = true; } else if (tok.equals(SWITCH_XPOWERED_BY)) { xpoweredBy = true; } else if (tok.equals(SWITCH_TRIM_SPACES)) { setTrimSpaces(true); } else if (tok.equals(SWITCH_CACHE)) { tok = nextArg(); if ("false".equals(tok)) { caching = false; } else { caching = true; } } else if (tok.equals(SWITCH_CLASSPATH)) { setClassPath(nextArg()); } else if (tok.startsWith(SWITCH_DIE)) { try { dieLevel = Integer.parseInt( tok.substring(SWITCH_DIE.length())); } catch (NumberFormatException nfe) { dieLevel = DEFAULT_DIE_LEVEL; } } else if (tok.equals(SWITCH_HELP)) { helpNeeded = true; } else if (tok.equals(SWITCH_POOLING)) { tok = nextArg(); if ("false".equals(tok)) { poolingEnabled = false; } else { poolingEnabled = true; } } else if (tok.equals(SWITCH_ENCODING)) { setJavaEncoding(nextArg()); } else if (tok.equals(SWITCH_SOURCE)) { setCompilerSourceVM(nextArg()); } else if (tok.equals(SWITCH_TARGET)) { setCompilerTargetVM(nextArg()); } else if (tok.equals(SWITCH_SMAP)) { smapSuppressed = false; } else if (tok.equals(SWITCH_DUMP_SMAP)) { smapDumped = true; } else { if (tok.startsWith("-")) { throw new JasperException("Unrecognized option: " + tok + ". Use -help for help."); } if (!fullstop) { argPos--; } // Start treating the rest as JSP Pages break; } } // Add all extra arguments to the list of files while( true ) { String file = nextFile(); if( file==null ) { break; } pages.add( file ); } }
// in java/org/apache/jasper/JspC.java
protected void processFile(String file) throws JasperException { if (log.isDebugEnabled()) { log.debug("Processing file: " + file); } ClassLoader originalClassLoader = null; try { // set up a scratch/output dir if none is provided if (scratchDir == null) { String temp = System.getProperty("java.io.tmpdir"); if (temp == null) { temp = ""; } scratchDir = new File(new File(temp).getAbsolutePath()); } String jspUri=file.replace('\\','/'); JspCompilationContext clctxt = new JspCompilationContext ( jspUri, this, context, null, rctxt ); /* Override the defaults */ if ((targetClassName != null) && (targetClassName.length() > 0)) { clctxt.setServletClassName(targetClassName); targetClassName = null; } if (targetPackage != null) { clctxt.setServletPackageName(targetPackage); } originalClassLoader = Thread.currentThread().getContextClassLoader(); if( loader==null ) { initClassLoader( clctxt ); } Thread.currentThread().setContextClassLoader(loader); clctxt.setClassLoader(loader); clctxt.setClassPath(classPath); Compiler clc = clctxt.createCompiler(); // If compile is set, generate both .java and .class, if // .jsp file is newer than .class file; // Otherwise only generate .java, if .jsp file is newer than // the .java file if( clc.isOutDated(compile) ) { if (log.isDebugEnabled()) { log.debug(jspUri + " is out dated, compiling..."); } clc.compile(compile, true); } // Generate mapping generateWebMapping( file, clctxt ); if ( showSuccess ) { log.info( "Built File: " + file ); } } catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } } catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); } finally { if(originalClassLoader != null) { Thread.currentThread().setContextClassLoader(originalClassLoader); } } }
// in java/org/apache/jasper/JspC.java
public void scanFiles( File base ) throws JasperException { Stack<String> dirs = new Stack<String>(); dirs.push(base.toString()); // Make sure default extensions are always included if ((getExtensions() == null) || (getExtensions().size() < 2)) { addExtension("jsp"); addExtension("jspx"); } while (!dirs.isEmpty()) { String s = dirs.pop(); File f = new File(s); if (f.exists() && f.isDirectory()) { String[] files = f.list(); String ext; for (int i = 0; (files != null) && i < files.length; i++) { File f2 = new File(s, files[i]); if (f2.isDirectory()) { dirs.push(f2.getPath()); } else { String path = f2.getPath(); String uri = path.substring(uriRoot.length()); ext = files[i].substring(files[i].lastIndexOf('.') +1); if (getExtensions().contains(ext) || jspConfig.isJspPage(uri)) { pages.add(path); } } } } }
// in java/org/apache/jasper/JspC.java
public void execute() throws JasperException { if(log.isDebugEnabled()) { log.debug("execute() starting for " + pages.size() + " pages."); } try { if (uriRoot == null) { if( pages.size() == 0 ) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.missingTarget")); } String firstJsp = pages.get( 0 ); File firstJspF = new File( firstJsp ); if (!firstJspF.exists()) { throw new JasperException( Localizer.getMessage("jspc.error.fileDoesNotExist", firstJsp)); } locateUriRoot( firstJspF ); } if (uriRoot == null) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.no_uriroot")); } File uriRootF = new File(uriRoot); if (!uriRootF.isDirectory()) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.uriroot_not_dir")); } if(context == null) { initServletContext(); } // No explicit pages, we'll process all .jsp in the webapp if (pages.size() == 0) { scanFiles(uriRootF); } initWebXml(); Iterator<String> iter = pages.iterator(); while (iter.hasNext()) { String nextjsp = iter.next().toString(); File fjsp = new File(nextjsp); if (!fjsp.isAbsolute()) { fjsp = new File(uriRootF, nextjsp); } if (!fjsp.exists()) { if (log.isWarnEnabled()) { log.warn (Localizer.getMessage ("jspc.error.fileDoesNotExist", fjsp.toString())); } continue; } String s = fjsp.getAbsolutePath(); if (s.startsWith(uriRoot)) { nextjsp = s.substring(uriRoot.length()); } if (nextjsp.startsWith("." + File.separatorChar)) { nextjsp = nextjsp.substring(2); } processFile(nextjsp); } completeWebXml(); if (addWebXmlMappings) { mergeIntoWebXml(); } } catch (IOException ioe) { throw new JasperException(ioe); } catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { rootCause.printStackTrace(); } throw je; } finally { if (loader != null) { LogFactory.release(loader); } } }
(Domain) ServletException 58
              
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doHandlePageException(Throwable t) throws IOException, ServletException { if (errorPageURL != null && !errorPageURL.equals("")) { /* * Set request attributes. Do not set the * javax.servlet.error.exception attribute here (instead, set in the * generated servlet code for the error page) in order to prevent * the ErrorReportValve, which is invoked as part of forwarding the * request to the error page, from throwing it if the response has * not been committed (the response will have been committed if the * error page is a JSP page). */ request.setAttribute(PageContext.EXCEPTION, t); request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, ((HttpServletRequest) request).getRequestURI()); request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, config.getServletName()); try { forward(errorPageURL); } catch (IllegalStateException ise) { include(errorPageURL); } // The error page could be inside an include. Object newException = request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); // t==null means the attribute was not set. if ((newException != null) && (newException == t)) { request.removeAttribute(RequestDispatcher.ERROR_EXCEPTION); } // now clear the error code - to prevent double handling. request.removeAttribute(RequestDispatcher.ERROR_STATUS_CODE); request.removeAttribute(RequestDispatcher.ERROR_REQUEST_URI); request.removeAttribute(RequestDispatcher.ERROR_SERVLET_NAME); request.removeAttribute(PageContext.EXCEPTION); } else { // Otherwise throw the exception wrapped inside a ServletException. // Set the exception as the root cause in the ServletException // to get a stack trace for the real problem if (t instanceof IOException) throw (IOException) t; if (t instanceof ServletException) throw (ServletException) t; if (t instanceof RuntimeException) throw (RuntimeException) t; Throwable rootCause = null; if (t instanceof JspException) { rootCause = ((JspException) t).getCause(); } else if (t instanceof ELException) { rootCause = ((ELException) t).getCause(); } if (rootCause != null) { throw new ServletException(t.getClass().getName() + ": " + t.getMessage(), rootCause); } throw new ServletException(t); } }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public void init(ServletConfig config) throws ServletException { super.init(config); this.config = config; this.context = config.getServletContext(); // Initialize the JSP Runtime Context // Check for a custom Options implementation String engineOptionsName = config.getInitParameter("engineOptionsClass"); if (engineOptionsName != null) { // Instantiate the indicated Options implementation try { ClassLoader loader = Thread.currentThread() .getContextClassLoader(); Class<?> engineOptionsClass = loader.loadClass(engineOptionsName); Class<?>[] ctorSig = { ServletConfig.class, ServletContext.class }; Constructor<?> ctor = engineOptionsClass.getConstructor(ctorSig); Object[] args = { config, context }; options = (Options) ctor.newInstance(args); } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); // Need to localize this. log.warn("Failed to load engineOptionsClass", e); // Use the default Options implementation options = new EmbeddedServletOptions(config, context); } } else { // Use the default Options implementation options = new EmbeddedServletOptions(config, context); } rctxt = new JspRuntimeContext(context, options); if (config.getInitParameter("jspFile") != null) { jspFile = config.getInitParameter("jspFile"); try { if (null == context.getResource(jspFile)) { throw new ServletException("missing jspFile"); } } catch (MalformedURLException e) { throw new ServletException("Can not locate jsp file", e); } try { if (SecurityUtil.isPackageProtectionEnabled()){ AccessController.doPrivileged(new PrivilegedExceptionAction<Object>(){ @Override public Object run() throws IOException, ServletException { serviceJspFile(null, null, jspFile, true); return null; } }); } else { serviceJspFile(null, null, jspFile, true); } } catch (IOException e) { throw new ServletException("Could not precompile jsp: " + jspFile, e); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ServletException) throw (ServletException)t; throw new ServletException("Could not precompile jsp: " + jspFile, e); } }
// in java/org/apache/jasper/servlet/JspServlet.java
boolean preCompile(HttpServletRequest request) throws ServletException { String queryString = request.getQueryString(); if (queryString == null) { return (false); } int start = queryString.indexOf(Constants.PRECOMPILE); if (start < 0) { return (false); } queryString = queryString.substring(start + Constants.PRECOMPILE.length()); if (queryString.length() == 0) { return (true); // ?jsp_precompile } if (queryString.startsWith("&")) { return (true); // ?jsp_precompile&foo=bar... } if (!queryString.startsWith("=")) { return (false); // part of some other name or value } int limit = queryString.length(); int ampersand = queryString.indexOf("&"); if (ampersand > 0) { limit = ampersand; } String value = queryString.substring(1, limit); if (value.equals("true")) { return (true); // ?jsp_precompile=true } else if (value.equals("false")) { // Spec says if jsp_precompile=false, the request should not // be delivered to the JSP page; the easiest way to implement // this is to set the flag to true, and precompile the page anyway. // This still conforms to the spec, since it says the // precompilation request can be ignored. return (true); // ?jsp_precompile=false } else { throw new ServletException("Cannot have request parameter " + Constants.PRECOMPILE + " set to " + value); } }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //jspFile may be configured as an init-param for this servlet instance String jspUri = jspFile; if (jspUri == null) { // JSP specified via <jsp-file> in <servlet> declaration and supplied through //custom servlet container code jspUri = (String) request.getAttribute(Constants.JSP_FILE); } if (jspUri == null) { /* * Check to see if the requested JSP has been the target of a * RequestDispatcher.include() */ jspUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); if (jspUri != null) { /* * Requested JSP has been target of * RequestDispatcher.include(). Its path is assembled from the * relevant javax.servlet.include.* request attributes */ String pathInfo = (String) request.getAttribute( RequestDispatcher.INCLUDE_PATH_INFO); if (pathInfo != null) { jspUri += pathInfo; } } else { /* * Requested JSP has not been the target of a * RequestDispatcher.include(). Reconstruct its path from the * request's getServletPath() and getPathInfo() */ jspUri = request.getServletPath(); String pathInfo = request.getPathInfo(); if (pathInfo != null) { jspUri += pathInfo; } } } if (log.isDebugEnabled()) { log.debug("JspEngine --> " + jspUri); log.debug("\t ServletPath: " + request.getServletPath()); log.debug("\t PathInfo: " + request.getPathInfo()); log.debug("\t RealPath: " + context.getRealPath(jspUri)); log.debug("\t RequestURI: " + request.getRequestURI()); log.debug("\t QueryString: " + request.getQueryString()); } try { boolean precompile = preCompile(request); serviceJspFile(request, response, jspUri, precompile); } catch (RuntimeException e) { throw e; } catch (ServletException e) { throw e; } catch (IOException e) { throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException(e); } }
// in java/org/apache/jasper/servlet/JspServlet.java
private void handleMissingResource(HttpServletRequest request, HttpServletResponse response, String jspUri) throws ServletException, IOException { String includeRequestUri = (String)request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored String msg = Localizer.getMessage("jsp.error.file.not.found",jspUri); // Strictly, filtering this is an application // responsibility but just in case... throw new ServletException(SecurityUtil.filter(msg)); } else { try { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); } catch (IllegalStateException ise) { log.error(Localizer.getMessage("jsp.error.file.not.found", jspUri)); } } return; }
// in java/org/apache/catalina/startup/Tomcat.java
Override public synchronized Servlet loadServlet() throws ServletException { if (singleThreadModel) { Servlet instance; try { instance = existing.getClass().newInstance(); } catch (InstantiationException e) { throw new ServletException(e); } catch (IllegalAccessException e) { throw new ServletException(e); } instance.init(facade); return instance; } else { if (!init) { existing.init(facade); init = true; } return existing; } }
// in java/org/apache/catalina/filters/FilterBase.java
Override public void init(FilterConfig filterConfig) throws ServletException { Enumeration<String> paramNames = filterConfig.getInitParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); if (!IntrospectionUtils.setProperty(this, paramName, filterConfig.getInitParameter(paramName))) { String msg = sm.getString("filterbase.noSuchProperty", paramName, this.getClass().getName()); if (isConfigProblemFatal()) { throw new ServletException(msg); } else { getLogger().warn(msg); } } } }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { for (Enumeration<String> names = filterConfig.getInitParameterNames(); names.hasMoreElements();) { String name = names.nextElement(); String value = filterConfig.getInitParameter(name); try { if (name.startsWith(PARAMETER_EXPIRES_BY_TYPE)) { String contentType = name.substring( PARAMETER_EXPIRES_BY_TYPE.length()).trim(); ExpiresConfiguration expiresConfiguration = parseExpiresConfiguration(value); this.expiresConfigurationByContentType.put(contentType, expiresConfiguration); } else if (name.equalsIgnoreCase(PARAMETER_EXPIRES_DEFAULT)) { ExpiresConfiguration expiresConfiguration = parseExpiresConfiguration(value); this.defaultExpiresConfiguration = expiresConfiguration; } else if (name.equalsIgnoreCase(PARAMETER_EXPIRES_EXCLUDED_RESPONSE_STATUS_CODES)) { this.excludedResponseStatusCodes = commaDelimitedListToIntArray(value); } else { log.warn(sm.getString( "expiresFilter.unknownParameterIgnored", name, value)); } } catch (RuntimeException e) { throw new ServletException(sm.getString( "expiresFilter.exceptionProcessingParameter", name, value), e); } } log.debug(sm.getString("expiresFilter.filterInitialized", this.toString())); }
// in java/org/apache/catalina/websocket/WebSocketServlet.java
private String getWebSocketAccept(String key) throws ServletException { MessageDigest sha1Helper = sha1Helpers.poll(); if (sha1Helper == null) { try { sha1Helper = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new ServletException(e); } } sha1Helper.reset(); sha1Helper.update(key.getBytes(B2CConverter.ISO_8859_1)); String result = Base64.encode(sha1Helper.digest(WS_ACCEPT)); sha1Helpers.add(sha1Helper); return result; }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // mode is flag for HTML or XML output int mode = 0; // if ?XML=true, set the mode to XML if (request.getParameter("XML") != null && request.getParameter("XML").equals("true")) { mode = 1; } StatusTransformer.setContentType(response, mode); PrintWriter writer = response.getWriter(); boolean completeStatus = false; if ((request.getPathInfo() != null) && (request.getPathInfo().equals("/all"))) { completeStatus = true; } // use StatusTransformer to output status Object[] args = new Object[1]; args[0] = request.getContextPath(); StatusTransformer.writeHeader(writer,args,mode); // Body Header Section args = new Object[2]; args[0] = request.getContextPath(); if (completeStatus) { args[1] = sm.getString("statusServlet.complete"); } else { args[1] = sm.getString("statusServlet.title"); } // use StatusTransformer to output status StatusTransformer.writeBody(writer,args,mode); // Manager Section args = new Object[9]; args[0] = sm.getString("htmlManagerServlet.manager"); args[1] = response.encodeURL(request.getContextPath() + "/html/list"); args[2] = sm.getString("htmlManagerServlet.list"); args[3] = response.encodeURL (request.getContextPath() + "/" + sm.getString("htmlManagerServlet.helpHtmlManagerFile")); args[4] = sm.getString("htmlManagerServlet.helpHtmlManager"); args[5] = response.encodeURL (request.getContextPath() + "/" + sm.getString("htmlManagerServlet.helpManagerFile")); args[6] = sm.getString("htmlManagerServlet.helpManager"); if (completeStatus) { args[7] = response.encodeURL (request.getContextPath() + "/status"); args[8] = sm.getString("statusServlet.title"); } else { args[7] = response.encodeURL (request.getContextPath() + "/status/all"); args[8] = sm.getString("statusServlet.complete"); } // use StatusTransformer to output status StatusTransformer.writeManager(writer,args,mode); // Server Header Section args = new Object[9]; args[0] = sm.getString("htmlManagerServlet.serverTitle"); args[1] = sm.getString("htmlManagerServlet.serverVersion"); args[2] = sm.getString("htmlManagerServlet.serverJVMVersion"); args[3] = sm.getString("htmlManagerServlet.serverJVMVendor"); args[4] = sm.getString("htmlManagerServlet.serverOSName"); args[5] = sm.getString("htmlManagerServlet.serverOSVersion"); args[6] = sm.getString("htmlManagerServlet.serverOSArch"); args[7] = sm.getString("htmlManagerServlet.serverHostname"); args[8] = sm.getString("htmlManagerServlet.serverIPAddress"); // use StatusTransformer to output status StatusTransformer.writePageHeading(writer,args,mode); // Server Row Section args = new Object[8]; args[0] = ServerInfo.getServerInfo(); args[1] = System.getProperty("java.runtime.version"); args[2] = System.getProperty("java.vm.vendor"); args[3] = System.getProperty("os.name"); args[4] = System.getProperty("os.version"); args[5] = System.getProperty("os.arch"); try { InetAddress address = InetAddress.getLocalHost(); args[6] = address.getHostName(); args[7] = address.getHostAddress(); } catch (UnknownHostException e) { args[6] = "-"; args[7] = "-"; } // use StatusTransformer to output status StatusTransformer.writeServerInfo(writer, args, mode); try { // Display operating system statistics using APR if available StatusTransformer.writeOSState(writer,mode); // Display virtual machine statistics StatusTransformer.writeVMState(writer,mode); Enumeration<ObjectName> enumeration = threadPools.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); String name = objectName.getKeyProperty("name"); // use StatusTransformer to output status StatusTransformer.writeConnectorState (writer, objectName, name, mBeanServer, globalRequestProcessors, requestProcessors, mode); } if ((request.getPathInfo() != null) && (request.getPathInfo().equals("/all"))) { // Note: Retrieving the full status is much slower // use StatusTransformer to output status StatusTransformer.writeDetailedState (writer, mBeanServer, mode); } } catch (Exception e) { throw new ServletException(e); } // use StatusTransformer to output status StatusTransformer.writeFooter(writer, mode); }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
protected Principal doLogin(Request request, String username, String password) throws ServletException { Principal p = context.getRealm().authenticate(username, password); if (p == null) { throw new ServletException(sm.getString("authenticator.loginFail")); } return p; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override public void init() throws ServletException { if (getServletConfig().getInitParameter("debug") != null) debug = Integer.parseInt(getServletConfig().getInitParameter("debug")); if (getServletConfig().getInitParameter("input") != null) input = Integer.parseInt(getServletConfig().getInitParameter("input")); if (getServletConfig().getInitParameter("output") != null) output = Integer.parseInt(getServletConfig().getInitParameter("output")); listings = Boolean.parseBoolean(getServletConfig().getInitParameter("listings")); if (getServletConfig().getInitParameter("readonly") != null) readOnly = Boolean.parseBoolean(getServletConfig().getInitParameter("readonly")); if (getServletConfig().getInitParameter("sendfileSize") != null) sendfileSize = Integer.parseInt(getServletConfig().getInitParameter("sendfileSize")) * 1024; fileEncoding = getServletConfig().getInitParameter("fileEncoding"); globalXsltFile = getServletConfig().getInitParameter("globalXsltFile"); contextXsltFile = getServletConfig().getInitParameter("contextXsltFile"); localXsltFile = getServletConfig().getInitParameter("localXsltFile"); readmeFile = getServletConfig().getInitParameter("readmeFile"); if (getServletConfig().getInitParameter("useAcceptRanges") != null) useAcceptRanges = Boolean.parseBoolean(getServletConfig().getInitParameter("useAcceptRanges")); // Sanity check on the specified buffer sizes if (input < 256) input = 256; if (output < 256) output = 256; if (debug > 0) { log("DefaultServlet.init: input buffer size=" + input + ", output buffer size=" + output); } // Load the proxy dir context. resources = (ProxyDirContext) getServletContext() .getAttribute(Globals.RESOURCES_ATTR); if (resources == null) { try { resources = (ProxyDirContext) new InitialContext() .lookup(RESOURCES_JNDI_NAME); } catch (NamingException e) { // Failed throw new ServletException("No resources", e); } } if (resources == null) { throw new UnavailableException("No resources"); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream renderXml(String contextPath, CacheEntry cacheEntry, InputStream xsltInputStream) throws IOException, ServletException { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<listing "); sb.append(" contextPath='"); sb.append(contextPath); sb.append("'"); sb.append(" directory='"); sb.append(cacheEntry.name); sb.append("' "); sb.append(" hasParent='").append(!cacheEntry.name.equals("/")); sb.append("'>"); sb.append("<entries>"); try { // Render the directory entries within this directory NamingEnumeration<NameClassPair> enumeration = resources.list(cacheEntry.name); // rewriteUrl(contextPath) is expensive. cache result for later reuse String rewrittenContextPath = rewriteUrl(contextPath); while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String resourceName = ncPair.getName(); String trimmed = resourceName/*.substring(trim)*/; if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF") || trimmed.equalsIgnoreCase(localXsltFile)) continue; if ((cacheEntry.name + trimmed).equals(contextXsltFile)) continue; CacheEntry childCacheEntry = resources.lookupCache(cacheEntry.name + resourceName); if (!childCacheEntry.exists) { continue; } sb.append("<entry"); sb.append(" type='") .append((childCacheEntry.context != null)?"dir":"file") .append("'"); sb.append(" urlPath='") .append(rewrittenContextPath) .append(rewriteUrl(cacheEntry.name + resourceName)) .append((childCacheEntry.context != null)?"/":"") .append("'"); if (childCacheEntry.resource != null) { sb.append(" size='") .append(renderSize(childCacheEntry.attributes.getContentLength())) .append("'"); } sb.append(" date='") .append(childCacheEntry.attributes.getLastModifiedHttp()) .append("'"); sb.append(">"); sb.append(RequestUtil.filter(trimmed)); if (childCacheEntry.context != null) sb.append("/"); sb.append("</entry>"); } } catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); } sb.append("</entries>"); String readme = getReadme(cacheEntry.context); if (readme!=null) { sb.append("<readme><![CDATA["); sb.append(readme); sb.append("]]></readme>"); } sb.append("</listing>"); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Source xmlSource = new StreamSource(new StringReader(sb.toString())); Source xslSource = new StreamSource(xsltInputStream); Transformer transformer = tFactory.newTransformer(xslSource); ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8"); StreamResult out = new StreamResult(osWriter); transformer.transform(xmlSource, out); osWriter.flush(); return (new ByteArrayInputStream(stream.toByteArray())); } catch (TransformerException e) { throw new ServletException("XSL transformer error", e); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream renderHtml(String contextPath, CacheEntry cacheEntry) throws IOException, ServletException { String name = cacheEntry.name; // Prepare a writer to a buffered area ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8"); PrintWriter writer = new PrintWriter(osWriter); StringBuilder sb = new StringBuilder(); // rewriteUrl(contextPath) is expensive. cache result for later reuse String rewrittenContextPath = rewriteUrl(contextPath); // Render the page header sb.append("<html>\r\n"); sb.append("<head>\r\n"); sb.append("<title>"); sb.append(sm.getString("directory.title", name)); sb.append("</title>\r\n"); sb.append("<STYLE><!--"); sb.append(org.apache.catalina.util.TomcatCSS.TOMCAT_CSS); sb.append("--></STYLE> "); sb.append("</head>\r\n"); sb.append("<body>"); sb.append("<h1>"); sb.append(sm.getString("directory.title", name)); // Render the link to our parent (if required) String parentDirectory = name; if (parentDirectory.endsWith("/")) { parentDirectory = parentDirectory.substring(0, parentDirectory.length() - 1); } int slash = parentDirectory.lastIndexOf('/'); if (slash >= 0) { String parent = name.substring(0, slash); sb.append(" - <a href=\""); sb.append(rewrittenContextPath); if (parent.equals("")) parent = "/"; sb.append(rewriteUrl(parent)); if (!parent.endsWith("/")) sb.append("/"); sb.append("\">"); sb.append("<b>"); sb.append(sm.getString("directory.parent", parent)); sb.append("</b>"); sb.append("</a>"); } sb.append("</h1>"); sb.append("<HR size=\"1\" noshade=\"noshade\">"); sb.append("<table width=\"100%\" cellspacing=\"0\"" + " cellpadding=\"5\" align=\"center\">\r\n"); // Render the column headings sb.append("<tr>\r\n"); sb.append("<td align=\"left\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.filename")); sb.append("</strong></font></td>\r\n"); sb.append("<td align=\"center\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.size")); sb.append("</strong></font></td>\r\n"); sb.append("<td align=\"right\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.lastModified")); sb.append("</strong></font></td>\r\n"); sb.append("</tr>"); try { // Render the directory entries within this directory NamingEnumeration<NameClassPair> enumeration = resources.list(cacheEntry.name); boolean shade = false; while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String resourceName = ncPair.getName(); String trimmed = resourceName/*.substring(trim)*/; if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF")) continue; CacheEntry childCacheEntry = resources.lookupCache(cacheEntry.name + resourceName); if (!childCacheEntry.exists) { continue; } sb.append("<tr"); if (shade) sb.append(" bgcolor=\"#eeeeee\""); sb.append(">\r\n"); shade = !shade; sb.append("<td align=\"left\">&nbsp;&nbsp;\r\n"); sb.append("<a href=\""); sb.append(rewrittenContextPath); resourceName = rewriteUrl(name + resourceName); sb.append(resourceName); if (childCacheEntry.context != null) sb.append("/"); sb.append("\"><tt>"); sb.append(RequestUtil.filter(trimmed)); if (childCacheEntry.context != null) sb.append("/"); sb.append("</tt></a></td>\r\n"); sb.append("<td align=\"right\"><tt>"); if (childCacheEntry.context != null) sb.append("&nbsp;"); else sb.append(renderSize(childCacheEntry.attributes.getContentLength())); sb.append("</tt></td>\r\n"); sb.append("<td align=\"right\"><tt>"); sb.append(childCacheEntry.attributes.getLastModifiedHttp()); sb.append("</tt></td>\r\n"); sb.append("</tr>\r\n"); } } catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); } // Render the page footer sb.append("</table>\r\n"); sb.append("<HR size=\"1\" noshade=\"noshade\">"); String readme = getReadme(cacheEntry.context); if (readme!=null) { sb.append(readme); sb.append("<HR size=\"1\" noshade=\"noshade\">"); } sb.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>"); sb.append("</body>\r\n"); sb.append("</html>\r\n"); // Return an input stream to the underlying bytes writer.write(sb.toString()); writer.flush(); return (new ByteArrayInputStream(stream.toByteArray())); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected DocumentBuilder getDocumentBuilder() throws ServletException { DocumentBuilder documentBuilder = null; DocumentBuilderFactory documentBuilderFactory = null; try { documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setExpandEntityReferences(false); documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setEntityResolver( new WebdavResolver(this.getServletContext())); } catch(ParserConfigurationException e) { throw new ServletException (sm.getString("webdavservlet.jaxpfailed")); } return documentBuilder; }
// in java/org/apache/catalina/connector/Request.java
Override public void login(String username, String password) throws ServletException { if (getAuthType() != null || getRemoteUser() != null || getUserPrincipal() != null) { throw new ServletException( sm.getString("coyoteRequest.alreadyAuthenticated")); } if (context.getAuthenticator() == null) { throw new ServletException("no authenticator"); } context.getAuthenticator().login(username, password, this); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; try { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<Void>() { @Override public Void run() throws ServletException, IOException { internalDoFilter(req,res); return null; } } ); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
private void internalDoFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { // Call the next filter if there is one if (pos < n) { ApplicationFilterConfig filterConfig = filters[pos++]; Filter filter = null; try { filter = filterConfig.getFilter(); support.fireInstanceEvent(InstanceEvent.BEFORE_FILTER_EVENT, filter, request, response); if (request.isAsyncSupported() && "false".equalsIgnoreCase( filterConfig.getFilterDef().getAsyncSupported())) { request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE); } if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; Principal principal = ((HttpServletRequest) req).getUserPrincipal(); Object[] args = new Object[]{req, res, this}; SecurityUtil.doAsPrivilege ("doFilter", filter, classType, args, principal); } else { filter.doFilter(request, response, this); } support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response); } catch (IOException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (ServletException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (RuntimeException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); } return; } // We fell off the end of the chain -- call the servlet instance try { if (ApplicationDispatcher.WRAP_SAME_OBJECT) { lastServicedRequest.set(request); lastServicedResponse.set(response); } support.fireInstanceEvent(InstanceEvent.BEFORE_SERVICE_EVENT, servlet, request, response); if (request.isAsyncSupported() && !support.getWrapper().isAsyncSupported()) { request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE); } // Use potentially wrapped request from this point if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) { if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; Principal principal = ((HttpServletRequest) req).getUserPrincipal(); Object[] args = new Object[]{req, res}; SecurityUtil.doAsPrivilege("service", servlet, classTypeUsedInService, args, principal); } else { servlet.service(request, response); } } else { servlet.service(request, response); } support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response); } catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); } finally { if (ApplicationDispatcher.WRAP_SAME_OBJECT) { lastServicedRequest.set(null); lastServicedResponse.set(null); } } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public void doFilterEvent(CometEvent event) throws IOException, ServletException { if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; try { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<Void>() { @Override public Void run() throws ServletException, IOException { internalDoFilterEvent(ev); return null; } } ); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
private void internalDoFilterEvent(CometEvent event) throws IOException, ServletException { // Call the next filter if there is one if (pos < n) { ApplicationFilterConfig filterConfig = filters[pos++]; CometFilter filter = null; try { filter = (CometFilter) filterConfig.getFilter(); // FIXME: No instance listener processing for events for now /* support.fireInstanceEvent(InstanceEvent.BEFORE_FILTER_EVENT, filter, event); */ if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; Principal principal = ev.getHttpServletRequest().getUserPrincipal(); Object[] args = new Object[]{ev, this}; SecurityUtil.doAsPrivilege("doFilterEvent", filter, cometClassType, args, principal); } else { filter.doFilterEvent(event, this); } /*support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event);*/ } catch (IOException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (ServletException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (RuntimeException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); } return; } // We fell off the end of the chain -- call the servlet instance try { /* support.fireInstanceEvent(InstanceEvent.BEFORE_SERVICE_EVENT, servlet, request, response); */ if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; Principal principal = ev.getHttpServletRequest().getUserPrincipal(); Object[] args = new Object[]{ ev }; SecurityUtil.doAsPrivilege("event", servlet, classTypeUsedInEvent, args, principal); } else { ((CometProcessor) servlet).event(event); } /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response);*/ } catch (IOException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (ServletException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (RuntimeException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw new ServletException (sm.getString("filterChain.servlet"), e); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends Filter> T createFilter(Class<T> c) throws ServletException { try { @SuppressWarnings("unchecked") T filter = (T) context.getInstanceManager().newInstance(c.getName()); return filter; } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends Servlet> T createServlet(Class<T> c) throws ServletException { try { @SuppressWarnings("unchecked") T servlet = (T) context.getInstanceManager().newInstance(c.getName()); context.dynamicServletCreated(servlet); return servlet; } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends EventListener> T createListener(Class<T> c) throws ServletException { try { @SuppressWarnings("unchecked") T listener = (T) context.getInstanceManager().newInstance(c.getName()); if (listener instanceof ServletContextListener || listener instanceof ServletContextAttributeListener || listener instanceof ServletRequestListener || listener instanceof ServletRequestAttributeListener || listener instanceof HttpSessionListener || listener instanceof HttpSessionAttributeListener) { return listener; } throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", listener.getClass().getName())); } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } }
// in java/org/apache/catalina/core/AsyncContextImpl.java
protected void doInternalDispatch() throws ServletException, IOException { if (log.isDebugEnabled()) { logDebug("intDispatch"); } try { dispatch.run(); if (!request.isAsync()) { fireOnComplete(); } } catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); } }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public Servlet allocate() throws ServletException { // If we are currently unloading this servlet, throw an exception if (unloading) throw new ServletException (sm.getString("standardWrapper.unloading", getName())); boolean newInstance = false; // If not SingleThreadedModel, return the same instance every time if (!singleThreadModel) { // Load and initialize our instance if necessary if (instance == null) { synchronized (this) { if (instance == null) { try { if (log.isDebugEnabled()) log.debug("Allocating non-STM instance"); instance = loadServlet(); if (!singleThreadModel) { // For non-STM, increment here to prevent a race // condition with unload. Bug 43683, test case // #3 newInstance = true; countAllocated.incrementAndGet(); } } catch (ServletException e) { throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); } } } } if (!instanceInitialized) { initServlet(instance); } if (singleThreadModel) { if (newInstance) { // Have to do this outside of the sync above to prevent a // possible deadlock synchronized (instancePool) { instancePool.push(instance); nInstances++; } } } else { if (log.isTraceEnabled()) log.trace(" Returning non-STM instance"); // For new instances, count will have been incremented at the // time of creation if (!newInstance) { countAllocated.incrementAndGet(); } return (instance); } } synchronized (instancePool) { while (countAllocated.get() >= nInstances) { // Allocate a new instance if possible, or else wait if (nInstances < maxInstances) { try { instancePool.push(loadServlet()); nInstances++; } catch (ServletException e) { throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); } } else { try { instancePool.wait(); } catch (InterruptedException e) { // Ignore } } } if (log.isTraceEnabled()) log.trace(" Returning allocated STM instance"); countAllocated.incrementAndGet(); return instancePool.pop(); } }
// in java/org/apache/catalina/core/StandardWrapper.java
public synchronized Servlet loadServlet() throws ServletException { // Nothing to do if we already have an instance or an instance pool if (!singleThreadModel && (instance != null)) return instance; PrintStream out = System.out; if (swallowOutput) { SystemLogHandler.startCapture(); } Servlet servlet; try { long t1=System.currentTimeMillis(); // Complain if no servlet class has been specified if (servletClass == null) { unavailable(null); throw new ServletException (sm.getString("standardWrapper.notClass", getName())); } InstanceManager instanceManager = ((StandardContext)getParent()).getInstanceManager(); try { servlet = (Servlet) instanceManager.newInstance(servletClass); } catch (ClassCastException e) { unavailable(null); // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.notServlet", servletClass), e); } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); } if (multipartConfigElement == null) { MultipartConfig annotation = servlet.getClass().getAnnotation(MultipartConfig.class); if (annotation != null) { multipartConfigElement = new MultipartConfigElement(annotation); } } processServletSecurityAnnotation(servlet.getClass()); // Special handling for ContainerServlet instances if ((servlet instanceof ContainerServlet) && (isContainerProvidedServlet(servletClass) || ((Context) getParent()).getPrivileged() )) { ((ContainerServlet) servlet).setWrapper(this); } classLoadTime=(int) (System.currentTimeMillis() -t1); if (servlet instanceof SingleThreadModel) { if (instancePool == null) { instancePool = new Stack<Servlet>(); } singleThreadModel = true; } initServlet(servlet); fireContainerEvent("load", this); loadTime=System.currentTimeMillis() -t1; } finally { if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } } return servlet; }
// in java/org/apache/catalina/core/StandardWrapper.java
private synchronized void initServlet(Servlet servlet) throws ServletException { if (instanceInitialized && !singleThreadModel) return; // Call the initialization method of this servlet try { instanceSupport.fireInstanceEvent(InstanceEvent.BEFORE_INIT_EVENT, servlet); if( Globals.IS_SECURITY_ENABLED) { Object[] args = new Object[]{(facade)}; SecurityUtil.doAsPrivilege("init", servlet, classType, args); args = null; } else { servlet.init(facade); } instanceInitialized = true; instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet); } catch (UnavailableException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); unavailable(f); throw f; } catch (ServletException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw f; } catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); } }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public synchronized void unload() throws ServletException { // Nothing to do if we have never loaded the instance if (!singleThreadModel && (instance == null)) return; unloading = true; // Loaf a while if the current instance is allocated // (possibly more than once if non-STM) if (countAllocated.get() > 0) { int nRetries = 0; long delay = unloadDelay / 20; while ((nRetries < 21) && (countAllocated.get() > 0)) { if ((nRetries % 10) == 0) { log.info(sm.getString("standardWrapper.waiting", countAllocated.toString())); } try { Thread.sleep(delay); } catch (InterruptedException e) { // Ignore } nRetries++; } } if (instanceInitialized) { PrintStream out = System.out; if (swallowOutput) { SystemLogHandler.startCapture(); } // Call the servlet destroy() method try { instanceSupport.fireInstanceEvent (InstanceEvent.BEFORE_DESTROY_EVENT, instance); if( Globals.IS_SECURITY_ENABLED) { SecurityUtil.doAsPrivilege("destroy", instance); SecurityUtil.remove(instance); } else { instance.destroy(); } instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance); // Annotation processing if (!((Context) getParent()).getIgnoreAnnotations()) { ((StandardContext)getParent()).getInstanceManager().destroyInstance(instance); } } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); } finally { // Write captured output if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } } } // Deregister the destroyed instance instance = null; if (isJspServlet && jspMonitorON != null ) { Registry.getRegistry(null, null).unregisterComponent(jspMonitorON); } if (singleThreadModel && (instancePool != null)) { try { while (!instancePool.isEmpty()) { Servlet s = instancePool.pop(); if (Globals.IS_SECURITY_ENABLED) { SecurityUtil.doAsPrivilege("destroy", s); SecurityUtil.remove(instance); } else { s.destroy(); } // Annotation processing if (!((Context) getParent()).getIgnoreAnnotations()) { ((StandardContext)getParent()).getInstanceManager().destroyInstance(s); } } } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); } instancePool = null; nInstances = 0; } singleThreadModel = false; unloading = false; fireContainerEvent("unload", this); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void checkSameObjects(ServletRequest appRequest, ServletResponse appResponse) throws ServletException { ServletRequest originalRequest = ApplicationFilterChain.getLastServicedRequest(); ServletResponse originalResponse = ApplicationFilterChain.getLastServicedResponse(); // Some forwards, eg from valves will not set original values if (originalRequest == null || originalResponse == null) { return; } boolean same = false; ServletRequest dispatchedRequest = appRequest; //find the request that was passed into the service method while (originalRequest instanceof ServletRequestWrapper && ((ServletRequestWrapper) originalRequest).getRequest()!=null ) { originalRequest = ((ServletRequestWrapper) originalRequest).getRequest(); } //compare with the dispatched request while (!same) { if (originalRequest.equals(dispatchedRequest)) { same = true; } if (!same && dispatchedRequest instanceof ServletRequestWrapper) { dispatchedRequest = ((ServletRequestWrapper) dispatchedRequest).getRequest(); } else { break; } } if (!same) { throw new ServletException(sm.getString( "applicationDispatcher.specViolation.request")); } same = false; ServletResponse dispatchedResponse = appResponse; //find the response that was passed into the service method while (originalResponse instanceof ServletResponseWrapper && ((ServletResponseWrapper) originalResponse).getResponse() != null ) { originalResponse = ((ServletResponseWrapper) originalResponse).getResponse(); } //compare with the dispatched response while (!same) { if (originalResponse.equals(dispatchedResponse)) { same = true; } if (!same && dispatchedResponse instanceof ServletResponseWrapper) { dispatchedResponse = ((ServletResponseWrapper) dispatchedResponse).getResponse(); } else { break; } } if (!same) { throw new ServletException(sm.getString( "applicationDispatcher.specViolation.response")); } }
// in java/org/apache/catalina/security/SecurityUtil.java
private static void execute(final Method method, final Object targetObject, final Object[] targetArguments, Principal principal) throws java.lang.Exception{ try{ Subject subject = null; PrivilegedExceptionAction<Void> pea = new PrivilegedExceptionAction<Void>(){ @Override public Void run() throws Exception{ method.invoke(targetObject, targetArguments); return null; } }; // The first argument is always the request object if (targetArguments != null && targetArguments[0] instanceof HttpServletRequest){ HttpServletRequest request = (HttpServletRequest)targetArguments[0]; boolean hasSubject = false; HttpSession session = request.getSession(false); if (session != null){ subject = (Subject)session.getAttribute(Globals.SUBJECT_ATTR); hasSubject = (subject != null); } if (subject == null){ subject = new Subject(); if (principal != null){ subject.getPrincipals().add(principal); } } if (session != null && !hasSubject) { session.setAttribute(Globals.SUBJECT_ATTR, subject); } } Subject.doAsPrivileged(subject, pea, null); } catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/javax/servlet/http/HttpServlet.java
Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request; HttpServletResponse response; try { request = (HttpServletRequest) req; response = (HttpServletResponse) res; } catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); } service(request, response); }
45
              
// in java/org/apache/jasper/servlet/JspServlet.java
catch (MalformedURLException e) { throw new ServletException("Can not locate jsp file", e); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IOException e) { throw new ServletException("Could not precompile jsp: " + jspFile, e); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ServletException) throw (ServletException)t; throw new ServletException("Could not precompile jsp: " + jspFile, e); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException(e); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (RuntimeException e) { throw new ServletException(sm.getString( "expiresFilter.exceptionProcessingParameter", name, value), e); }
// in java/org/apache/catalina/websocket/WebSocketServlet.java
catch (NoSuchAlgorithmException e) { throw new ServletException(e); }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
catch (Exception e) { throw new ServletException(e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Failed throw new ServletException("No resources", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (TransformerException e) { throw new ServletException("XSL transformer error", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch(ParserConfigurationException e) { throw new ServletException (sm.getString("webdavservlet.jaxpfailed")); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ClassCastException e) { unavailable(null); // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.notServlet", servletClass), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/security/SecurityUtil.java
catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/javax/servlet/http/HttpServlet.java
catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); }
189
              
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void forward(String relativeUrlPath) throws ServletException, IOException { invokingJspCtxt.forward(relativeUrlPath); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void include(String relativeUrlPath) throws ServletException, IOException { invokingJspCtxt.include(relativeUrlPath); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void include(String relativeUrlPath, boolean flush) throws ServletException, IOException { invokingJspCtxt.include(relativeUrlPath, false); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void handlePageException(Exception ex) throws IOException, ServletException { // Should never be called since handleException() called with a // Throwable in the generated servlet. handlePageException((Throwable) ex); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void handlePageException(Throwable t) throws IOException, ServletException { invokingJspCtxt.handlePageException(t); }
// in java/org/apache/jasper/runtime/HttpJspBase.java
Override public final void init(ServletConfig config) throws ServletException { super.init(config); jspInit(); _jspInit(); }
// in java/org/apache/jasper/runtime/HttpJspBase.java
Override public final void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { _jspService(request, response); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void include(String relativeUrlPath) throws ServletException, IOException { JspRuntimeLibrary .include(request, response, relativeUrlPath, out, true); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void include(final String relativeUrlPath, final boolean flush) throws ServletException, IOException { if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doInclude(relativeUrlPath, flush); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doInclude(String relativeUrlPath, boolean flush) throws ServletException, IOException { JspRuntimeLibrary.include(request, response, relativeUrlPath, out, flush); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void forward(final String relativeUrlPath) throws ServletException, IOException { if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doForward(relativeUrlPath); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doForward(String relativeUrlPath) throws ServletException, IOException { // JSP.4.5 If the buffer was flushed, throw IllegalStateException try { out.clear(); } catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer .getMessage("jsp.error.attempt_to_clear_flushed_buffer")); ise.initCause(ex); throw ise; } // Make sure that the response object is not the wrapper for include while (response instanceof ServletResponseWrapperInclude) { response = ((ServletResponseWrapperInclude) response).getResponse(); } final String path = getAbsolutePathRelativeToContext(relativeUrlPath); String includeUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); if (includeUri != null) request.removeAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH); try { context.getRequestDispatcher(path).forward(request, response); } finally { if (includeUri != null) request.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH, includeUri); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void handlePageException(Exception ex) throws IOException, ServletException { // Should never be called since handleException() called with a // Throwable in the generated servlet. handlePageException((Throwable) ex); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void handlePageException(final Throwable t) throws IOException, ServletException { if (t == null) throw new NullPointerException("null Throwable"); if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doHandlePageException(t); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doHandlePageException(Throwable t) throws IOException, ServletException { if (errorPageURL != null && !errorPageURL.equals("")) { /* * Set request attributes. Do not set the * javax.servlet.error.exception attribute here (instead, set in the * generated servlet code for the error page) in order to prevent * the ErrorReportValve, which is invoked as part of forwarding the * request to the error page, from throwing it if the response has * not been committed (the response will have been committed if the * error page is a JSP page). */ request.setAttribute(PageContext.EXCEPTION, t); request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, ((HttpServletRequest) request).getRequestURI()); request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, config.getServletName()); try { forward(errorPageURL); } catch (IllegalStateException ise) { include(errorPageURL); } // The error page could be inside an include. Object newException = request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); // t==null means the attribute was not set. if ((newException != null) && (newException == t)) { request.removeAttribute(RequestDispatcher.ERROR_EXCEPTION); } // now clear the error code - to prevent double handling. request.removeAttribute(RequestDispatcher.ERROR_STATUS_CODE); request.removeAttribute(RequestDispatcher.ERROR_REQUEST_URI); request.removeAttribute(RequestDispatcher.ERROR_SERVLET_NAME); request.removeAttribute(PageContext.EXCEPTION); } else { // Otherwise throw the exception wrapped inside a ServletException. // Set the exception as the root cause in the ServletException // to get a stack trace for the real problem if (t instanceof IOException) throw (IOException) t; if (t instanceof ServletException) throw (ServletException) t; if (t instanceof RuntimeException) throw (RuntimeException) t; Throwable rootCause = null; if (t instanceof JspException) { rootCause = ((JspException) t).getCause(); } else if (t instanceof ELException) { rootCause = ((ELException) t).getCause(); } if (rootCause != null) { throw new ServletException(t.getClass().getName() + ": " + t.getMessage(), rootCause); } throw new ServletException(t); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void include(ServletRequest request, ServletResponse response, String relativePath, JspWriter out, boolean flush) throws IOException, ServletException { if (flush && !(out instanceof BodyContent)) out.flush(); // FIXME - It is tempting to use request.getRequestDispatcher() to // resolve a relative path directly, but Catalina currently does not // take into account whether the caller is inside a RequestDispatcher // include or not. Whether Catalina *should* take that into account // is a spec issue currently under review. In the mean time, // replicate Jasper's previous behavior String resourcePath = getContextRelativePath(request, relativePath); RequestDispatcher rd = request.getRequestDispatcher(resourcePath); rd.include(request, new ServletResponseWrapperInclude(response, out)); }
// in java/org/apache/jasper/servlet/JspCServletContext.java
Override public <T extends Filter> T createFilter(Class<T> c) throws ServletException { return null; }
// in java/org/apache/jasper/servlet/JspCServletContext.java
Override public <T extends Servlet> T createServlet(Class<T> c) throws ServletException { return null; }
// in java/org/apache/jasper/servlet/JspCServletContext.java
Override public <T extends EventListener> T createListener(Class<T> c) throws ServletException { return null; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public Servlet getServlet() throws ServletException { // DCL on 'reload' requires that 'reload' be volatile // (this also forces a read memory barrier, ensuring the // new servlet object is read consistently) if (reload) { synchronized (this) { // Synchronizing on jsw enables simultaneous loading // of different pages, but not the same page. if (reload) { // This is to maintain the original protocol. destroy(); final Servlet servlet; try { InstanceManager instanceManager = InstanceManagerFactory.getInstanceManager(config); servlet = (Servlet) instanceManager.newInstance(ctxt.getFQCN(), ctxt.getJspLoader()); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JasperException(t); } servlet.init(config); if (!firstTime) { ctxt.getRuntimeContext().incrementJspReloadCount(); } theServlet = servlet; reload = false; // Volatile 'reload' forces in order write of 'theServlet' and new servlet object } } } return theServlet; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile) throws ServletException, IOException, FileNotFoundException { Servlet servlet; try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if ((available > 0L) && (available < Long.MAX_VALUE)) { if (available > System.currentTimeMillis()) { response.setDateHeader("Retry-After", available); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, Localizer.getMessage("jsp.error.unavailable")); return; } // Wait period has expired. Reset. available = 0; } /* * (1) Compile */ if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; // The following sets reload to true, if necessary ctxt.compile(); } } else { if (compileException != null) { // Throw cached compilation exception throw compileException; } } /* * (2) (Re)load servlet class file */ servlet = getServlet(); // If a page is to be precompiled only, return. if (precompile) { return; } } catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; } catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } try { /* * (3) Handle limitation of number of loaded Jsps */ if (unloadAllowed) { synchronized(this) { if (unloadByCount) { if (unloadHandle == null) { unloadHandle = ctxt.getRuntimeContext().push(this); } else if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { ctxt.getRuntimeContext().makeYoungest(unloadHandle); lastUsageTime = System.currentTimeMillis(); } } else { if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { lastUsageTime = System.currentTimeMillis(); } } } } /* * (4) Service request */ if (servlet instanceof SingleThreadModel) { // sync on the wrapper so that the freshness // of the page is determined right before servicing synchronized (this) { servlet.service(request, response); } } else { servlet.service(request, response); } } catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); } catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public void init(ServletConfig config) throws ServletException { super.init(config); this.config = config; this.context = config.getServletContext(); // Initialize the JSP Runtime Context // Check for a custom Options implementation String engineOptionsName = config.getInitParameter("engineOptionsClass"); if (engineOptionsName != null) { // Instantiate the indicated Options implementation try { ClassLoader loader = Thread.currentThread() .getContextClassLoader(); Class<?> engineOptionsClass = loader.loadClass(engineOptionsName); Class<?>[] ctorSig = { ServletConfig.class, ServletContext.class }; Constructor<?> ctor = engineOptionsClass.getConstructor(ctorSig); Object[] args = { config, context }; options = (Options) ctor.newInstance(args); } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); // Need to localize this. log.warn("Failed to load engineOptionsClass", e); // Use the default Options implementation options = new EmbeddedServletOptions(config, context); } } else { // Use the default Options implementation options = new EmbeddedServletOptions(config, context); } rctxt = new JspRuntimeContext(context, options); if (config.getInitParameter("jspFile") != null) { jspFile = config.getInitParameter("jspFile"); try { if (null == context.getResource(jspFile)) { throw new ServletException("missing jspFile"); } } catch (MalformedURLException e) { throw new ServletException("Can not locate jsp file", e); } try { if (SecurityUtil.isPackageProtectionEnabled()){ AccessController.doPrivileged(new PrivilegedExceptionAction<Object>(){ @Override public Object run() throws IOException, ServletException { serviceJspFile(null, null, jspFile, true); return null; } }); } else { serviceJspFile(null, null, jspFile, true); } } catch (IOException e) { throw new ServletException("Could not precompile jsp: " + jspFile, e); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ServletException) throw (ServletException)t; throw new ServletException("Could not precompile jsp: " + jspFile, e); } }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public Object run() throws IOException, ServletException { serviceJspFile(null, null, jspFile, true); return null; }
// in java/org/apache/jasper/servlet/JspServlet.java
boolean preCompile(HttpServletRequest request) throws ServletException { String queryString = request.getQueryString(); if (queryString == null) { return (false); } int start = queryString.indexOf(Constants.PRECOMPILE); if (start < 0) { return (false); } queryString = queryString.substring(start + Constants.PRECOMPILE.length()); if (queryString.length() == 0) { return (true); // ?jsp_precompile } if (queryString.startsWith("&")) { return (true); // ?jsp_precompile&foo=bar... } if (!queryString.startsWith("=")) { return (false); // part of some other name or value } int limit = queryString.length(); int ampersand = queryString.indexOf("&"); if (ampersand > 0) { limit = ampersand; } String value = queryString.substring(1, limit); if (value.equals("true")) { return (true); // ?jsp_precompile=true } else if (value.equals("false")) { // Spec says if jsp_precompile=false, the request should not // be delivered to the JSP page; the easiest way to implement // this is to set the flag to true, and precompile the page anyway. // This still conforms to the spec, since it says the // precompilation request can be ignored. return (true); // ?jsp_precompile=false } else { throw new ServletException("Cannot have request parameter " + Constants.PRECOMPILE + " set to " + value); } }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //jspFile may be configured as an init-param for this servlet instance String jspUri = jspFile; if (jspUri == null) { // JSP specified via <jsp-file> in <servlet> declaration and supplied through //custom servlet container code jspUri = (String) request.getAttribute(Constants.JSP_FILE); } if (jspUri == null) { /* * Check to see if the requested JSP has been the target of a * RequestDispatcher.include() */ jspUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); if (jspUri != null) { /* * Requested JSP has been target of * RequestDispatcher.include(). Its path is assembled from the * relevant javax.servlet.include.* request attributes */ String pathInfo = (String) request.getAttribute( RequestDispatcher.INCLUDE_PATH_INFO); if (pathInfo != null) { jspUri += pathInfo; } } else { /* * Requested JSP has not been the target of a * RequestDispatcher.include(). Reconstruct its path from the * request's getServletPath() and getPathInfo() */ jspUri = request.getServletPath(); String pathInfo = request.getPathInfo(); if (pathInfo != null) { jspUri += pathInfo; } } } if (log.isDebugEnabled()) { log.debug("JspEngine --> " + jspUri); log.debug("\t ServletPath: " + request.getServletPath()); log.debug("\t PathInfo: " + request.getPathInfo()); log.debug("\t RealPath: " + context.getRealPath(jspUri)); log.debug("\t RequestURI: " + request.getRequestURI()); log.debug("\t QueryString: " + request.getQueryString()); } try { boolean precompile = preCompile(request); serviceJspFile(request, response, jspUri, precompile); } catch (RuntimeException e) { throw e; } catch (ServletException e) { throw e; } catch (IOException e) { throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException(e); } }
// in java/org/apache/jasper/servlet/JspServlet.java
private void serviceJspFile(HttpServletRequest request, HttpServletResponse response, String jspUri, boolean precompile) throws ServletException, IOException { JspServletWrapper wrapper = rctxt.getWrapper(jspUri); if (wrapper == null) { synchronized(this) { wrapper = rctxt.getWrapper(jspUri); if (wrapper == null) { // Check if the requested JSP page exists, to avoid // creating unnecessary directories and files. if (null == context.getResource(jspUri)) { handleMissingResource(request, response, jspUri); return; } wrapper = new JspServletWrapper(config, options, jspUri, rctxt); rctxt.addWrapper(jspUri,wrapper); } } } try { wrapper.service(request, response, precompile); } catch (FileNotFoundException fnfe) { handleMissingResource(request, response, jspUri); } }
// in java/org/apache/jasper/servlet/JspServlet.java
private void handleMissingResource(HttpServletRequest request, HttpServletResponse response, String jspUri) throws ServletException, IOException { String includeRequestUri = (String)request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored String msg = Localizer.getMessage("jsp.error.file.not.found",jspUri); // Strictly, filtering this is an application // responsibility but just in case... throw new ServletException(SecurityUtil.filter(msg)); } else { try { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); } catch (IllegalStateException ise) { log.error(Localizer.getMessage("jsp.error.file.not.found", jspUri)); } } return; }
// in java/org/apache/catalina/startup/Tomcat.java
public Context addWebapp(String contextPath, String baseDir) throws ServletException { return addWebapp(getHost(), contextPath, baseDir); }
// in java/org/apache/catalina/startup/Tomcat.java
Override public synchronized Servlet loadServlet() throws ServletException { if (singleThreadModel) { Servlet instance; try { instance = existing.getClass().newInstance(); } catch (InstantiationException e) { throw new ServletException(e); } catch (IllegalAccessException e) { throw new ServletException(e); } instance.init(facade); return instance; } else { if (!init) { existing.init(facade); init = true; } return existing; } }
// in java/org/apache/catalina/filters/SetCharacterEncodingFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Conditionally select and set the character encoding to be used if (ignore || (request.getCharacterEncoding() == null)) { String characterEncoding = selectEncoding(request); if (characterEncoding != null) { request.setCharacterEncoding(characterEncoding); } } // Pass control on to the next filter chain.doFilter(request, response); }
// in java/org/apache/catalina/filters/FilterBase.java
Override public void init(FilterConfig filterConfig) throws ServletException { Enumeration<String> paramNames = filterConfig.getInitParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); if (!IntrospectionUtils.setProperty(this, paramName, filterConfig.getInitParameter(paramName))) { String msg = sm.getString("filterbase.noSuchProperty", paramName, this.getClass().getName()); if (isConfigProblemFatal()) { throw new ServletException(msg); } else { getLogger().warn(msg); } } } }
// in java/org/apache/catalina/filters/RequestDumperFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest hRequest = null; HttpServletResponse hResponse = null; if (request instanceof HttpServletRequest) { hRequest = (HttpServletRequest) request; } if (response instanceof HttpServletResponse) { hResponse = (HttpServletResponse) response; } // Log pre-service information doLog("START TIME ", getTimestamp()); if (hRequest == null) { doLog(" requestURI", NON_HTTP_REQ_MSG); doLog(" authType", NON_HTTP_REQ_MSG); } else { doLog(" requestURI", hRequest.getRequestURI()); doLog(" authType", hRequest.getAuthType()); } doLog(" characterEncoding", request.getCharacterEncoding()); doLog(" contentLength", Integer.valueOf(request.getContentLength()).toString()); doLog(" contentType", request.getContentType()); if (hRequest == null) { doLog(" contextPath", NON_HTTP_REQ_MSG); doLog(" cookie", NON_HTTP_REQ_MSG); doLog(" header", NON_HTTP_REQ_MSG); } else { doLog(" contextPath", hRequest.getContextPath()); Cookie cookies[] = hRequest.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { doLog(" cookie", cookies[i].getName() + "=" + cookies[i].getValue()); } } Enumeration<String> hnames = hRequest.getHeaderNames(); while (hnames.hasMoreElements()) { String hname = hnames.nextElement(); Enumeration<String> hvalues = hRequest.getHeaders(hname); while (hvalues.hasMoreElements()) { String hvalue = hvalues.nextElement(); doLog(" header", hname + "=" + hvalue); } } } doLog(" locale", request.getLocale().toString()); if (hRequest == null) { doLog(" method", NON_HTTP_REQ_MSG); } else { doLog(" method", hRequest.getMethod()); } Enumeration<String> pnames = request.getParameterNames(); while (pnames.hasMoreElements()) { String pname = pnames.nextElement(); String pvalues[] = request.getParameterValues(pname); StringBuilder result = new StringBuilder(pname); result.append('='); for (int i = 0; i < pvalues.length; i++) { if (i > 0) { result.append(", "); } result.append(pvalues[i]); } doLog(" parameter", result.toString()); } if (hRequest == null) { doLog(" pathInfo", NON_HTTP_REQ_MSG); } else { doLog(" pathInfo", hRequest.getPathInfo()); } doLog(" protocol", request.getProtocol()); if (hRequest == null) { doLog(" queryString", NON_HTTP_REQ_MSG); } else { doLog(" queryString", hRequest.getQueryString()); } doLog(" remoteAddr", request.getRemoteAddr()); doLog(" remoteHost", request.getRemoteHost()); if (hRequest == null) { doLog(" remoteUser", NON_HTTP_REQ_MSG); doLog("requestedSessionId", NON_HTTP_REQ_MSG); } else { doLog(" remoteUser", hRequest.getRemoteUser()); doLog("requestedSessionId", hRequest.getRequestedSessionId()); } doLog(" scheme", request.getScheme()); doLog(" serverName", request.getServerName()); doLog(" serverPort", Integer.valueOf(request.getServerPort()).toString()); if (hRequest == null) { doLog(" servletPath", NON_HTTP_REQ_MSG); } else { doLog(" servletPath", hRequest.getServletPath()); } doLog(" isSecure", Boolean.valueOf(request.isSecure()).toString()); doLog("------------------", "--------------------------------------------"); // Perform the request chain.doFilter(request, response); // Log post-service information doLog("------------------", "--------------------------------------------"); if (hRequest == null) { doLog(" authType", NON_HTTP_REQ_MSG); } else { doLog(" authType", hRequest.getAuthType()); } doLog(" contentType", response.getContentType()); if (hResponse == null) { doLog(" header", NON_HTTP_RES_MSG); } else { Iterable<String> rhnames = hResponse.getHeaderNames(); for (String rhname : rhnames) { Iterable<String> rhvalues = hResponse.getHeaders(rhname); for (String rhvalue : rhvalues) { doLog(" header", rhname + "=" + rhvalue); } } } if (hRequest == null) { doLog(" remoteUser", NON_HTTP_REQ_MSG); } else { doLog(" remoteUser", hRequest.getRemoteUser()); } if (hResponse == null) { doLog(" remoteUser", NON_HTTP_RES_MSG); } else { doLog(" status", Integer.valueOf(hResponse.getStatus()).toString()); } doLog("END TIME ", getTimestamp()); doLog("==================", "============================================"); }
// in java/org/apache/catalina/filters/RequestDumperFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { // NOOP }
// in java/org/apache/catalina/filters/RequestFilter.java
protected void process(String property, ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (isAllowed(property)) { chain.doFilter(request, response); } else { if (response instanceof HttpServletResponse) { ((HttpServletResponse) response).sendError(denyStatus); } else { sendErrorWhenNotHttp(response); } } }
// in java/org/apache/catalina/filters/RequestFilter.java
protected void processCometEvent(String property, CometEvent event, CometFilterChain chain) throws IOException, ServletException { HttpServletResponse response = event.getHttpServletResponse(); if (isAllowed(property)) { chain.doFilterEvent(event); } else { response.sendError(denyStatus); event.close(); } }
// in java/org/apache/catalina/filters/AddDefaultCharsetFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { super.init(filterConfig); if (encoding == null || encoding.length() == 0 || encoding.equalsIgnoreCase("default")) { encoding = DEFAULT_ENCODING; } else if (encoding.equalsIgnoreCase("system")) { encoding = Charset.defaultCharset().name(); } else if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException(sm.getString( "addDefaultCharset.unsupportedCharset", encoding)); } }
// in java/org/apache/catalina/filters/AddDefaultCharsetFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Wrap the response if (response instanceof HttpServletResponse) { ResponseWrapper wrapped = new ResponseWrapper((HttpServletResponse)response, encoding); chain.doFilter(request, wrapped); } else { chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/RemoteHostFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { process(request.getRemoteHost(), request, response, chain); }
// in java/org/apache/catalina/filters/RemoteHostFilter.java
Override public void doFilterEvent(CometEvent event, CometFilterChain chain) throws IOException, ServletException { processCometEvent(event.getHttpServletRequest().getRemoteHost(), event, chain); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (response.isCommitted()) { if (log.isDebugEnabled()) { log.debug(sm.getString( "expiresFilter.responseAlreadyCommited", httpRequest.getRequestURL())); } chain.doFilter(request, response); } else { XHttpServletResponse xResponse = new XHttpServletResponse( httpRequest, httpResponse); chain.doFilter(request, xResponse); if (!xResponse.isWriteResponseBodyStarted()) { // Empty response, manually trigger // onBeforeWriteResponseBody() onBeforeWriteResponseBody(httpRequest, xResponse); } } } else { chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { for (Enumeration<String> names = filterConfig.getInitParameterNames(); names.hasMoreElements();) { String name = names.nextElement(); String value = filterConfig.getInitParameter(name); try { if (name.startsWith(PARAMETER_EXPIRES_BY_TYPE)) { String contentType = name.substring( PARAMETER_EXPIRES_BY_TYPE.length()).trim(); ExpiresConfiguration expiresConfiguration = parseExpiresConfiguration(value); this.expiresConfigurationByContentType.put(contentType, expiresConfiguration); } else if (name.equalsIgnoreCase(PARAMETER_EXPIRES_DEFAULT)) { ExpiresConfiguration expiresConfiguration = parseExpiresConfiguration(value); this.defaultExpiresConfiguration = expiresConfiguration; } else if (name.equalsIgnoreCase(PARAMETER_EXPIRES_EXCLUDED_RESPONSE_STATUS_CODES)) { this.excludedResponseStatusCodes = commaDelimitedListToIntArray(value); } else { log.warn(sm.getString( "expiresFilter.unknownParameterIgnored", name, value)); } } catch (RuntimeException e) { throw new ServletException(sm.getString( "expiresFilter.exceptionProcessingParameter", name, value), e); } } log.debug(sm.getString("expiresFilter.filterInitialized", this.toString())); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (internalProxies != null && internalProxies.matcher(request.getRemoteAddr()).matches()) { String remoteIp = null; // In java 6, proxiesHeaderValue should be declared as a java.util.Deque LinkedList<String> proxiesHeaderValue = new LinkedList<String>(); StringBuilder concatRemoteIpHeaderValue = new StringBuilder(); for (Enumeration<String> e = request.getHeaders(remoteIpHeader); e.hasMoreElements();) { if (concatRemoteIpHeaderValue.length() > 0) { concatRemoteIpHeaderValue.append(", "); } concatRemoteIpHeaderValue.append(e.nextElement()); } String[] remoteIpHeaderValue = commaDelimitedListToStringArray(concatRemoteIpHeaderValue.toString()); int idx; // loop on remoteIpHeaderValue to find the first trusted remote ip and to build the proxies chain for (idx = remoteIpHeaderValue.length - 1; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; remoteIp = currentRemoteIp; if (internalProxies.matcher(currentRemoteIp).matches()) { // do nothing, internalProxies IPs are not appended to the } else if (trustedProxies != null && trustedProxies.matcher(currentRemoteIp).matches()) { proxiesHeaderValue.addFirst(currentRemoteIp); } else { idx--; // decrement idx because break statement doesn't do it break; } } // continue to loop on remoteIpHeaderValue to build the new value of the remoteIpHeader LinkedList<String> newRemoteIpHeaderValue = new LinkedList<String>(); for (; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; newRemoteIpHeaderValue.addFirst(currentRemoteIp); } XForwardedRequest xRequest = new XForwardedRequest(request); if (remoteIp != null) { xRequest.setRemoteAddr(remoteIp); xRequest.setRemoteHost(remoteIp); if (proxiesHeaderValue.size() == 0) { xRequest.removeHeader(proxiesHeader); } else { String commaDelimitedListOfProxies = listToCommaDelimitedString(proxiesHeaderValue); xRequest.setHeader(proxiesHeader, commaDelimitedListOfProxies); } if (newRemoteIpHeaderValue.size() == 0) { xRequest.removeHeader(remoteIpHeader); } else { String commaDelimitedRemoteIpHeaderValue = listToCommaDelimitedString(newRemoteIpHeaderValue); xRequest.setHeader(remoteIpHeader, commaDelimitedRemoteIpHeaderValue); } } if (protocolHeader != null) { String protocolHeaderValue = request.getHeader(protocolHeader); if (protocolHeaderValue == null) { // don't modify the secure,scheme and serverPort attributes of the request } else if (protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue)) { xRequest.setSecure(true); xRequest.setScheme("https"); setPorts(xRequest, httpsServerPort); } else { xRequest.setSecure(false); xRequest.setScheme("http"); setPorts(xRequest, httpServerPort); } } if (log.isDebugEnabled()) { log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "', originalRemoteHost='" + request.getRemoteHost() + "', originalSecure='" + request.isSecure() + "', originalScheme='" + request.getScheme() + "', original[" + remoteIpHeader + "]='" + concatRemoteIpHeaderValue + "', original[" + protocolHeader + "]='" + (protocolHeader == null ? null : request.getHeader(protocolHeader)) + "' will be seen as newRemoteAddr='" + xRequest.getRemoteAddr() + "', newRemoteHost='" + xRequest.getRemoteHost() + "', newScheme='" + xRequest.getScheme() + "', newSecure='" + xRequest.isSecure() + "', new[" + remoteIpHeader + "]='" + xRequest.getHeader(remoteIpHeader) + "', new[" + proxiesHeader + "]='" + xRequest.getHeader(proxiesHeader) + "'"); } if (requestAttributesEnabled) { request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE, request.getRemoteAddr()); request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE, request.getRemoteHost()); request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE, request.getProtocol()); request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE, Integer.valueOf(request.getServerPort())); } chain.doFilter(xRequest, response); } else { if (log.isDebugEnabled()) { log.debug("Skip RemoteIpFilter for request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "'"); } chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { doFilter((HttpServletRequest)request, (HttpServletResponse)response, chain); } else { chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { if (filterConfig.getInitParameter(INTERNAL_PROXIES_PARAMETER) != null) { setInternalProxies(filterConfig.getInitParameter(INTERNAL_PROXIES_PARAMETER)); } if (filterConfig.getInitParameter(PROTOCOL_HEADER_PARAMETER) != null) { setProtocolHeader(filterConfig.getInitParameter(PROTOCOL_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER) != null) { setProtocolHeaderHttpsValue(filterConfig.getInitParameter(PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER)); } if (filterConfig.getInitParameter(PORT_HEADER_PARAMETER) != null) { setPortHeader(filterConfig.getInitParameter(PORT_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(CHANGE_LOCAL_PORT_PARAMETER) != null) { setChangeLocalPort(Boolean.parseBoolean(filterConfig.getInitParameter(CHANGE_LOCAL_PORT_PARAMETER))); } if (filterConfig.getInitParameter(PROXIES_HEADER_PARAMETER) != null) { setProxiesHeader(filterConfig.getInitParameter(PROXIES_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(REMOTE_IP_HEADER_PARAMETER) != null) { setRemoteIpHeader(filterConfig.getInitParameter(REMOTE_IP_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(TRUSTED_PROXIES_PARAMETER) != null) { setTrustedProxies(filterConfig.getInitParameter(TRUSTED_PROXIES_PARAMETER)); } if (filterConfig.getInitParameter(HTTP_SERVER_PORT_PARAMETER) != null) { try { setHttpServerPort(Integer.parseInt(filterConfig.getInitParameter(HTTP_SERVER_PORT_PARAMETER))); } catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTP_SERVER_PORT_PARAMETER + " : " + e.getMessage()); } } if (filterConfig.getInitParameter(HTTPS_SERVER_PORT_PARAMETER) != null) { try { setHttpsServerPort(Integer.parseInt(filterConfig.getInitParameter(HTTPS_SERVER_PORT_PARAMETER))); } catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTPS_SERVER_PORT_PARAMETER + " : " + e.getMessage()); } } }
// in java/org/apache/catalina/filters/WebdavFixFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { // NOOP }
// in java/org/apache/catalina/filters/WebdavFixFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { chain.doFilter(request, response); return; } HttpServletRequest httpRequest = ((HttpServletRequest) request); HttpServletResponse httpResponse = ((HttpServletResponse) response); String ua = httpRequest.getHeader("User-Agent"); if (ua == null || ua.length() == 0 || !ua.startsWith(UA_MINIDIR_START)) { // No UA or starts with non MS value // Hope everything just works... chain.doFilter(request, response); } else if (ua.startsWith(UA_MINIDIR_5_1_2600)) { // XP 32-bit SP3 - needs redirect with explicit port httpResponse.sendRedirect(buildRedirect(httpRequest)); } else if (ua.startsWith(UA_MINIDIR_5_2_3790)) { // XP 64-bit SP2 if (!"".equals(httpRequest.getContextPath())) { log(request, "XP-x64-SP2 clients only work with the root context"); } // Namespace issue maybe // see http://greenbytes.de/tech/webdav/webdav-redirector-list.html log(request, "XP-x64-SP2 is known not to work with WebDAV Servlet"); chain.doFilter(request, response); } else { // Don't know which MS client it is - try the redirect with an // explicit port in the hope that it moves the client to a different // WebDAV implementation that works httpResponse.sendRedirect(buildRedirect(httpRequest)); } }
// in java/org/apache/catalina/filters/RemoteAddrFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { process(request.getRemoteAddr(), request, response, chain); }
// in java/org/apache/catalina/filters/RemoteAddrFilter.java
Override public void doFilterEvent(CometEvent event, CometFilterChain chain) throws IOException, ServletException { processCometEvent(event.getHttpServletRequest().getRemoteAddr(), event, chain); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { // Set the parameters super.init(filterConfig); try { Class<?> clazz = Class.forName(randomClass); randomSource = (Random) clazz.newInstance(); } catch (ClassNotFoundException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; } catch (InstantiationException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; } catch (IllegalAccessException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; } }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ServletResponse wResponse = null; if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; boolean skipNonceCheck = false; if (Constants.METHOD_GET.equals(req.getMethod())) { String path = req.getServletPath(); if (req.getPathInfo() != null) { path = path + req.getPathInfo(); } if (entryPoints.contains(path)) { skipNonceCheck = true; } } @SuppressWarnings("unchecked") LruCache<String> nonceCache = (LruCache<String>) req.getSession(true).getAttribute( Constants.CSRF_NONCE_SESSION_ATTR_NAME); if (!skipNonceCheck) { String previousNonce = req.getParameter(Constants.CSRF_NONCE_REQUEST_PARAM); if (nonceCache != null && !nonceCache.contains(previousNonce)) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } if (nonceCache == null) { nonceCache = new LruCache<String>(nonceCacheSize); req.getSession().setAttribute( Constants.CSRF_NONCE_SESSION_ATTR_NAME, nonceCache); } String newNonce = generateNonce(); nonceCache.add(newNonce); wResponse = new CsrfResponseWrapper(res, newNonce); } else { wResponse = response; } chain.doFilter(request, wResponse); }
// in java/org/apache/catalina/filters/FailedRequestFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!isGoodRequest(request)) { ((HttpServletResponse) response) .sendError(HttpServletResponse.SC_BAD_REQUEST); return; } chain.doFilter(request, response); }
// in java/org/apache/catalina/filters/FailedRequestFilter.java
Override public void doFilterEvent(CometEvent event, CometFilterChain chain) throws IOException, ServletException { if (event.getEventType() == CometEvent.EventType.BEGIN && !isGoodRequest(event.getHttpServletRequest())) { event.getHttpServletResponse().sendError( HttpServletResponse.SC_BAD_REQUEST); event.close(); return; } chain.doFilterEvent(event); }
// in java/org/apache/catalina/websocket/WebSocketServlet.java
Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Information required to send the server handshake message String key; String subProtocol = null; List<String> extensions = Collections.emptyList(); if (!headerContainsToken(req, "upgrade", "websocket")) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (!headerContainsToken(req, "connection", "upgrade")) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (!headerContainsToken(req, "sec-websocket-version", "13")) { resp.setStatus(426); resp.setHeader("Sec-WebSocket-Version", "13"); return; } key = req.getHeader("Sec-WebSocket-Key"); if (key == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } String origin = req.getHeader("Origin"); if (!verifyOrigin(origin)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } List<String> subProtocols = getTokensFromHeader(req, "Sec-WebSocket-Protocol-Client"); if (!subProtocols.isEmpty()) { subProtocol = selectSubProtocol(subProtocols); } // TODO Read client handshake - Sec-WebSocket-Extensions // TODO Extensions require the ability to specify something (API TBD) // that can be passed to the Tomcat internals and process extension // data present when the frame is fragmented. // If we got this far, all is good. Accept the connection. resp.setHeader("Upgrade", "websocket"); resp.setHeader("Connection", "upgrade"); resp.setHeader("Sec-WebSocket-Accept", getWebSocketAccept(key)); if (subProtocol != null) { resp.setHeader("Sec-WebSocket-Protocol", subProtocol); } if (!extensions.isEmpty()) { // TODO } // Small hack until the Servlet API provides a way to do this. StreamInbound inbound = createWebSocketInbound(subProtocol); ((RequestFacade) req).doUpgrade(inbound); }
// in java/org/apache/catalina/websocket/WebSocketServlet.java
private String getWebSocketAccept(String key) throws ServletException { MessageDigest sha1Helper = sha1Helpers.poll(); if (sha1Helper == null) { try { sha1Helper = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new ServletException(e); } } sha1Helper.reset(); sha1Helper.update(key.getBytes(B2CConverter.ISO_8859_1)); String result = Base64.encode(sha1Helper.digest(WS_ACCEPT)); sha1Helpers.add(sha1Helper); return result; }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need // By obtaining the command from the pathInfo, per-command security can // be configured in web.xml String command = request.getPathInfo(); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Process the requested command if (command == null || command.equals("/")) { // No command == list } else if (command.equals("/list")) { // List always displayed - nothing to do here } else if (command.equals("/sessions")) { try { doSessions(cn, request, response, smClient); return; } catch (Exception e) { log("HTMLManagerServlet.sessions[" + cn + "]", e); message = smClient.getString("managerServlet.exception", e.toString()); } } else if (command.equals("/upload") || command.equals("/deploy") || command.equals("/reload") || command.equals("/undeploy") || command.equals("/expire") || command.equals("/start") || command.equals("/stop")) { message = smClient.getString("managerServlet.postCommand", command); } else { message = smClient.getString("managerServlet.unknownCommand", command); } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need // By obtaining the command from the pathInfo, per-command security can // be configured in web.xml String command = request.getPathInfo(); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } String deployPath = request.getParameter("deployPath"); ContextName deployCn = null; if (deployPath != null) { deployCn = new ContextName(deployPath, request.getParameter("deployVersion")); } String deployConfig = request.getParameter("deployConfig"); String deployWar = request.getParameter("deployWar"); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; if (command == null || command.length() == 0) { // No command == list // List always displayed -> do nothing } else if (command.equals("/upload")) { message = upload(request, smClient); } else if (command.equals("/deploy")) { message = deployInternal(deployConfig, deployCn, deployWar, smClient); } else if (command.equals("/reload")) { message = reload(cn, smClient); } else if (command.equals("/undeploy")) { message = undeploy(cn, smClient); } else if (command.equals("/expire")) { message = expireSessions(cn, request, smClient); } else if (command.equals("/start")) { message = start(cn, smClient); } else if (command.equals("/stop")) { message = stop(cn, smClient); } else if (command.equals("/findleaks")) { message = findleaks(smClient); } else { // Try GET doGet(request,response); return; } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected String upload(HttpServletRequest request, StringManager smClient) throws IOException, ServletException { String message = ""; Part warPart = null; String filename = null; Collection<Part> parts = request.getParts(); Iterator<Part> iter = parts.iterator(); try { while (iter.hasNext()) { Part part = iter.next(); if (part.getName().equals("deployWar") && warPart == null) { warPart = part; } else { part.delete(); } } while (true) { if (warPart == null) { message = smClient.getString( "htmlManagerServlet.deployUploadNoFile"); break; } filename = extractFilename(warPart.getHeader("Content-Disposition")); if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) { message = smClient.getString( "htmlManagerServlet.deployUploadNotWar", filename); break; } // Get the filename if uploaded name includes a path if (filename.lastIndexOf('\\') >= 0) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (filename.lastIndexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } // Identify the appBase of the owning Host of this Context // (if any) File file = new File(host.getAppBaseFile(), filename); if (file.exists()) { message = smClient.getString( "htmlManagerServlet.deployUploadWarExists", filename); break; } ContextName cn = new ContextName(filename); String name = cn.getName(); if ((host.findChild(name) != null) && !isDeployed(name)) { message = smClient.getString( "htmlManagerServlet.deployUploadInServerXml", filename); break; } if (!isServiced(name)) { addServiced(name); try { warPart.write(file.getAbsolutePath()); // Perform new deployment check(name); } finally { removeServiced(name); } } break; } } catch(Exception e) { message = smClient.getString ("htmlManagerServlet.deployUploadFail", e.getMessage()); log(message, e); } finally { if (warPart != null) { warPart.delete(); } warPart = null; } return message; }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
Override public void init() throws ServletException { super.init(); // Set our properties from the initialization parameters String value = null; value = getServletConfig().getInitParameter("showProxySessions"); showProxySessions = Boolean.parseBoolean(value); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected void doSessions(ContextName cn, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { req.setAttribute("path", cn.getPath()); req.setAttribute("version", cn.getVersion()); String action = req.getParameter("action"); if (debug >= 1) { log("sessions: Session action '" + action + "' for web application '" + cn.getDisplayName() + "'"); } if ("sessionDetail".equals(action)) { String sessionId = req.getParameter("sessionId"); displaySessionDetailPage(req, resp, cn, sessionId, smClient); return; } else if ("invalidateSessions".equals(action)) { String[] sessionIds = req.getParameterValues("sessionIds"); int i = invalidateSessions(cn, sessionIds, smClient); req.setAttribute(APPLICATION_MESSAGE, "" + i + " sessions invalidated."); } else if ("removeSessionAttribute".equals(action)) { String sessionId = req.getParameter("sessionId"); String name = req.getParameter("attributeName"); boolean removed = removeSessionAttribute(cn, sessionId, name, smClient); String outMessage = removed ? "Session attribute '" + name + "' removed." : "Session did not contain any attribute named '" + name + "'"; req.setAttribute(APPLICATION_MESSAGE, outMessage); displaySessionDetailPage(req, resp, cn, sessionId, smClient); return; } // else displaySessionsListPage(cn, req, resp, smClient); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected void displaySessionsListPage(ContextName cn, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { List<Session> sessions = getSessionsForName(cn, smClient); String sortBy = req.getParameter("sort"); String orderBy = null; if (null != sortBy && !"".equals(sortBy.trim())) { Comparator<Session> comparator = getComparator(sortBy); if (comparator != null) { orderBy = req.getParameter("order"); if ("DESC".equalsIgnoreCase(orderBy)) { comparator = new ReverseComparator(comparator); orderBy = "ASC"; } else { orderBy = "DESC"; } try { Collections.sort(sessions, comparator); } catch (IllegalStateException ise) { // at least 1 of the sessions is invalidated req.setAttribute(APPLICATION_ERROR, "Can't sort session list: one session is invalidated"); } } else { log("WARNING: unknown sort order: " + sortBy); } } // keep sort order req.setAttribute("sort", sortBy); req.setAttribute("order", orderBy); req.setAttribute("activeSessions", sessions); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now getServletContext().getRequestDispatcher(sessionsListJspPath).include(req, resp); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected void displaySessionDetailPage(HttpServletRequest req, HttpServletResponse resp, ContextName cn, String sessionId, StringManager smClient) throws ServletException, IOException { Session session = getSessionForNameAndId(cn, sessionId, smClient); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now req.setAttribute("currentSession", session); getServletContext().getRequestDispatcher(resp.encodeURL(sessionDetailJspPath)).include(req, resp); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
Override public void init() throws ServletException { // Retrieve the MBean server registry = Registry.getRegistry(null, null); mBeanServer = Registry.getRegistry(null, null).getMBeanServer(); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); PrintWriter writer = response.getWriter(); if( mBeanServer==null ) { writer.println("Error - No mbean server"); return; } String qry=request.getParameter("set"); if( qry!= null ) { String name=request.getParameter("att"); String val=request.getParameter("val"); setAttribute( writer, qry, name, val ); return; } qry=request.getParameter("get"); if( qry!= null ) { String name=request.getParameter("att"); getAttribute( writer, qry, name, request.getParameter("key") ); return; } qry = request.getParameter("invoke"); if(qry != null) { String opName=request.getParameter("op"); String ps = request.getParameter("ps"); String[] valuesStr; if (ps == null) { valuesStr = new String[0]; } else { valuesStr = ps.split(","); } invokeOperation( writer, qry, opName,valuesStr ); return; } qry=request.getParameter("qry"); if( qry == null ) { qry = "*:*"; } listBeans( writer, qry ); }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null) command = request.getServletPath(); String name = request.getParameter("name"); // Prepare our output writer to generate the response message response.setContentType("text/plain; charset=" + Constants.CHARSET); PrintWriter writer = response.getWriter(); // Process the requested command if (command == null) { writer.println(sm.getString("hostManagerServlet.noCommand")); } else if (command.equals("/add")) { add(request, writer, name, false, smClient); } else if (command.equals("/remove")) { remove(writer, name, smClient); } else if (command.equals("/list")) { list(writer, smClient); } else if (command.equals("/start")) { start(writer, name, smClient); } else if (command.equals("/stop")) { stop(writer, name, smClient); } else { writer.println(sm.getString("hostManagerServlet.unknownCommand", command)); } // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
Override public void init() throws ServletException { // Ensure that our ContainerServlet properties have been set if ((wrapper == null) || (context == null)) throw new UnavailableException (sm.getString("hostManagerServlet.noWrapper")); // Set our properties from the initialization parameters String value = null; try { value = getServletConfig().getInitParameter("debug"); debug = Integer.parseInt(value); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } }
// in java/org/apache/catalina/manager/host/HTMLHostManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Process the requested command if (command == null) { // No command == list } else if (command.equals("/list")) { // Nothing to do - always generate list } else if (command.equals("/add") || command.equals("/remove") || command.equals("/start") || command.equals("/stop")) { message = smClient.getString( "hostManagerServlet.postCommand", command); } else { message = smClient.getString( "hostManagerServlet.unknownCommand", command); } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/host/HTMLHostManagerServlet.java
Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); String name = request.getParameter("name"); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Process the requested command if (command == null) { // No command == list } else if (command.equals("/add")) { message = add(request, name, smClient); } else if (command.equals("/remove")) { message = remove(name, smClient); } else if (command.equals("/start")) { message = start(name, smClient); } else if (command.equals("/stop")) { message = stop(name, smClient); } else { //Try GET doGet(request, response); } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
Override public void init() throws ServletException { // Retrieve the MBean server mBeanServer = Registry.getRegistry(null, null).getMBeanServer(); try { // Query protocol handlers String onStr = "*:type=ProtocolHandler,*"; ObjectName objectName = new ObjectName(onStr); Set<ObjectInstance> set = mBeanServer.queryMBeans(objectName, null); Iterator<ObjectInstance> iterator = set.iterator(); while (iterator.hasNext()) { ObjectInstance oi = iterator.next(); protocolHandlers.addElement(oi.getObjectName()); } // Query Thread Pools onStr = "*:type=ThreadPool,*"; objectName = new ObjectName(onStr); set = mBeanServer.queryMBeans(objectName, null); iterator = set.iterator(); while (iterator.hasNext()) { ObjectInstance oi = iterator.next(); threadPools.addElement(oi.getObjectName()); } // Query Global Request Processors onStr = "*:type=GlobalRequestProcessor,*"; objectName = new ObjectName(onStr); set = mBeanServer.queryMBeans(objectName, null); iterator = set.iterator(); while (iterator.hasNext()) { ObjectInstance oi = iterator.next(); globalRequestProcessors.addElement(oi.getObjectName()); } // Query Request Processors onStr = "*:type=RequestProcessor,*"; objectName = new ObjectName(onStr); set = mBeanServer.queryMBeans(objectName, null); iterator = set.iterator(); while (iterator.hasNext()) { ObjectInstance oi = iterator.next(); requestProcessors.addElement(oi.getObjectName()); } // Register with MBean server onStr = "JMImplementation:type=MBeanServerDelegate"; objectName = new ObjectName(onStr); mBeanServer.addNotificationListener(objectName, this, null, null); } catch (Exception e) { e.printStackTrace(); } }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // mode is flag for HTML or XML output int mode = 0; // if ?XML=true, set the mode to XML if (request.getParameter("XML") != null && request.getParameter("XML").equals("true")) { mode = 1; } StatusTransformer.setContentType(response, mode); PrintWriter writer = response.getWriter(); boolean completeStatus = false; if ((request.getPathInfo() != null) && (request.getPathInfo().equals("/all"))) { completeStatus = true; } // use StatusTransformer to output status Object[] args = new Object[1]; args[0] = request.getContextPath(); StatusTransformer.writeHeader(writer,args,mode); // Body Header Section args = new Object[2]; args[0] = request.getContextPath(); if (completeStatus) { args[1] = sm.getString("statusServlet.complete"); } else { args[1] = sm.getString("statusServlet.title"); } // use StatusTransformer to output status StatusTransformer.writeBody(writer,args,mode); // Manager Section args = new Object[9]; args[0] = sm.getString("htmlManagerServlet.manager"); args[1] = response.encodeURL(request.getContextPath() + "/html/list"); args[2] = sm.getString("htmlManagerServlet.list"); args[3] = response.encodeURL (request.getContextPath() + "/" + sm.getString("htmlManagerServlet.helpHtmlManagerFile")); args[4] = sm.getString("htmlManagerServlet.helpHtmlManager"); args[5] = response.encodeURL (request.getContextPath() + "/" + sm.getString("htmlManagerServlet.helpManagerFile")); args[6] = sm.getString("htmlManagerServlet.helpManager"); if (completeStatus) { args[7] = response.encodeURL (request.getContextPath() + "/status"); args[8] = sm.getString("statusServlet.title"); } else { args[7] = response.encodeURL (request.getContextPath() + "/status/all"); args[8] = sm.getString("statusServlet.complete"); } // use StatusTransformer to output status StatusTransformer.writeManager(writer,args,mode); // Server Header Section args = new Object[9]; args[0] = sm.getString("htmlManagerServlet.serverTitle"); args[1] = sm.getString("htmlManagerServlet.serverVersion"); args[2] = sm.getString("htmlManagerServlet.serverJVMVersion"); args[3] = sm.getString("htmlManagerServlet.serverJVMVendor"); args[4] = sm.getString("htmlManagerServlet.serverOSName"); args[5] = sm.getString("htmlManagerServlet.serverOSVersion"); args[6] = sm.getString("htmlManagerServlet.serverOSArch"); args[7] = sm.getString("htmlManagerServlet.serverHostname"); args[8] = sm.getString("htmlManagerServlet.serverIPAddress"); // use StatusTransformer to output status StatusTransformer.writePageHeading(writer,args,mode); // Server Row Section args = new Object[8]; args[0] = ServerInfo.getServerInfo(); args[1] = System.getProperty("java.runtime.version"); args[2] = System.getProperty("java.vm.vendor"); args[3] = System.getProperty("os.name"); args[4] = System.getProperty("os.version"); args[5] = System.getProperty("os.arch"); try { InetAddress address = InetAddress.getLocalHost(); args[6] = address.getHostName(); args[7] = address.getHostAddress(); } catch (UnknownHostException e) { args[6] = "-"; args[7] = "-"; } // use StatusTransformer to output status StatusTransformer.writeServerInfo(writer, args, mode); try { // Display operating system statistics using APR if available StatusTransformer.writeOSState(writer,mode); // Display virtual machine statistics StatusTransformer.writeVMState(writer,mode); Enumeration<ObjectName> enumeration = threadPools.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); String name = objectName.getKeyProperty("name"); // use StatusTransformer to output status StatusTransformer.writeConnectorState (writer, objectName, name, mBeanServer, globalRequestProcessors, requestProcessors, mode); } if ((request.getPathInfo() != null) && (request.getPathInfo().equals("/all"))) { // Note: Retrieving the full status is much slower // use StatusTransformer to output status StatusTransformer.writeDetailedState (writer, mBeanServer, mode); } } catch (Exception e) { throw new ServletException(e); } // use StatusTransformer to output status StatusTransformer.writeFooter(writer, mode); }
// in java/org/apache/catalina/manager/ManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null) command = request.getServletPath(); String config = request.getParameter("config"); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } String type = request.getParameter("type"); String war = request.getParameter("war"); String tag = request.getParameter("tag"); boolean update = false; if ((request.getParameter("update") != null) && (request.getParameter("update").equals("true"))) { update = true; } boolean statusLine = false; if ("true".equals(request.getParameter("statusLine"))) { statusLine = true; } // Prepare our output writer to generate the response message response.setContentType("text/plain; charset=" + Constants.CHARSET); PrintWriter writer = response.getWriter(); // Process the requested command (note - "/deploy" is not listed here) if (command == null) { writer.println(smClient.getString("managerServlet.noCommand")); } else if (command.equals("/deploy")) { if (war != null || config != null) { deploy(writer, config, cn, war, update, smClient); } else { deploy(writer, cn, tag, smClient); } } else if (command.equals("/list")) { list(writer, smClient); } else if (command.equals("/reload")) { reload(writer, cn, smClient); } else if (command.equals("/resources")) { resources(writer, type, smClient); } else if (command.equals("/save")) { save(writer, path, smClient); } else if (command.equals("/serverinfo")) { serverinfo(writer, smClient); } else if (command.equals("/sessions")) { expireSessions(writer, cn, request, smClient); } else if (command.equals("/expire")) { expireSessions(writer, cn, request, smClient); } else if (command.equals("/start")) { start(writer, cn, smClient); } else if (command.equals("/stop")) { stop(writer, cn, smClient); } else if (command.equals("/undeploy")) { undeploy(writer, cn, smClient); } else if (command.equals("/findleaks")) { findleaks(statusLine, writer, smClient); } else { writer.println(smClient.getString("managerServlet.unknownCommand", command)); } // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
Override public void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null) command = request.getServletPath(); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } String tag = request.getParameter("tag"); boolean update = false; if ((request.getParameter("update") != null) && (request.getParameter("update").equals("true"))) { update = true; } // Prepare our output writer to generate the response message response.setContentType("text/plain;charset="+Constants.CHARSET); PrintWriter writer = response.getWriter(); // Process the requested command if (command == null) { writer.println(smClient.getString("managerServlet.noCommand")); } else if (command.equals("/deploy")) { deploy(writer, cn, tag, update, request, smClient); } else { writer.println(smClient.getString("managerServlet.unknownCommand", command)); } // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
Override public void init() throws ServletException { // Ensure that our ContainerServlet properties have been set if ((wrapper == null) || (context == null)) throw new UnavailableException( sm.getString("managerServlet.noWrapper")); // Set our properties from the initialization parameters String value = null; try { value = getServletConfig().getInitParameter("debug"); debug = Integer.parseInt(value); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } // Acquire global JNDI resources if available Server server = ((Engine)host.getParent()).getService().getServer(); if (server != null) { global = server.getGlobalNamingContext(); } // Calculate the directory into which we will be deploying applications versioned = (File) getServletContext().getAttribute (ServletContext.TEMPDIR); // Identify the appBase of the owning Host of this Context // (if any) deployed = ((Host) context.getParent()).getAppBaseFile(); configBase = new File(context.getCatalinaBase(), "conf"); Container container = context; Container host = null; Container engine = null; while (container != null) { if (container instanceof Host) host = container; if (container instanceof Engine) engine = container; container = container.getParent(); } if (engine != null) { configBase = new File(configBase, engine.getName()); } if (host != null) { configBase = new File(configBase, host.getName()); } // Note: The directory must exist for this to work. // Log debugging messages as necessary if (debug >= 1) { log("init: Associated with Deployer '" + oname + "'"); if (global != null) { log("init: Global resources are available"); } } }
// in java/org/apache/catalina/valves/RequestFilterValve.java
protected void process(String property, Request request, Response response) throws IOException, ServletException { if (isAllowed(property)) { getNext().invoke(request, response); return; } // Deny this request denyRequest(request, response); }
// in java/org/apache/catalina/valves/RequestFilterValve.java
protected void denyRequest(Request request, Response response) throws IOException, ServletException { response.sendError(denyStatus); }
// in java/org/apache/catalina/valves/RemoteHostValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { process(request.getRequest().getRemoteHost(), request, response); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { // Perform the request getNext().invoke(request, response); if (request.isComet() && !response.isClosed()) { // Start tracking this connection, since this is a // begin event, and Comet mode is on HttpSession session = request.getSession(true); // Track the connection for webapp reload cometRequests.add(request); // Track the connection for session expiration synchronized (session) { Request[] requests = (Request[]) session.getAttribute(cometRequestsAttribute); if (requests == null) { requests = new Request[1]; requests[0] = request; session.setAttribute(cometRequestsAttribute, requests); } else { Request[] newRequests = new Request[requests.length + 1]; for (int i = 0; i < requests.length; i++) { newRequests[i] = requests[i]; } newRequests[requests.length] = request; session.setAttribute(cometRequestsAttribute, newRequests); } } } }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
Override public void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Perform the request boolean ok = false; try { getNext().event(request, response, event); ok = true; } finally { if (!ok || response.isClosed() || (event.getEventType() == CometEvent.EventType.END) || (event.getEventType() == CometEvent.EventType.ERROR && !(event.getEventSubType() == CometEvent.EventSubType.TIMEOUT))) { // Remove the connection from webapp reload tracking cometRequests.remove(request); // Remove connection from session expiration tracking // Note: can't get the session if it has been invalidated but // OK since session listener will have done clean-up HttpSession session = request.getSession(false); if (session != null) { synchronized (session) { Request[] reqs = null; try { reqs = (Request[]) session.getAttribute(cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } if (reqs != null) { boolean found = false; for (int i = 0; !found && (i < reqs.length); i++) { found = (reqs[i] == request); } if (found) { if (reqs.length > 1) { Request[] newConnectionInfos = new Request[reqs.length - 1]; int pos = 0; for (int i = 0; i < reqs.length; i++) { if (reqs[i] != request) { newConnectionInfos[pos++] = reqs[i]; } } try { session.setAttribute( cometRequestsAttribute, newConnectionInfos); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } else { try { session.removeAttribute( cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } } } } } } } }
// in java/org/apache/catalina/valves/CrawlerSessionManagerValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { boolean isBot = false; String sessionId = null; String clientIp = null; if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": ClientIp=" + request.getRemoteAddr() + ", RequestedSessionId=" + request.getRequestedSessionId()); } // If the incoming request has a valid session ID, no action is required if (request.getSession(false) == null) { // Is this a crawler - check the UA headers Enumeration<String> uaHeaders = request.getHeaders("user-agent"); String uaHeader = null; if (uaHeaders.hasMoreElements()) { uaHeader = uaHeaders.nextElement(); } // If more than one UA header - assume not a bot if (uaHeader != null && !uaHeaders.hasMoreElements()) { if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": UserAgent=" + uaHeader); } if (uaPattern.matcher(uaHeader).matches()) { isBot = true; if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": Bot found. UserAgent=" + uaHeader); } } } // If this is a bot, is the session ID known? if (isBot) { clientIp = request.getRemoteAddr(); sessionId = clientIpSessionId.get(clientIp); if (sessionId != null) { request.setRequestedSessionId(sessionId); if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": SessionID=" + sessionId); } } } } getNext().invoke(request, response); if (isBot) { if (sessionId == null) { // Has bot just created a session, if so make a note of it HttpSession s = request.getSession(false); if (s != null) { clientIpSessionId.put(clientIp, s.getId()); sessionIdClientIp.put(s.getId(), clientIp); // #valueUnbound() will be called on session expiration s.setAttribute(this.getClass().getName(), this); s.setMaxInactiveInterval(sessionInactiveInterval); if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": New bot session. SessionID=" + s.getId()); } } } else { if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": Bot session accessed. SessionID=" + sessionId); } } } }
// in java/org/apache/catalina/valves/RemoteAddrValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { process(request.getRequest().getRemoteAddr(), request, response); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { getNext().invoke(request, response); }
// in java/org/apache/catalina/valves/StuckThreadDetectionValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (threshold <= 0) { // short-circuit if not monitoring stuck threads getNext().invoke(request, response); return; } // Save the thread/runnable // Keeping a reference to the thread object here does not prevent // GC'ing, as the reference is removed from the Map in the finally clause Long key = Long.valueOf(Thread.currentThread().getId()); StringBuffer requestUrl = request.getRequestURL(); if(request.getQueryString()!=null) { requestUrl.append("?"); requestUrl.append(request.getQueryString()); } MonitoredThread monitoredThread = new MonitoredThread(Thread.currentThread(), requestUrl.toString()); activeThreads.put(key, monitoredThread); try { getNext().invoke(request, response); } finally { activeThreads.remove(key); if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) { completedStuckThreadsQueue.add( new CompletedStuckThread(monitoredThread.getThread().getName(), monitoredThread.getActiveTimeInMillis())); } } }
// in java/org/apache/catalina/valves/SSLValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { /* mod_header converts the '\n' into ' ' so we have to rebuild the client certificate */ String strcert0 = mygetHeader(request, "ssl_client_cert"); if (strcert0 != null && strcert0.length()>28) { String strcert1 = strcert0.replace(' ', '\n'); String strcert2 = strcert1.substring(28, strcert1.length()-26); String strcert3 = "-----BEGIN CERTIFICATE-----\n"; String strcert4 = strcert3.concat(strcert2); String strcerts = strcert4.concat("\n-----END CERTIFICATE-----\n"); // ByteArrayInputStream bais = new ByteArrayInputStream(strcerts.getBytes("UTF-8")); ByteArrayInputStream bais = new ByteArrayInputStream( strcerts.getBytes(B2CConverter.ISO_8859_1)); X509Certificate jsseCerts[] = null; String providerName = (String) request.getConnector().getProperty( "clientCertProvider"); try { CertificateFactory cf; if (providerName == null) { cf = CertificateFactory.getInstance("X.509"); } else { cf = CertificateFactory.getInstance("X.509", providerName); } X509Certificate cert = (X509Certificate) cf.generateCertificate(bais); jsseCerts = new X509Certificate[1]; jsseCerts[0] = cert; } catch (java.security.cert.CertificateException e) { log.warn(sm.getString("sslValve.certError", strcerts), e); } catch (NoSuchProviderException e) { log.error(sm.getString( "sslValve.invalidProvider", providerName), e); } request.setAttribute(Globals.CERTIFICATES_ATTR, jsseCerts); } strcert0 = mygetHeader(request, "ssl_cipher"); if (strcert0 != null) { request.setAttribute(Globals.CIPHER_SUITE_ATTR, strcert0); } strcert0 = mygetHeader(request, "ssl_session_id"); if (strcert0 != null) { request.setAttribute(Globals.SSL_SESSION_ID_ATTR, strcert0); } strcert0 = mygetHeader(request, "ssl_cipher_usekeysize"); if (strcert0 != null) { request.setAttribute(Globals.KEY_SIZE_ATTR, Integer.valueOf(strcert0)); } getNext().invoke(request, response); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { // Perform the request getNext().invoke(request, response); if (response.isCommitted()) { return; } Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); if (request.isAsyncStarted() && response.getStatus() < 400 && throwable == null) { return; } if (throwable != null) { // The response is an error response.setError(); // Reset the response (if possible) try { response.reset(); } catch (IllegalStateException e) { // Ignore } response.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } response.setSuspended(false); try { report(request, response, throwable); } catch (Throwable tt) { ExceptionUtils.handleThrowable(tt); } if (request.isAsyncStarted()) { request.getAsyncContext().complete(); } }
// in java/org/apache/catalina/valves/SemaphoreValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (controlConcurrency(request, response)) { boolean shouldRelease = true; try { if (block) { if (interruptible) { try { semaphore.acquire(); } catch (InterruptedException e) { shouldRelease = false; permitDenied(request, response); return; } } else { semaphore.acquireUninterruptibly(); } } else { if (!semaphore.tryAcquire()) { shouldRelease = false; permitDenied(request, response); return; } } getNext().invoke(request, response); } finally { if (shouldRelease) { semaphore.release(); } } } else { getNext().invoke(request, response); } }
// in java/org/apache/catalina/valves/SemaphoreValve.java
public void permitDenied(Request request, Response response) throws IOException, ServletException { // NO-OP by default }
// in java/org/apache/catalina/valves/PersistentValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { // Select the Context to be used for this Request Context context = request.getContext(); if (context == null) { response.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, sm.getString("standardHost.noContext")); return; } // Bind the context CL to the current thread Thread.currentThread().setContextClassLoader (context.getLoader().getClassLoader()); // Update the session last access time for our session (if any) String sessionId = request.getRequestedSessionId(); Manager manager = context.getManager(); if (sessionId != null && manager != null) { if (manager instanceof StoreManager) { Store store = ((StoreManager) manager).getStore(); if (store != null) { Session session = null; try { session = store.load(sessionId); } catch (Exception e) { container.getLogger().error("deserializeError"); } if (session != null) { if (!session.isValid() || isSessionStale(session, System.currentTimeMillis())) { if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("session swapped in is invalid or expired"); } session.expire(); store.remove(sessionId); } else { session.setManager(manager); // session.setId(sessionId); Only if new ??? manager.add(session); // ((StandardSession)session).activate(); session.access(); session.endAccess(); } } } } } if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("sessionId: " + sessionId); } // Ask the next valve to process the request. getNext().invoke(request, response); // If still processing async, don't try to store the session // TODO: Are there some async states where it is would be safe to store // the session? if (!request.isAsync()) { // Read the sessionid after the response. // HttpSession hsess = hreq.getSession(false); Session hsess; try { hsess = request.getSessionInternal(); } catch (Exception ex) { hsess = null; } String newsessionId = null; if (hsess!=null) { newsessionId = hsess.getIdInternal(); } if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("newsessionId: " + newsessionId); } if (newsessionId!=null) { /* store the session and remove it from the manager */ if (manager instanceof StoreManager) { Session session = manager.findSession(newsessionId); Store store = ((StoreManager) manager).getStore(); if (store != null && session!=null && session.isValid() && !isSessionStale(session, System.currentTimeMillis())) { // ((StandardSession)session).passivate(); store.save(session); ((StoreManager) manager).removeSuper(session); session.recycle(); } else { if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("newsessionId store: " + store + " session: " + session + " valid: " + (session == null ? "N/A" : Boolean.toString( session.isValid())) + " stale: " + isSessionStale(session, System.currentTimeMillis())); } } } else { if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("newsessionId Manager: " + manager); } } } } }
// in java/org/apache/catalina/valves/AccessLogValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { getNext().invoke(request, response); }
// in java/org/apache/catalina/valves/RemoteIpValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { final String originalRemoteAddr = request.getRemoteAddr(); final String originalRemoteHost = request.getRemoteHost(); final String originalScheme = request.getScheme(); final boolean originalSecure = request.isSecure(); final int originalServerPort = request.getServerPort(); if (internalProxies !=null && internalProxies.matcher(originalRemoteAddr).matches()) { String remoteIp = null; // In java 6, proxiesHeaderValue should be declared as a java.util.Deque LinkedList<String> proxiesHeaderValue = new LinkedList<String>(); StringBuilder concatRemoteIpHeaderValue = new StringBuilder(); for (Enumeration<String> e = request.getHeaders(remoteIpHeader); e.hasMoreElements();) { if (concatRemoteIpHeaderValue.length() > 0) { concatRemoteIpHeaderValue.append(", "); } concatRemoteIpHeaderValue.append(e.nextElement()); } String[] remoteIpHeaderValue = commaDelimitedListToStringArray(concatRemoteIpHeaderValue.toString()); int idx; // loop on remoteIpHeaderValue to find the first trusted remote ip and to build the proxies chain for (idx = remoteIpHeaderValue.length - 1; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; remoteIp = currentRemoteIp; if (internalProxies.matcher(currentRemoteIp).matches()) { // do nothing, internalProxies IPs are not appended to the } else if (trustedProxies != null && trustedProxies.matcher(currentRemoteIp).matches()) { proxiesHeaderValue.addFirst(currentRemoteIp); } else { idx--; // decrement idx because break statement doesn't do it break; } } // continue to loop on remoteIpHeaderValue to build the new value of the remoteIpHeader LinkedList<String> newRemoteIpHeaderValue = new LinkedList<String>(); for (; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; newRemoteIpHeaderValue.addFirst(currentRemoteIp); } if (remoteIp != null) { request.setRemoteAddr(remoteIp); request.setRemoteHost(remoteIp); // use request.coyoteRequest.mimeHeaders.setValue(str).setString(str) because request.addHeader(str, str) is no-op in Tomcat // 6.0 if (proxiesHeaderValue.size() == 0) { request.getCoyoteRequest().getMimeHeaders().removeHeader(proxiesHeader); } else { String commaDelimitedListOfProxies = listToCommaDelimitedString(proxiesHeaderValue); request.getCoyoteRequest().getMimeHeaders().setValue(proxiesHeader).setString(commaDelimitedListOfProxies); } if (newRemoteIpHeaderValue.size() == 0) { request.getCoyoteRequest().getMimeHeaders().removeHeader(remoteIpHeader); } else { String commaDelimitedRemoteIpHeaderValue = listToCommaDelimitedString(newRemoteIpHeaderValue); request.getCoyoteRequest().getMimeHeaders().setValue(remoteIpHeader).setString(commaDelimitedRemoteIpHeaderValue); } } if (protocolHeader != null) { String protocolHeaderValue = request.getHeader(protocolHeader); if (protocolHeaderValue == null) { // don't modify the secure,scheme and serverPort attributes // of the request } else if (protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue)) { request.setSecure(true); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString("https"); setPorts(request, httpsServerPort); } else { request.setSecure(false); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString("http"); setPorts(request, httpServerPort); } } if (log.isDebugEnabled()) { log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr '" + originalRemoteAddr + "', originalRemoteHost='" + originalRemoteHost + "', originalSecure='" + originalSecure + "', originalScheme='" + originalScheme + "' will be seen as newRemoteAddr='" + request.getRemoteAddr() + "', newRemoteHost='" + request.getRemoteHost() + "', newScheme='" + request.getScheme() + "', newSecure='" + request.isSecure() + "'"); } } else { if (log.isDebugEnabled()) { log.debug("Skip RemoteIpValve for request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "'"); } } if (requestAttributesEnabled) { request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE, request.getRemoteAddr()); request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE, request.getRemoteHost()); request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE, request.getProtocol()); request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE, Integer.valueOf(request.getServerPort())); } try { getNext().invoke(request, response); } finally { request.setRemoteAddr(originalRemoteAddr); request.setRemoteHost(originalRemoteHost); request.setSecure(originalSecure); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString(originalScheme); request.setServerPort(originalServerPort); } }
// in java/org/apache/catalina/valves/ValveBase.java
Override public void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Perform the request getNext().event(request, response, event); }
// in java/org/apache/catalina/authenticator/SingleSignOn.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { request.removeNote(Constants.REQ_SSOID_NOTE); // Has a valid user already been authenticated? if (containerLog.isDebugEnabled()) { containerLog.debug("Process request for '" + request.getRequestURI() + "'"); } if (request.getUserPrincipal() != null) { if (containerLog.isDebugEnabled()) { containerLog.debug(" Principal '" + request.getUserPrincipal().getName() + "' has already been authenticated"); } getNext().invoke(request, response); return; } // Check for the single sign on cookie if (containerLog.isDebugEnabled()) { containerLog.debug(" Checking for SSO cookie"); } Cookie cookie = null; Cookie cookies[] = request.getCookies(); if (cookies == null) { cookies = new Cookie[0]; } for (int i = 0; i < cookies.length; i++) { if (Constants.SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) { cookie = cookies[i]; break; } } if (cookie == null) { if (containerLog.isDebugEnabled()) { containerLog.debug(" SSO cookie is not present"); } getNext().invoke(request, response); return; } // Look up the cached Principal associated with this cookie value if (containerLog.isDebugEnabled()) { containerLog.debug(" Checking for cached principal for " + cookie.getValue()); } SingleSignOnEntry entry = lookup(cookie.getValue()); if (entry != null) { if (containerLog.isDebugEnabled()) { containerLog.debug(" Found cached principal '" + (entry.getPrincipal() != null ? entry.getPrincipal().getName() : "") + "' with auth type '" + entry.getAuthType() + "'"); } request.setNote(Constants.REQ_SSOID_NOTE, cookie.getValue()); // Only set security elements if reauthentication is not required if (!getRequireReauthentication()) { request.setAuthType(entry.getAuthType()); request.setUserPrincipal(entry.getPrincipal()); } } else { if (containerLog.isDebugEnabled()) { containerLog.debug(" No cached principal found, erasing SSO cookie"); } cookie.setMaxAge(0); response.addCookie(cookie); } // Invoke the next Valve in our pipeline getNext().invoke(request, response); }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (log.isDebugEnabled()) { log.debug("Security checking request " + request.getMethod() + " " + request.getRequestURI()); } // Have we got a cached authenticated Principal to record? if (cache) { Principal principal = request.getUserPrincipal(); if (principal == null) { Session session = request.getSessionInternal(false); if (session != null) { principal = session.getPrincipal(); if (principal != null) { if (log.isDebugEnabled()) { log.debug("We have cached auth type " + session.getAuthType() + " for principal " + session.getPrincipal()); } request.setAuthType(session.getAuthType()); request.setUserPrincipal(principal); } } } } // Special handling for form-based logins to deal with the case // where the login form (and therefore the "j_security_check" URI // to which it submits) might be outside the secured area String contextPath = this.context.getPath(); String requestURI = request.getDecodedRequestURI(); if (requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION)) { if (!authenticate(request, response)) { if (log.isDebugEnabled()) { log.debug(" Failed authenticate() test ??" + requestURI ); } return; } } // The Servlet may specify security constraints through annotations. // Ensure that they have been processed before constraints are checked Wrapper wrapper = (Wrapper) request.getMappingData().wrapper; if (wrapper != null) { wrapper.servletSecurityAnnotationScan(); } Realm realm = this.context.getRealm(); // Is this request URI subject to a security constraint? SecurityConstraint [] constraints = realm.findSecurityConstraints(request, this.context); if (constraints == null && !context.getPreemptiveAuthentication()) { if (log.isDebugEnabled()) { log.debug(" Not subject to any constraint"); } getNext().invoke(request, response); return; } // Make sure that constrained resources are not cached by web proxies // or browsers as caching can provide a security hole if (constraints != null && disableProxyCaching && !"POST".equalsIgnoreCase(request.getMethod())) { if (securePagesWithPragma) { // Note: These can cause problems with downloading files with IE response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); } else { response.setHeader("Cache-Control", "private"); } response.setHeader("Expires", DATE_ONE); } int i; if (constraints != null) { // Enforce any user data constraint for this security constraint if (log.isDebugEnabled()) { log.debug(" Calling hasUserDataPermission()"); } if (!realm.hasUserDataPermission(request, response, constraints)) { if (log.isDebugEnabled()) { log.debug(" Failed hasUserDataPermission() test"); } /* * ASSERT: Authenticator already set the appropriate * HTTP status code, so we do not have to do anything special */ return; } } // Since authenticate modifies the response on failure, // we have to check for allow-from-all first. boolean authRequired; if (constraints == null) { authRequired = false; } else { authRequired = true; for(i=0; i < constraints.length && authRequired; i++) { if(!constraints[i].getAuthConstraint()) { authRequired = false; } else if(!constraints[i].getAllRoles()) { String [] roles = constraints[i].findAuthRoles(); if(roles == null || roles.length == 0) { authRequired = false; } } } } if (!authRequired && context.getPreemptiveAuthentication()) { authRequired = request.getCoyoteRequest().getMimeHeaders().getValue( "authorization") != null; } if (!authRequired && context.getPreemptiveAuthentication()) { X509Certificate[] certs = (X509Certificate[]) request.getAttribute( Globals.CERTIFICATES_ATTR); authRequired = certs != null && certs.length > 0; } if(authRequired) { if (log.isDebugEnabled()) { log.debug(" Calling authenticate()"); } if (!authenticate(request, response)) { if (log.isDebugEnabled()) { log.debug(" Failed authenticate() test"); } /* * ASSERT: Authenticator already set the appropriate * HTTP status code, so we do not have to do anything * special */ return; } } if (constraints != null) { if (log.isDebugEnabled()) { log.debug(" Calling accessControl()"); } if (!realm.hasResourcePermission(request, response, constraints, this.context)) { if (log.isDebugEnabled()) { log.debug(" Failed accessControl() test"); } /* * ASSERT: AccessControl method has already set the * appropriate HTTP status code, so we do not have to do * anything special */ return; } } // Any and all specified constraints have been satisfied if (log.isDebugEnabled()) { log.debug(" Successfully passed all security constraints"); } getNext().invoke(request, response); }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
Override public void login(String username, String password, Request request) throws ServletException { Principal principal = doLogin(request, username, password); register(request, request.getResponse(), principal, getAuthMethod(), username, password); }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
protected Principal doLogin(Request request, String username, String password) throws ServletException { Principal p = context.getRealm().authenticate(username, password); if (p == null) { throw new ServletException(sm.getString("authenticator.loginFail")); } return p; }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
Override public void logout(Request request) throws ServletException { register(request, request.getResponse(), null, null, null, null); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override public void init() throws ServletException { if (getServletConfig().getInitParameter("debug") != null) debug = Integer.parseInt(getServletConfig().getInitParameter("debug")); if (getServletConfig().getInitParameter("input") != null) input = Integer.parseInt(getServletConfig().getInitParameter("input")); if (getServletConfig().getInitParameter("output") != null) output = Integer.parseInt(getServletConfig().getInitParameter("output")); listings = Boolean.parseBoolean(getServletConfig().getInitParameter("listings")); if (getServletConfig().getInitParameter("readonly") != null) readOnly = Boolean.parseBoolean(getServletConfig().getInitParameter("readonly")); if (getServletConfig().getInitParameter("sendfileSize") != null) sendfileSize = Integer.parseInt(getServletConfig().getInitParameter("sendfileSize")) * 1024; fileEncoding = getServletConfig().getInitParameter("fileEncoding"); globalXsltFile = getServletConfig().getInitParameter("globalXsltFile"); contextXsltFile = getServletConfig().getInitParameter("contextXsltFile"); localXsltFile = getServletConfig().getInitParameter("localXsltFile"); readmeFile = getServletConfig().getInitParameter("readmeFile"); if (getServletConfig().getInitParameter("useAcceptRanges") != null) useAcceptRanges = Boolean.parseBoolean(getServletConfig().getInitParameter("useAcceptRanges")); // Sanity check on the specified buffer sizes if (input < 256) input = 256; if (output < 256) output = 256; if (debug > 0) { log("DefaultServlet.init: input buffer size=" + input + ", output buffer size=" + output); } // Load the proxy dir context. resources = (ProxyDirContext) getServletContext() .getAttribute(Globals.RESOURCES_ATTR); if (resources == null) { try { resources = (ProxyDirContext) new InitialContext() .lookup(RESOURCES_JNDI_NAME); } catch (NamingException e) { // Failed throw new ServletException("No resources", e); } } if (resources == null) { throw new UnavailableException("No resources"); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Serve the requested resource, including the data content serveResource(request, response, true); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doHead(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Serve the requested resource, without the data content serveResource(request, response, false); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { StringBuilder allow = new StringBuilder(); // There is a doGet method allow.append("GET, HEAD"); // There is a doPost allow.append(", POST"); // There is a doPut allow.append(", PUT"); // There is a doDelete allow.append(", DELETE"); // Trace - assume disabled unless we can prove otherwise if (req instanceof RequestFacade && ((RequestFacade) req).getAllowTrace()) { allow.append(", TRACE"); } // Always allow options allow.append(", OPTIONS"); resp.setHeader("Allow", allow.toString()); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String path = getRelativePath(req); boolean exists = true; try { resources.lookup(path); } catch (NamingException e) { exists = false; } boolean result = true; // Temp. content file used to support partial PUT File contentFile = null; Range range = parseContentRange(req, resp); InputStream resourceInputStream = null; // Append data specified in ranges to existing content for this // resource - create a temp. file on the local filesystem to // perform this operation // Assume just one range is specified for now if (range != null) { contentFile = executePartialPut(req, range, path); resourceInputStream = new FileInputStream(contentFile); } else { resourceInputStream = req.getInputStream(); } try { Resource newResource = new Resource(resourceInputStream); // FIXME: Add attributes if (exists) { resources.rebind(path, newResource); } else { resources.bind(path, newResource); } } catch(NamingException e) { result = false; } if (result) { if (exists) { resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { resp.setStatus(HttpServletResponse.SC_CREATED); } } else { resp.sendError(HttpServletResponse.SC_CONFLICT); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String path = getRelativePath(req); boolean exists = true; try { resources.lookup(path); } catch (NamingException e) { exists = false; } if (exists) { boolean result = true; try { resources.unbind(path); } catch (NamingException e) { result = false; } if (result) { resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException { boolean serveContent = content; // Identify the requested resource path String path = getRelativePath(request); if (debug > 0) { if (serveContent) log("DefaultServlet.serveResource: Serving resource '" + path + "' headers and data"); else log("DefaultServlet.serveResource: Serving resource '" + path + "' headers only"); } CacheEntry cacheEntry = resources.lookupCache(path); if (!cacheEntry.exists) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } else { // We're included // SRV.9.3 says we must throw a FNFE throw new FileNotFoundException( sm.getString("defaultServlet.missingResource", requestUri)); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } // If the resource is not a collection, and the resource path // ends with "/" or "\", return NOT FOUND if (cacheEntry.context == null) { if (path.endsWith("/") || (path.endsWith("\\"))) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } } boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST; // Check if the conditions specified in the optional If headers are // satisfied. if (cacheEntry.context == null) { // Checking If headers boolean included = (request.getAttribute( RequestDispatcher.INCLUDE_CONTEXT_PATH) != null); if (!included && !isError && !checkIfHeaders(request, response, cacheEntry.attributes)) { return; } } // Find content type. String contentType = cacheEntry.attributes.getMimeType(); if (contentType == null) { contentType = getServletContext().getMimeType(cacheEntry.name); cacheEntry.attributes.setMimeType(contentType); } ArrayList<Range> ranges = null; long contentLength = -1L; if (cacheEntry.context != null) { // Skip directory listings if we have been configured to // suppress them if (!listings) { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); return; } contentType = "text/html;charset=UTF-8"; } else { if (!isError) { if (useAcceptRanges) { // Accept ranges header response.setHeader("Accept-Ranges", "bytes"); } // Parse range specifier ranges = parseRange(request, response, cacheEntry.attributes); // ETag header response.setHeader("ETag", cacheEntry.attributes.getETag()); // Last-Modified header response.setHeader("Last-Modified", cacheEntry.attributes.getLastModifiedHttp()); } // Get content length contentLength = cacheEntry.attributes.getContentLength(); // Special case for zero length files, which would cause a // (silent) ISE when setting the output buffer size if (contentLength == 0L) { serveContent = false; } } ServletOutputStream ostream = null; PrintWriter writer = null; if (serveContent) { // Trying to retrieve the servlet output stream try { ostream = response.getOutputStream(); } catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } } } // Check to see if a Filter, Valve of wrapper has written some content. // If it has, disable range requests and setting of a content length // since neither can be done reliably. ServletResponse r = response; long contentWritten = 0; while (r instanceof ServletResponseWrapper) { r = ((ServletResponseWrapper) r).getResponse(); } if (r instanceof ResponseFacade) { contentWritten = ((ResponseFacade) r).getContentWritten(); } if (contentWritten > 0) { ranges = FULL; } if ( (cacheEntry.context != null) || isError || ( ((ranges == null) || (ranges.isEmpty())) && (request.getHeader("Range") == null) ) || (ranges == FULL) ) { // Set the appropriate output headers if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if ((cacheEntry.resource != null) && (contentLength >= 0) && (!serveContent || ostream != null)) { if (debug > 0) log("DefaultServlet.serveFile: contentLength=" + contentLength); // Don't set a content length if something else has already // written to the response. if (contentWritten == 0) { if (contentLength < Integer.MAX_VALUE) { response.setContentLength((int) contentLength); } else { // Set the content-length as String to be able to use a // long response.setHeader("content-length", "" + contentLength); } } } InputStream renderResult = null; if (cacheEntry.context != null) { if (serveContent) { // Serve the directory browser renderResult = render(getPathPrefix(request), cacheEntry); } } // Copy the input stream to our output stream (if requested) if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, contentLength, null)) copy(cacheEntry, renderResult, ostream); } else { copy(cacheEntry, renderResult, writer); } } } else { if ((ranges == null) || (ranges.isEmpty())) return; // Partial content response. response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); if (ranges.size() == 1) { Range range = ranges.get(0); response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; if (length < Integer.MAX_VALUE) { response.setContentLength((int) length); } else { // Set the content-length as String to be able to use a long response.setHeader("content-length", "" + length); } if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, range.end - range.start + 1, range)) copy(cacheEntry, ostream, range); } else { // we should not get here throw new IllegalStateException(); } } } else { response.setContentType("multipart/byteranges; boundary=" + mimeSeparation); if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { copy(cacheEntry, ostream, ranges.iterator(), contentType); } else { // we should not get here throw new IllegalStateException(); } } } } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream render(String contextPath, CacheEntry cacheEntry) throws IOException, ServletException { InputStream xsltInputStream = findXsltInputStream(cacheEntry.context); if (xsltInputStream==null) { return renderHtml(contextPath, cacheEntry); } return renderXml(contextPath, cacheEntry, xsltInputStream); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream renderXml(String contextPath, CacheEntry cacheEntry, InputStream xsltInputStream) throws IOException, ServletException { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<listing "); sb.append(" contextPath='"); sb.append(contextPath); sb.append("'"); sb.append(" directory='"); sb.append(cacheEntry.name); sb.append("' "); sb.append(" hasParent='").append(!cacheEntry.name.equals("/")); sb.append("'>"); sb.append("<entries>"); try { // Render the directory entries within this directory NamingEnumeration<NameClassPair> enumeration = resources.list(cacheEntry.name); // rewriteUrl(contextPath) is expensive. cache result for later reuse String rewrittenContextPath = rewriteUrl(contextPath); while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String resourceName = ncPair.getName(); String trimmed = resourceName/*.substring(trim)*/; if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF") || trimmed.equalsIgnoreCase(localXsltFile)) continue; if ((cacheEntry.name + trimmed).equals(contextXsltFile)) continue; CacheEntry childCacheEntry = resources.lookupCache(cacheEntry.name + resourceName); if (!childCacheEntry.exists) { continue; } sb.append("<entry"); sb.append(" type='") .append((childCacheEntry.context != null)?"dir":"file") .append("'"); sb.append(" urlPath='") .append(rewrittenContextPath) .append(rewriteUrl(cacheEntry.name + resourceName)) .append((childCacheEntry.context != null)?"/":"") .append("'"); if (childCacheEntry.resource != null) { sb.append(" size='") .append(renderSize(childCacheEntry.attributes.getContentLength())) .append("'"); } sb.append(" date='") .append(childCacheEntry.attributes.getLastModifiedHttp()) .append("'"); sb.append(">"); sb.append(RequestUtil.filter(trimmed)); if (childCacheEntry.context != null) sb.append("/"); sb.append("</entry>"); } } catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); } sb.append("</entries>"); String readme = getReadme(cacheEntry.context); if (readme!=null) { sb.append("<readme><![CDATA["); sb.append(readme); sb.append("]]></readme>"); } sb.append("</listing>"); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Source xmlSource = new StreamSource(new StringReader(sb.toString())); Source xslSource = new StreamSource(xsltInputStream); Transformer transformer = tFactory.newTransformer(xslSource); ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8"); StreamResult out = new StreamResult(osWriter); transformer.transform(xmlSource, out); osWriter.flush(); return (new ByteArrayInputStream(stream.toByteArray())); } catch (TransformerException e) { throw new ServletException("XSL transformer error", e); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream renderHtml(String contextPath, CacheEntry cacheEntry) throws IOException, ServletException { String name = cacheEntry.name; // Prepare a writer to a buffered area ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8"); PrintWriter writer = new PrintWriter(osWriter); StringBuilder sb = new StringBuilder(); // rewriteUrl(contextPath) is expensive. cache result for later reuse String rewrittenContextPath = rewriteUrl(contextPath); // Render the page header sb.append("<html>\r\n"); sb.append("<head>\r\n"); sb.append("<title>"); sb.append(sm.getString("directory.title", name)); sb.append("</title>\r\n"); sb.append("<STYLE><!--"); sb.append(org.apache.catalina.util.TomcatCSS.TOMCAT_CSS); sb.append("--></STYLE> "); sb.append("</head>\r\n"); sb.append("<body>"); sb.append("<h1>"); sb.append(sm.getString("directory.title", name)); // Render the link to our parent (if required) String parentDirectory = name; if (parentDirectory.endsWith("/")) { parentDirectory = parentDirectory.substring(0, parentDirectory.length() - 1); } int slash = parentDirectory.lastIndexOf('/'); if (slash >= 0) { String parent = name.substring(0, slash); sb.append(" - <a href=\""); sb.append(rewrittenContextPath); if (parent.equals("")) parent = "/"; sb.append(rewriteUrl(parent)); if (!parent.endsWith("/")) sb.append("/"); sb.append("\">"); sb.append("<b>"); sb.append(sm.getString("directory.parent", parent)); sb.append("</b>"); sb.append("</a>"); } sb.append("</h1>"); sb.append("<HR size=\"1\" noshade=\"noshade\">"); sb.append("<table width=\"100%\" cellspacing=\"0\"" + " cellpadding=\"5\" align=\"center\">\r\n"); // Render the column headings sb.append("<tr>\r\n"); sb.append("<td align=\"left\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.filename")); sb.append("</strong></font></td>\r\n"); sb.append("<td align=\"center\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.size")); sb.append("</strong></font></td>\r\n"); sb.append("<td align=\"right\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.lastModified")); sb.append("</strong></font></td>\r\n"); sb.append("</tr>"); try { // Render the directory entries within this directory NamingEnumeration<NameClassPair> enumeration = resources.list(cacheEntry.name); boolean shade = false; while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String resourceName = ncPair.getName(); String trimmed = resourceName/*.substring(trim)*/; if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF")) continue; CacheEntry childCacheEntry = resources.lookupCache(cacheEntry.name + resourceName); if (!childCacheEntry.exists) { continue; } sb.append("<tr"); if (shade) sb.append(" bgcolor=\"#eeeeee\""); sb.append(">\r\n"); shade = !shade; sb.append("<td align=\"left\">&nbsp;&nbsp;\r\n"); sb.append("<a href=\""); sb.append(rewrittenContextPath); resourceName = rewriteUrl(name + resourceName); sb.append(resourceName); if (childCacheEntry.context != null) sb.append("/"); sb.append("\"><tt>"); sb.append(RequestUtil.filter(trimmed)); if (childCacheEntry.context != null) sb.append("/"); sb.append("</tt></a></td>\r\n"); sb.append("<td align=\"right\"><tt>"); if (childCacheEntry.context != null) sb.append("&nbsp;"); else sb.append(renderSize(childCacheEntry.attributes.getContentLength())); sb.append("</tt></td>\r\n"); sb.append("<td align=\"right\"><tt>"); sb.append(childCacheEntry.attributes.getLastModifiedHttp()); sb.append("</tt></td>\r\n"); sb.append("</tr>\r\n"); } } catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); } // Render the page footer sb.append("</table>\r\n"); sb.append("<HR size=\"1\" noshade=\"noshade\">"); String readme = getReadme(cacheEntry.context); if (readme!=null) { sb.append(readme); sb.append("<HR size=\"1\" noshade=\"noshade\">"); } sb.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>"); sb.append("</body>\r\n"); sb.append("</html>\r\n"); // Return an input stream to the underlying bytes writer.write(sb.toString()); writer.flush(); return (new ByteArrayInputStream(stream.toByteArray())); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override public void init() throws ServletException { super.init(); if (getServletConfig().getInitParameter("secret") != null) secret = getServletConfig().getInitParameter("secret"); if (getServletConfig().getInitParameter("maxDepth") != null) maxDepth = Integer.parseInt( getServletConfig().getInitParameter("maxDepth")); if (getServletConfig().getInitParameter("allowSpecialPaths") != null) allowSpecialPaths = Boolean.parseBoolean( getServletConfig().getInitParameter("allowSpecialPaths")); // Load the MD5 helper used to calculate signatures. try { md5Helper = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new UnavailableException("No MD5"); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected DocumentBuilder getDocumentBuilder() throws ServletException { DocumentBuilder documentBuilder = null; DocumentBuilderFactory documentBuilderFactory = null; try { documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setExpandEntityReferences(false); documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setEntityResolver( new WebdavResolver(this.getServletContext())); } catch(ParserConfigurationException e) { throw new ServletException (sm.getString("webdavservlet.jaxpfailed")); } return documentBuilder; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final String path = getRelativePath(req); // Block access to special subdirectories. // DefaultServlet assumes it services resources from the root of the web app // and doesn't add any special path protection // WebdavServlet remounts the webapp under a new path, so this check is // necessary on all methods (including GET). if (isSpecialPath(path)) { resp.sendError(WebdavStatus.SC_NOT_FOUND); return; } final String method = req.getMethod(); if (debug > 0) { log("[" + method + "] " + path); } if (method.equals(METHOD_PROPFIND)) { doPropfind(req, resp); } else if (method.equals(METHOD_PROPPATCH)) { doProppatch(req, resp); } else if (method.equals(METHOD_MKCOL)) { doMkcol(req, resp); } else if (method.equals(METHOD_COPY)) { doCopy(req, resp); } else if (method.equals(METHOD_MOVE)) { doMove(req, resp); } else if (method.equals(METHOD_LOCK)) { doLock(req, resp); } else if (method.equals(METHOD_UNLOCK)) { doUnlock(req, resp); } else { // DefaultServlet processing super.service(req, resp); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("DAV", "1,2"); StringBuilder methodsAllowed = determineMethodsAllowed(resources, req); resp.addHeader("Allow", methodsAllowed.toString()); resp.addHeader("MS-Author-Via", "DAV"); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doPropfind(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (!listings) { // Get allowed methods StringBuilder methodsAllowed = determineMethodsAllowed(resources, req); resp.addHeader("Allow", methodsAllowed.toString()); resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED); return; } String path = getRelativePath(req); if (path.endsWith("/")) path = path.substring(0, path.length() - 1); // Properties which are to be displayed. Vector<String> properties = null; // Propfind depth int depth = maxDepth; // Propfind type int type = FIND_ALL_PROP; String depthStr = req.getHeader("Depth"); if (depthStr == null) { depth = maxDepth; } else { if (depthStr.equals("0")) { depth = 0; } else if (depthStr.equals("1")) { depth = 1; } else if (depthStr.equals("infinity")) { depth = maxDepth; } } Node propNode = null; if (req.getContentLength() > 0) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse (new InputSource(req.getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); NodeList childList = rootElement.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: if (currentNode.getNodeName().endsWith("prop")) { type = FIND_BY_PROPERTY; propNode = currentNode; } if (currentNode.getNodeName().endsWith("propname")) { type = FIND_PROPERTY_NAMES; } if (currentNode.getNodeName().endsWith("allprop")) { type = FIND_ALL_PROP; } break; } } } catch (SAXException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); } catch (IOException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); } } if (type == FIND_BY_PROPERTY) { properties = new Vector<String>(); // propNode must be non-null if type == FIND_BY_PROPERTY @SuppressWarnings("null") NodeList childList = propNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String nodeName = currentNode.getNodeName(); String propertyName = null; if (nodeName.indexOf(':') != -1) { propertyName = nodeName.substring (nodeName.indexOf(':') + 1); } else { propertyName = nodeName; } // href is a live property which is handled differently properties.addElement(propertyName); break; } } } boolean exists = true; Object object = null; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } } if (!exists) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, path); return; } resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); if (depth == 0) { parseProperties(req, generatedXML, path, type, properties); } else { // The stack always contains the object of the current level Stack<String> stack = new Stack<String>(); stack.push(path); // Stack of the objects one level below Stack<String> stackBelow = new Stack<String>(); while ((!stack.isEmpty()) && (depth >= 0)) { String currentPath = stack.pop(); parseProperties(req, generatedXML, currentPath, type, properties); try { object = resources.lookup(currentPath); } catch (NamingException e) { continue; } if ((object instanceof DirContext) && (depth > 0)) { try { NamingEnumeration<NameClassPair> enumeration = resources.list(currentPath); while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String newPath = currentPath; if (!(newPath.endsWith("/"))) newPath += "/"; newPath += ncPair.getName(); stackBelow.push(newPath); } } catch (NamingException e) { resp.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } // Displaying the lock-null resources present in that // collection String lockPath = currentPath; if (lockPath.endsWith("/")) lockPath = lockPath.substring(0, lockPath.length() - 1); Vector<String> currentLockNullResources = lockNullResources.get(lockPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); } } } if (stack.isEmpty()) { depth--; stack = stackBelow; stackBelow = new Stack<String>(); } generatedXML.sendData(); } } generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doMkcol(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } String path = getRelativePath(req); boolean exists = true; try { resources.lookup(path); } catch (NamingException e) { exists = false; } // Can't create a collection if a resource already exists at the given // path if (exists) { // Get allowed methods StringBuilder methodsAllowed = determineMethodsAllowed(resources, req); resp.addHeader("Allow", methodsAllowed.toString()); resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED); return; } if (req.getContentLength() > 0) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { // Document document = documentBuilder.parse(new InputSource(req.getInputStream())); // TODO : Process this request body resp.sendError(WebdavStatus.SC_NOT_IMPLEMENTED); return; } catch(SAXException saxe) { // Parse error - assume invalid content resp.sendError(WebdavStatus.SC_UNSUPPORTED_MEDIA_TYPE); return; } } boolean result = true; try { resources.createSubcontext(path); } catch (NamingException e) { result = false; } if (!result) { resp.sendError(WebdavStatus.SC_CONFLICT, WebdavStatus.getStatusText (WebdavStatus.SC_CONFLICT)); } else { resp.setStatus(WebdavStatus.SC_CREATED); // Removing any lock-null resource which would be present lockNullResources.remove(path); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } deleteResource(req, resp); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } super.doPut(req, resp); String path = getRelativePath(req); // Removing any lock-null resource which would be present lockNullResources.remove(path); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doLock(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } LockInfo lock = new LockInfo(); // Parsing lock request // Parsing depth header String depthStr = req.getHeader("Depth"); if (depthStr == null) { lock.depth = maxDepth; } else { if (depthStr.equals("0")) { lock.depth = 0; } else { lock.depth = maxDepth; } } // Parsing timeout header int lockDuration = DEFAULT_TIMEOUT; String lockDurationStr = req.getHeader("Timeout"); if (lockDurationStr == null) { lockDuration = DEFAULT_TIMEOUT; } else { int commaPos = lockDurationStr.indexOf(","); // If multiple timeouts, just use the first if (commaPos != -1) { lockDurationStr = lockDurationStr.substring(0,commaPos); } if (lockDurationStr.startsWith("Second-")) { lockDuration = (new Integer(lockDurationStr.substring(7))).intValue(); } else { if (lockDurationStr.equalsIgnoreCase("infinity")) { lockDuration = MAX_TIMEOUT; } else { try { lockDuration = (new Integer(lockDurationStr)).intValue(); } catch (NumberFormatException e) { lockDuration = MAX_TIMEOUT; } } } if (lockDuration == 0) { lockDuration = DEFAULT_TIMEOUT; } if (lockDuration > MAX_TIMEOUT) { lockDuration = MAX_TIMEOUT; } } lock.expiresAt = System.currentTimeMillis() + (lockDuration * 1000); int lockRequestType = LOCK_CREATION; Node lockInfoNode = null; DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse(new InputSource (req.getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); lockInfoNode = rootElement; } catch (IOException e) { lockRequestType = LOCK_REFRESH; } catch (SAXException e) { lockRequestType = LOCK_REFRESH; } if (lockInfoNode != null) { // Reading lock information NodeList childList = lockInfoNode.getChildNodes(); StringWriter strWriter = null; DOMWriter domWriter = null; Node lockScopeNode = null; Node lockTypeNode = null; Node lockOwnerNode = null; for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String nodeName = currentNode.getNodeName(); if (nodeName.endsWith("lockscope")) { lockScopeNode = currentNode; } if (nodeName.endsWith("locktype")) { lockTypeNode = currentNode; } if (nodeName.endsWith("owner")) { lockOwnerNode = currentNode; } break; } } if (lockScopeNode != null) { childList = lockScopeNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String tempScope = currentNode.getNodeName(); if (tempScope.indexOf(':') != -1) { lock.scope = tempScope.substring (tempScope.indexOf(':') + 1); } else { lock.scope = tempScope; } break; } } if (lock.scope == null) { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } } else { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } if (lockTypeNode != null) { childList = lockTypeNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String tempType = currentNode.getNodeName(); if (tempType.indexOf(':') != -1) { lock.type = tempType.substring(tempType.indexOf(':') + 1); } else { lock.type = tempType; } break; } } if (lock.type == null) { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } } else { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } if (lockOwnerNode != null) { childList = lockOwnerNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: lock.owner += currentNode.getNodeValue(); break; case Node.ELEMENT_NODE: strWriter = new StringWriter(); domWriter = new DOMWriter(strWriter, true); domWriter.setQualifiedNames(false); domWriter.print(currentNode); lock.owner += strWriter.toString(); break; } } if (lock.owner == null) { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } } else { lock.owner = ""; } } String path = getRelativePath(req); lock.path = path; boolean exists = true; Object object = null; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; } Enumeration<LockInfo> locksList = null; if (lockRequestType == LOCK_CREATION) { // Generating lock id String lockTokenStr = req.getServletPath() + "-" + lock.type + "-" + lock.scope + "-" + req.getUserPrincipal() + "-" + lock.depth + "-" + lock.owner + "-" + lock.tokens + "-" + lock.expiresAt + "-" + System.currentTimeMillis() + "-" + secret; String lockToken = md5Encoder.encode(md5Helper.digest( lockTokenStr.getBytes(B2CConverter.ISO_8859_1))); if ( (exists) && (object instanceof DirContext) && (lock.depth == maxDepth) ) { // Locking a collection (and all its member resources) // Checking if a child resource of this collection is // already locked Vector<String> lockPaths = new Vector<String>(); locksList = collectionLocks.elements(); while (locksList.hasMoreElements()) { LockInfo currentLock = locksList.nextElement(); if (currentLock.hasExpired()) { resourceLocks.remove(currentLock.path); continue; } if ( (currentLock.path.startsWith(lock.path)) && ((currentLock.isExclusive()) || (lock.isExclusive())) ) { // A child collection of this collection is locked lockPaths.addElement(currentLock.path); } } locksList = resourceLocks.elements(); while (locksList.hasMoreElements()) { LockInfo currentLock = locksList.nextElement(); if (currentLock.hasExpired()) { resourceLocks.remove(currentLock.path); continue; } if ( (currentLock.path.startsWith(lock.path)) && ((currentLock.isExclusive()) || (lock.isExclusive())) ) { // A child resource of this collection is locked lockPaths.addElement(currentLock.path); } } if (!lockPaths.isEmpty()) { // One of the child paths was locked // We generate a multistatus error report Enumeration<String> lockPathsList = lockPaths.elements(); resp.setStatus(WebdavStatus.SC_CONFLICT); XMLWriter generatedXML = new XMLWriter(); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); while (lockPathsList.hasMoreElements()) { generatedXML.writeElement("D", "response", XMLWriter.OPENING); generatedXML.writeElement("D", "href", XMLWriter.OPENING); generatedXML.writeText(lockPathsList.nextElement()); generatedXML.writeElement("D", "href", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML .writeText("HTTP/1.1 " + WebdavStatus.SC_LOCKED + " " + WebdavStatus .getStatusText(WebdavStatus.SC_LOCKED)); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "response", XMLWriter.CLOSING); } generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); Writer writer = resp.getWriter(); writer.write(generatedXML.toString()); writer.close(); return; } boolean addLock = true; // Checking if there is already a shared lock on this path locksList = collectionLocks.elements(); while (locksList.hasMoreElements()) { LockInfo currentLock = locksList.nextElement(); if (currentLock.path.equals(lock.path)) { if (currentLock.isExclusive()) { resp.sendError(WebdavStatus.SC_LOCKED); return; } else { if (lock.isExclusive()) { resp.sendError(WebdavStatus.SC_LOCKED); return; } } currentLock.tokens.addElement(lockToken); lock = currentLock; addLock = false; } } if (addLock) { lock.tokens.addElement(lockToken); collectionLocks.addElement(lock); } } else { // Locking a single resource // Retrieving an already existing lock on that resource LockInfo presentLock = resourceLocks.get(lock.path); if (presentLock != null) { if ((presentLock.isExclusive()) || (lock.isExclusive())) { // If either lock is exclusive, the lock can't be // granted resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED); return; } else { presentLock.tokens.addElement(lockToken); lock = presentLock; } } else { lock.tokens.addElement(lockToken); resourceLocks.put(lock.path, lock); // Checking if a resource exists at this path exists = true; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; } if (!exists) { // "Creating" a lock-null resource int slash = lock.path.lastIndexOf('/'); String parentPath = lock.path.substring(0, slash); Vector<String> lockNulls = lockNullResources.get(parentPath); if (lockNulls == null) { lockNulls = new Vector<String>(); lockNullResources.put(parentPath, lockNulls); } lockNulls.addElement(lock.path); } // Add the Lock-Token header as by RFC 2518 8.10.1 // - only do this for newly created locks resp.addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">"); } } } if (lockRequestType == LOCK_REFRESH) { String ifHeader = req.getHeader("If"); if (ifHeader == null) ifHeader = ""; // Checking resource locks LockInfo toRenew = resourceLocks.get(path); Enumeration<String> tokenList = null; if (toRenew != null) { // At least one of the tokens of the locks must have been given tokenList = toRenew.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (ifHeader.indexOf(token) != -1) { toRenew.expiresAt = lock.expiresAt; lock = toRenew; } } } // Checking inheritable collection locks Enumeration<LockInfo> collectionLocksList = collectionLocks.elements(); while (collectionLocksList.hasMoreElements()) { toRenew = collectionLocksList.nextElement(); if (path.equals(toRenew.path)) { tokenList = toRenew.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (ifHeader.indexOf(token) != -1) { toRenew.expiresAt = lock.expiresAt; lock = toRenew; } } } } } // Set the status, then generate the XML response containing // the lock information XMLWriter generatedXML = new XMLWriter(); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "prop", XMLWriter.OPENING); generatedXML.writeElement("D", "lockdiscovery", XMLWriter.OPENING); lock.toXML(generatedXML); generatedXML.writeElement("D", "lockdiscovery", XMLWriter.CLOSING); generatedXML.writeElement("D", "prop", XMLWriter.CLOSING); resp.setStatus(WebdavStatus.SC_OK); resp.setContentType("text/xml; charset=UTF-8"); Writer writer = resp.getWriter(); writer.write(generatedXML.toString()); writer.close(); }
// in java/org/apache/catalina/servlets/CGIServlet.java
Override public void init(ServletConfig config) throws ServletException { super.init(config); // Set our properties from the initialization parameters if (getServletConfig().getInitParameter("debug") != null) debug = Integer.parseInt(getServletConfig().getInitParameter("debug")); cgiPathPrefix = getServletConfig().getInitParameter("cgiPathPrefix"); boolean passShellEnvironment = Boolean.valueOf(getServletConfig().getInitParameter("passShellEnvironment")).booleanValue(); if (passShellEnvironment) { shellEnv.putAll(System.getenv()); } if (getServletConfig().getInitParameter("executable") != null) { cgiExecutable = getServletConfig().getInitParameter("executable"); } if (getServletConfig().getInitParameter("executable-arg-1") != null) { List<String> args = new ArrayList<String>(); for (int i = 1;; i++) { String arg = getServletConfig().getInitParameter( "executable-arg-" + i); if (arg == null) { break; } args.add(arg); } cgiExecutableArgs = args; } if (getServletConfig().getInitParameter("parameterEncoding") != null) { parameterEncoding = getServletConfig().getInitParameter("parameterEncoding"); } if (getServletConfig().getInitParameter("stderrTimeout") != null) { stderrTimeout = Long.parseLong(getServletConfig().getInitParameter( "stderrTimeout")); } }
// in java/org/apache/catalina/servlets/CGIServlet.java
Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doGet(req, res); }
// in java/org/apache/catalina/servlets/CGIServlet.java
Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { CGIEnvironment cgiEnv = new CGIEnvironment(req, getServletContext()); if (cgiEnv.isValid()) { CGIRunner cgi = new CGIRunner(cgiEnv.getCommand(), cgiEnv.getEnvironment(), cgiEnv.getWorkingDirectory(), cgiEnv.getParameters()); //if POST, we need to cgi.setInput //REMIND: how does this interact with Servlet API 2.3's Filters?! if ("POST".equals(req.getMethod())) { cgi.setInput(req.getInputStream()); } cgi.setResponse(res); cgi.run(); } if (!cgiEnv.isValid()) { res.setStatus(404); } if (debug >= 10) { ServletOutputStream out = res.getOutputStream(); out.println("<HTML><HEAD><TITLE>$Name$</TITLE></HEAD>"); out.println("<BODY>$Header$<p>"); if (cgiEnv.isValid()) { out.println(cgiEnv.toString()); } else { out.println("<H3>"); out.println("CGI script not found or not specified."); out.println("</H3>"); out.println("<H4>"); out.println("Check the <b>HttpServletRequest "); out.println("<a href=\"#pathInfo\">pathInfo</a></b> "); out.println("property to see if it is what you meant "); out.println("it to be. You must specify an existant "); out.println("and executable file as part of the "); out.println("path-info."); out.println("</H4>"); out.println("<H4>"); out.println("For a good discussion of how CGI scripts "); out.println("work and what their environment variables "); out.println("mean, please visit the <a "); out.println("href=\"http://cgi-spec.golux.com\">CGI "); out.println("Specification page</a>."); out.println("</H4>"); } printServletEnvironment(out, req, res); out.println("</BODY></HTML>"); } }
// in java/org/apache/catalina/ha/session/JvmRouteBinderValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (getEnabled() && request.getContext() != null && request.getContext().getDistributable() && !request.isAsyncDispatching()) { // valve cluster can access manager - other cluster handle turnover // at host level - hopefully! Manager manager = request.getContext().getManager(); if (manager != null && ( (manager instanceof ClusterManager && getCluster() != null && getCluster().getManager(((ClusterManager)manager).getName()) != null) || (manager instanceof PersistentManager))) { handlePossibleTurnover(request); } } // Pass this request on to the next valve in our pipeline getNext().invoke(request, response); }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { long totalstart = 0; //this happens before the request if(doStatistics()) { totalstart = System.currentTimeMillis(); } if (primaryIndicator) { createPrimaryIndicator(request) ; } Context context = request.getContext(); boolean isCrossContext = context != null && context instanceof StandardContext && ((StandardContext) context).getCrossContext(); try { if(isCrossContext) { if(log.isDebugEnabled()) { log.debug(sm.getString("ReplicationValve.crossContext.add")); } //FIXME add Pool of Arraylists crossContextSessions.set(new ArrayList<DeltaSession>()); } getNext().invoke(request, response); if(context != null) { Manager manager = context.getManager(); if (manager != null && manager instanceof ClusterManager) { ClusterManager clusterManager = (ClusterManager) manager; CatalinaCluster containerCluster = (CatalinaCluster) getContainer().getCluster(); if (containerCluster == null) { if (log.isWarnEnabled()) { log.warn(sm.getString("ReplicationValve.nocluster")); } return; } // valve cluster can access manager - other cluster handle replication // at host level - hopefully! if(containerCluster.getManager(clusterManager.getName()) == null) { return ; } if(containerCluster.hasMembers()) { sendReplicationMessage(request, totalstart, isCrossContext, clusterManager, containerCluster); } else { resetReplicationRequest(request,isCrossContext); } } } } finally { // Array must be remove: Current master request send endAccess at recycle. // Don't register this request session again! if(isCrossContext) { if(log.isDebugEnabled()) { log.debug(sm.getString("ReplicationValve.crossContext.remove")); } // crossContextSessions.remove() only exist at Java 5 // register ArrayList at a pool crossContextSessions.set(null); } } }
// in java/org/apache/catalina/ssi/SSIFilter.java
Override public void init(FilterConfig config) throws ServletException { this.config = config; if (config.getInitParameter("debug") != null) { debug = Integer.parseInt(config.getInitParameter("debug")); } if (config.getInitParameter("contentType") != null) { contentTypeRegEx = Pattern.compile(config.getInitParameter("contentType")); } else { contentTypeRegEx = shtmlRegEx; } isVirtualWebappRelative = Boolean.parseBoolean(config.getInitParameter("isVirtualWebappRelative")); if (config.getInitParameter("expires") != null) expires = Long.valueOf(config.getInitParameter("expires")); allowExec = Boolean.parseBoolean(config.getInitParameter("allowExec")); if (debug > 0) config.getServletContext().log( "SSIFilter.init() SSI invoker started with 'debug'=" + debug); }
// in java/org/apache/catalina/ssi/SSIFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // cast once HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse res = (HttpServletResponse)response; // indicate that we're in SSI processing req.setAttribute(Globals.SSI_FLAG_ATTR, "true"); // setup to capture output ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream(); ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(config.getServletContext(),req, res, basos); // process remainder of filter chain chain.doFilter(req, responseIncludeWrapper); // we can't assume the chain flushed its output responseIncludeWrapper.flushOutputStreamOrWriter(); byte[] bytes = basos.toByteArray(); // get content type String contentType = responseIncludeWrapper.getContentType(); // is this an allowed type for SSI processing? if (contentTypeRegEx.matcher(contentType).matches()) { String encoding = res.getCharacterEncoding(); // set up SSI processing SSIExternalResolver ssiExternalResolver = new SSIServletExternalResolver(config.getServletContext(), req, res, isVirtualWebappRelative, debug, encoding); SSIProcessor ssiProcessor = new SSIProcessor(ssiExternalResolver, debug, allowExec); // prepare readers/writers Reader reader = new InputStreamReader(new ByteArrayInputStream(bytes), encoding); ByteArrayOutputStream ssiout = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(ssiout, encoding)); // do SSI processing long lastModified = ssiProcessor.process(reader, responseIncludeWrapper.getLastModified(), writer); // set output bytes writer.flush(); bytes = ssiout.toByteArray(); // override headers if (expires != null) { res.setDateHeader("expires", (new java.util.Date()).getTime() + expires.longValue() * 1000); } if (lastModified > 0) { res.setDateHeader("last-modified", lastModified); } res.setContentLength(bytes.length); Matcher shtmlMatcher = shtmlRegEx.matcher(responseIncludeWrapper.getContentType()); if (shtmlMatcher.matches()) { // Convert shtml mime type to ordinary html mime type but preserve // encoding, if any. String enc = shtmlMatcher.group(1); res.setContentType("text/html" + ((enc != null) ? enc : "")); } } // write output OutputStream out = null; try { out = res.getOutputStream(); } catch (IllegalStateException e) { // Ignore, will try to use a writer } if (out == null) { res.getWriter().write(new String(bytes)); } else { out.write(bytes); } }
// in java/org/apache/catalina/ssi/SSIServlet.java
Override public void init() throws ServletException { if (getServletConfig().getInitParameter("debug") != null) debug = Integer.parseInt(getServletConfig().getInitParameter("debug")); isVirtualWebappRelative = Boolean.parseBoolean(getServletConfig().getInitParameter("isVirtualWebappRelative")); if (getServletConfig().getInitParameter("expires") != null) expires = Long.valueOf(getServletConfig().getInitParameter("expires")); buffered = Boolean.parseBoolean(getServletConfig().getInitParameter("buffered")); inputEncoding = getServletConfig().getInitParameter("inputEncoding"); if (getServletConfig().getInitParameter("outputEncoding") != null) outputEncoding = getServletConfig().getInitParameter("outputEncoding"); allowExec = Boolean.parseBoolean( getServletConfig().getInitParameter("allowExec")); if (debug > 0) log("SSIServlet.init() SSI invoker started with 'debug'=" + debug); }
// in java/org/apache/catalina/ssi/SSIServlet.java
Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { if (debug > 0) log("SSIServlet.doGet()"); requestHandler(req, res); }
// in java/org/apache/catalina/ssi/SSIServlet.java
Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { if (debug > 0) log("SSIServlet.doPost()"); requestHandler(req, res); }
// in java/org/apache/catalina/connector/Request.java
Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { if (response.isCommitted()) { throw new IllegalStateException( sm.getString("coyoteRequest.authenticate.ise")); } return context.getAuthenticator().authenticate(this, response); }
// in java/org/apache/catalina/connector/Request.java
Override public void login(String username, String password) throws ServletException { if (getAuthType() != null || getRemoteUser() != null || getUserPrincipal() != null) { throw new ServletException( sm.getString("coyoteRequest.alreadyAuthenticated")); } if (context.getAuthenticator() == null) { throw new ServletException("no authenticator"); } context.getAuthenticator().login(username, password, this); }
// in java/org/apache/catalina/connector/Request.java
Override public void logout() throws ServletException { context.getAuthenticator().logout(this); }
// in java/org/apache/catalina/connector/Request.java
Override public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException { parseParts(); if (partsParseException != null) { if (partsParseException instanceof IOException) { throw (IOException) partsParseException; } else if (partsParseException instanceof IllegalStateException) { throw (IllegalStateException) partsParseException; } else if (partsParseException instanceof ServletException) { throw (ServletException) partsParseException; } } return parts; }
// in java/org/apache/catalina/connector/Request.java
Override public Part getPart(String name) throws IOException, IllegalStateException, ServletException { Collection<Part> c = getParts(); Iterator<Part> iterator = c.iterator(); while (iterator.hasNext()) { Part part = iterator.next(); if (name.equals(part.getName())) { return part; } } return null; }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { return request.authenticate(response); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public void login(String username, String password) throws ServletException { request.login(username, password); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public void logout() throws ServletException { request.logout(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Collection<Part> getParts() throws IllegalStateException, IOException, ServletException { return request.getParts(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Part getPart(String name) throws IllegalStateException, IOException, ServletException { return request.getPart(name); }
// in java/org/apache/catalina/connector/CometEventImpl.java
Override public void setTimeout(int timeout) throws IOException, ServletException, UnsupportedOperationException { if (request.getAttribute(Globals.COMET_TIMEOUT_SUPPORTED_ATTR) == Boolean.TRUE) { request.setAttribute(Globals.COMET_TIMEOUT_ATTR, Integer.valueOf(timeout)); if (request.isComet()) { request.setCometTimeout(timeout); } } else { throw new UnsupportedOperationException(); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; try { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<Void>() { @Override public Void run() throws ServletException, IOException { internalDoFilter(req,res); return null; } } ); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public Void run() throws ServletException, IOException { internalDoFilter(req,res); return null; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
private void internalDoFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { // Call the next filter if there is one if (pos < n) { ApplicationFilterConfig filterConfig = filters[pos++]; Filter filter = null; try { filter = filterConfig.getFilter(); support.fireInstanceEvent(InstanceEvent.BEFORE_FILTER_EVENT, filter, request, response); if (request.isAsyncSupported() && "false".equalsIgnoreCase( filterConfig.getFilterDef().getAsyncSupported())) { request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE); } if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; Principal principal = ((HttpServletRequest) req).getUserPrincipal(); Object[] args = new Object[]{req, res, this}; SecurityUtil.doAsPrivilege ("doFilter", filter, classType, args, principal); } else { filter.doFilter(request, response, this); } support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response); } catch (IOException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (ServletException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (RuntimeException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); } return; } // We fell off the end of the chain -- call the servlet instance try { if (ApplicationDispatcher.WRAP_SAME_OBJECT) { lastServicedRequest.set(request); lastServicedResponse.set(response); } support.fireInstanceEvent(InstanceEvent.BEFORE_SERVICE_EVENT, servlet, request, response); if (request.isAsyncSupported() && !support.getWrapper().isAsyncSupported()) { request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE); } // Use potentially wrapped request from this point if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) { if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; Principal principal = ((HttpServletRequest) req).getUserPrincipal(); Object[] args = new Object[]{req, res}; SecurityUtil.doAsPrivilege("service", servlet, classTypeUsedInService, args, principal); } else { servlet.service(request, response); } } else { servlet.service(request, response); } support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response); } catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); } finally { if (ApplicationDispatcher.WRAP_SAME_OBJECT) { lastServicedRequest.set(null); lastServicedResponse.set(null); } } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public void doFilterEvent(CometEvent event) throws IOException, ServletException { if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; try { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<Void>() { @Override public Void run() throws ServletException, IOException { internalDoFilterEvent(ev); return null; } } ); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public Void run() throws ServletException, IOException { internalDoFilterEvent(ev); return null; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
private void internalDoFilterEvent(CometEvent event) throws IOException, ServletException { // Call the next filter if there is one if (pos < n) { ApplicationFilterConfig filterConfig = filters[pos++]; CometFilter filter = null; try { filter = (CometFilter) filterConfig.getFilter(); // FIXME: No instance listener processing for events for now /* support.fireInstanceEvent(InstanceEvent.BEFORE_FILTER_EVENT, filter, event); */ if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; Principal principal = ev.getHttpServletRequest().getUserPrincipal(); Object[] args = new Object[]{ev, this}; SecurityUtil.doAsPrivilege("doFilterEvent", filter, cometClassType, args, principal); } else { filter.doFilterEvent(event, this); } /*support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event);*/ } catch (IOException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (ServletException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (RuntimeException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); } return; } // We fell off the end of the chain -- call the servlet instance try { /* support.fireInstanceEvent(InstanceEvent.BEFORE_SERVICE_EVENT, servlet, request, response); */ if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; Principal principal = ev.getHttpServletRequest().getUserPrincipal(); Object[] args = new Object[]{ ev }; SecurityUtil.doAsPrivilege("event", servlet, classTypeUsedInEvent, args, principal); } else { ((CometProcessor) servlet).event(event); } /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response);*/ } catch (IOException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (ServletException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (RuntimeException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw new ServletException (sm.getString("filterChain.servlet"), e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Initialize local variables we may need boolean unavailable = false; Throwable throwable = null; // This should be a Request attribute... long t1=System.currentTimeMillis(); requestCount++; StandardWrapper wrapper = (StandardWrapper) getContainer(); Servlet servlet = null; Context context = (Context) wrapper.getParent(); // Check for the application being marked unavailable if (!context.getAvailable()) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardContext.isUnavailable")); unavailable = true; } // Check for the servlet being marked unavailable if (!unavailable && wrapper.isUnavailable()) { container.getLogger().info(sm.getString("standardWrapper.isUnavailable", wrapper.getName())); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } unavailable = true; } // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (UnavailableException e) { container.getLogger().error( sm.getString("standardWrapper.allocateException", wrapper.getName()), e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } } catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } // Identify if the request is Comet related now that the servlet has been allocated boolean comet = false; if (servlet instanceof CometProcessor && request.getAttribute( Globals.COMET_SUPPORTED_ATTR) == Boolean.TRUE) { comet = true; request.setComet(true); } MessageBytes requestPathMB = request.getRequestPathMB(); DispatcherType dispatcherType = DispatcherType.REQUEST; if (request.getDispatcherType()==DispatcherType.ASYNC) dispatcherType = DispatcherType.ASYNC; request.setAttribute (ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, dispatcherType); request.setAttribute (ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB); // Create the filter chain for this request ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance(); ApplicationFilterChain filterChain = factory.createFilterChain(request, wrapper, servlet); // Reset comet flag value after creating the filter chain request.setComet(false); // Call the filter chain for this request // NOTE: This also calls the servlet's service() method try { if ((servlet != null) && (filterChain != null)) { // Swallow output if needed if (context.getSwallowOutput()) { try { SystemLogHandler.startCapture(); if (request.isAsyncDispatching()) { //TODO SERVLET3 - async ((AsyncContextImpl)request.getAsyncContext()).doInternalDispatch(); } else if (comet) { filterChain.doFilterEvent(request.getEvent()); request.setComet(true); } else { filterChain.doFilter(request.getRequest(), response.getResponse()); } } finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } } } else { if (request.isAsyncDispatching()) { //TODO SERVLET3 - async ((AsyncContextImpl)request.getAsyncContext()).doInternalDispatch(); } else if (comet) { request.setComet(true); filterChain.doFilterEvent(request.getEvent()); } else { filterChain.doFilter (request.getRequest(), response.getResponse()); } } } } catch (ClientAbortException e) { throwable = e; exception(request, response, e); } catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing } catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } // Release the filter chain (if any) for this request if (filterChain != null) { if (request.isComet()) { // If this is a Comet request, then the same chain will be used for the // processing of all subsequent events. filterChain.reuse(); } else { filterChain.release(); } } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } // If this servlet has been marked permanently unavailable, // unload it and release this instance try { if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) { wrapper.unload(); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } long t2=System.currentTimeMillis(); long time=t2-t1; processingTime += time; if( time > maxTime) maxTime=time; if( time < minTime) minTime=time; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
Override public void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Initialize local variables we may need Throwable throwable = null; // This should be a Request attribute... long t1=System.currentTimeMillis(); // FIXME: Add a flag to count the total amount of events processed ? requestCount++; StandardWrapper wrapper = (StandardWrapper) getContainer(); if (wrapper == null) { // Context has been shutdown. Nothing to do here. return; } Servlet servlet = null; Context context = (Context) wrapper.getParent(); // Check for the application being marked unavailable boolean unavailable = !context.getAvailable() || wrapper.isUnavailable(); // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (UnavailableException e) { // The response is already committed, so it's not possible to do anything } catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } MessageBytes requestPathMB = request.getRequestPathMB(); request.setAttribute (ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, DispatcherType.REQUEST); request.setAttribute (ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB); // Get the current (unchanged) filter chain for this request ApplicationFilterChain filterChain = (ApplicationFilterChain) request.getFilterChain(); // Call the filter chain for this request // NOTE: This also calls the servlet's event() method try { if ((servlet != null) && (filterChain != null)) { // Swallow output if needed if (context.getSwallowOutput()) { try { SystemLogHandler.startCapture(); filterChain.doFilterEvent(request.getEvent()); } finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } } } else { filterChain.doFilterEvent(request.getEvent()); } } } catch (ClientAbortException e) { throwable = e; exception(request, response, e); } catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing } catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } // Release the filter chain (if any) for this request if (filterChain != null) { filterChain.reuse(); } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } // If this servlet has been marked permanently unavailable, // unload it and release this instance try { if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) { wrapper.unload(); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } long t2=System.currentTimeMillis(); long time=t2-t1; processingTime += time; if( time > maxTime) maxTime=time; if( time < minTime) minTime=time; }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
Filter getFilter() throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { // Return the existing filter instance, if any if (this.filter != null) return (this.filter); // Identify the class loader we will be using String filterClass = filterDef.getFilterClass(); this.filter = (Filter) getInstanceManager().newInstance(filterClass); initFilter(); return (this.filter); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
private void initFilter() throws ServletException { if (context instanceof StandardContext && context.getSwallowOutput()) { try { SystemLogHandler.startCapture(); filter.init(this); } finally { String capturedlog = SystemLogHandler.stopCapture(); if (capturedlog != null && capturedlog.length() > 0) { getServletContext().log(capturedlog); } } } else { filter.init(this); } // Expose filter via JMX registerJMX(); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
void setFilterDef(FilterDef filterDef) throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { this.filterDef = filterDef; if (filterDef == null) { // Release any previously allocated filter instance if (this.filter != null){ if (Globals.IS_SECURITY_ENABLED) { try{ SecurityUtil.doAsPrivilege("destroy", filter); } catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); } SecurityUtil.remove(filter); } else { filter.destroy(); } if (!context.getIgnoreAnnotations()) { try { ((StandardContext) context).getInstanceManager().destroyInstance(this.filter); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); } } } this.filter = null; } else { // Allocate a new filter instance if necessary if (filterDef.getFilter() == null) { getFilter(); } } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends Filter> T createFilter(Class<T> c) throws ServletException { try { @SuppressWarnings("unchecked") T filter = (T) context.getInstanceManager().newInstance(c.getName()); return filter; } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends Servlet> T createServlet(Class<T> c) throws ServletException { try { @SuppressWarnings("unchecked") T servlet = (T) context.getInstanceManager().newInstance(c.getName()); context.dynamicServletCreated(servlet); return servlet; } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends EventListener> T createListener(Class<T> c) throws ServletException { try { @SuppressWarnings("unchecked") T listener = (T) context.getInstanceManager().newInstance(c.getName()); if (listener instanceof ServletContextListener || listener instanceof ServletContextAttributeListener || listener instanceof ServletRequestListener || listener instanceof ServletRequestAttributeListener || listener instanceof HttpSessionListener || listener instanceof HttpSessionAttributeListener) { return listener; } throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", listener.getClass().getName())); } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } }
// in java/org/apache/catalina/core/AsyncContextImpl.java
protected void doInternalDispatch() throws ServletException, IOException { if (log.isDebugEnabled()) { logDebug("intDispatch"); } try { dispatch.run(); if (!request.isAsync()) { fireOnComplete(); } } catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); } }
// in java/org/apache/catalina/core/StandardContextValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Disallow any direct access to resources under WEB-INF or META-INF MessageBytes requestPathMB = request.getRequestPathMB(); if ((requestPathMB.startsWithIgnoreCase("/META-INF/", 0)) || (requestPathMB.equalsIgnoreCase("/META-INF")) || (requestPathMB.startsWithIgnoreCase("/WEB-INF/", 0)) || (requestPathMB.equalsIgnoreCase("/WEB-INF"))) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Select the Wrapper to be used for this Request Wrapper wrapper = request.getWrapper(); if (wrapper == null || wrapper.isUnavailable()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Acknowledge the request try { response.sendAcknowledgement(); } catch (IOException ioe) { container.getLogger().error(sm.getString( "standardContextValve.acknowledgeException"), ioe); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (request.isAsyncSupported()) { request.setAsyncSupported(wrapper.getPipeline().isAsyncSupported()); } wrapper.getPipeline().getFirst().invoke(request, response); }
// in java/org/apache/catalina/core/StandardContextValve.java
Override public final void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Select the Wrapper to be used for this Request Wrapper wrapper = request.getWrapper(); wrapper.getPipeline().getFirst().event(request, response, event); }
// in java/org/apache/catalina/core/StandardEngineValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Select the Host to be used for this Request Host host = request.getHost(); if (host == null) { response.sendError (HttpServletResponse.SC_BAD_REQUEST, sm.getString("standardEngine.noHost", request.getServerName())); return; } if (request.isAsyncSupported()) { request.setAsyncSupported(host.getPipeline().isAsyncSupported()); } // Ask this Host to process this request host.getPipeline().getFirst().invoke(request, response); }
// in java/org/apache/catalina/core/StandardEngineValve.java
Override public final void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Ask this Host to process this request request.getHost().getPipeline().getFirst().event(request, response, event); }
// in java/org/apache/catalina/core/StandardHostValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Select the Context to be used for this Request Context context = request.getContext(); if (context == null) { response.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, sm.getString("standardHost.noContext")); return; } // Bind the context CL to the current thread if( context.getLoader() != null ) { // Not started - it should check for availability first // This should eventually move to Engine, it's generic. if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( context.getLoader().getClassLoader()); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader (context.getLoader().getClassLoader()); } } if (request.isAsyncSupported()) { request.setAsyncSupported(context.getPipeline().isAsyncSupported()); } // Don't fire listeners during async processing // If a request init listener throws an exception, the request is // aborted boolean asyncAtStart = request.isAsync(); if (asyncAtStart || context.fireRequestInitEvent(request)) { // Ask this Context to process this request try { context.getPipeline().getFirst().invoke(request, response); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); throwable(request, response, t); } // If the request was async at the start and an error occurred then // the async error handling will kick-in and that will fire the // request destroyed event *after* the error handling has taken // place if (!(request.isAsync() || (asyncAtStart && request.getAttribute( RequestDispatcher.ERROR_EXCEPTION) != null))) { // Protect against NPEs if context was destroyed during a long // running request. if (context.getState().isAvailable()) { // Error page processing response.setSuspended(false); Throwable t = (Throwable) request.getAttribute( RequestDispatcher.ERROR_EXCEPTION); if (t != null) { throwable(request, response, t); } else { status(request, response); } context.fireRequestDestroyEvent(request); } } } // Access a session (if present) to update last accessed time, based on a // strict interpretation of the specification if (ACCESS_SESSION) { request.getSession(false); } // Restore the context classloader if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( StandardHostValve.class.getClassLoader()); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader (StandardHostValve.class.getClassLoader()); } }
// in java/org/apache/catalina/core/StandardHostValve.java
Override public final void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Select the Context to be used for this Request Context context = request.getContext(); // Bind the context CL to the current thread if( context.getLoader() != null ) { // Not started - it should check for availability first // This should eventually move to Engine, it's generic. Thread.currentThread().setContextClassLoader (context.getLoader().getClassLoader()); } // Ask this Context to process this request context.getPipeline().getFirst().event(request, response, event); // Error page processing response.setSuspended(false); Throwable t = (Throwable) request.getAttribute( RequestDispatcher.ERROR_EXCEPTION); if (t != null) { throwable(request, response, t); } else { status(request, response); } // Access a session (if present) to update last accessed time, based on a // strict interpretation of the specification if (ACCESS_SESSION) { request.getSession(false); } // Restore the context classloader Thread.currentThread().setContextClassLoader (StandardHostValve.class.getClassLoader()); }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public String[] getServletMethods() throws ServletException { instance = loadServlet(); Class<? extends Servlet> servletClazz = instance.getClass(); if (!javax.servlet.http.HttpServlet.class.isAssignableFrom( servletClazz)) { return DEFAULT_SERVLET_METHODS; } HashSet<String> allow = new HashSet<String>(); allow.add("TRACE"); allow.add("OPTIONS"); Method[] methods = getAllDeclaredMethods(servletClazz); for (int i=0; methods != null && i<methods.length; i++) { Method m = methods[i]; if (m.getName().equals("doGet")) { allow.add("GET"); allow.add("HEAD"); } else if (m.getName().equals("doPost")) { allow.add("POST"); } else if (m.getName().equals("doPut")) { allow.add("PUT"); } else if (m.getName().equals("doDelete")) { allow.add("DELETE"); } } String[] methodNames = new String[allow.size()]; return allow.toArray(methodNames); }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public Servlet allocate() throws ServletException { // If we are currently unloading this servlet, throw an exception if (unloading) throw new ServletException (sm.getString("standardWrapper.unloading", getName())); boolean newInstance = false; // If not SingleThreadedModel, return the same instance every time if (!singleThreadModel) { // Load and initialize our instance if necessary if (instance == null) { synchronized (this) { if (instance == null) { try { if (log.isDebugEnabled()) log.debug("Allocating non-STM instance"); instance = loadServlet(); if (!singleThreadModel) { // For non-STM, increment here to prevent a race // condition with unload. Bug 43683, test case // #3 newInstance = true; countAllocated.incrementAndGet(); } } catch (ServletException e) { throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); } } } } if (!instanceInitialized) { initServlet(instance); } if (singleThreadModel) { if (newInstance) { // Have to do this outside of the sync above to prevent a // possible deadlock synchronized (instancePool) { instancePool.push(instance); nInstances++; } } } else { if (log.isTraceEnabled()) log.trace(" Returning non-STM instance"); // For new instances, count will have been incremented at the // time of creation if (!newInstance) { countAllocated.incrementAndGet(); } return (instance); } } synchronized (instancePool) { while (countAllocated.get() >= nInstances) { // Allocate a new instance if possible, or else wait if (nInstances < maxInstances) { try { instancePool.push(loadServlet()); nInstances++; } catch (ServletException e) { throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); } } else { try { instancePool.wait(); } catch (InterruptedException e) { // Ignore } } } if (log.isTraceEnabled()) log.trace(" Returning allocated STM instance"); countAllocated.incrementAndGet(); return instancePool.pop(); } }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public void deallocate(Servlet servlet) throws ServletException { // If not SingleThreadModel, no action is required if (!singleThreadModel) { countAllocated.decrementAndGet(); return; } // Unlock and free this instance synchronized (instancePool) { countAllocated.decrementAndGet(); instancePool.push(servlet); instancePool.notify(); } }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public synchronized void load() throws ServletException { instance = loadServlet(); if (!instanceInitialized) { initServlet(instance); } if (isJspServlet) { StringBuilder oname = new StringBuilder(getDomain()); oname.append(":type=JspMonitor,name="); oname.append(getName()); oname.append(getWebModuleKeyProperties()); try { jspMonitorON = new ObjectName(oname.toString()); Registry.getRegistry(null, null) .registerComponent(instance, jspMonitorON, null); } catch( Exception ex ) { log.info("Error registering JSP monitoring with jmx " + instance); } } }
// in java/org/apache/catalina/core/StandardWrapper.java
public synchronized Servlet loadServlet() throws ServletException { // Nothing to do if we already have an instance or an instance pool if (!singleThreadModel && (instance != null)) return instance; PrintStream out = System.out; if (swallowOutput) { SystemLogHandler.startCapture(); } Servlet servlet; try { long t1=System.currentTimeMillis(); // Complain if no servlet class has been specified if (servletClass == null) { unavailable(null); throw new ServletException (sm.getString("standardWrapper.notClass", getName())); } InstanceManager instanceManager = ((StandardContext)getParent()).getInstanceManager(); try { servlet = (Servlet) instanceManager.newInstance(servletClass); } catch (ClassCastException e) { unavailable(null); // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.notServlet", servletClass), e); } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); } if (multipartConfigElement == null) { MultipartConfig annotation = servlet.getClass().getAnnotation(MultipartConfig.class); if (annotation != null) { multipartConfigElement = new MultipartConfigElement(annotation); } } processServletSecurityAnnotation(servlet.getClass()); // Special handling for ContainerServlet instances if ((servlet instanceof ContainerServlet) && (isContainerProvidedServlet(servletClass) || ((Context) getParent()).getPrivileged() )) { ((ContainerServlet) servlet).setWrapper(this); } classLoadTime=(int) (System.currentTimeMillis() -t1); if (servlet instanceof SingleThreadModel) { if (instancePool == null) { instancePool = new Stack<Servlet>(); } singleThreadModel = true; } initServlet(servlet); fireContainerEvent("load", this); loadTime=System.currentTimeMillis() -t1; } finally { if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } } return servlet; }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public void servletSecurityAnnotationScan() throws ServletException { if (getServlet() == null) { Class<?> clazz = null; try { clazz = getParent().getLoader().getClassLoader().loadClass( getServletClass()); processServletSecurityAnnotation(clazz); } catch (ClassNotFoundException e) { // Safe to ignore. No class means no annotations to process } } else { if (servletSecurityAnnotationScanRequired) { processServletSecurityAnnotation(getServlet().getClass()); } } }
// in java/org/apache/catalina/core/StandardWrapper.java
private synchronized void initServlet(Servlet servlet) throws ServletException { if (instanceInitialized && !singleThreadModel) return; // Call the initialization method of this servlet try { instanceSupport.fireInstanceEvent(InstanceEvent.BEFORE_INIT_EVENT, servlet); if( Globals.IS_SECURITY_ENABLED) { Object[] args = new Object[]{(facade)}; SecurityUtil.doAsPrivilege("init", servlet, classType, args); args = null; } else { servlet.init(facade); } instanceInitialized = true; instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet); } catch (UnavailableException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); unavailable(f); throw f; } catch (ServletException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw f; } catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); } }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public synchronized void unload() throws ServletException { // Nothing to do if we have never loaded the instance if (!singleThreadModel && (instance == null)) return; unloading = true; // Loaf a while if the current instance is allocated // (possibly more than once if non-STM) if (countAllocated.get() > 0) { int nRetries = 0; long delay = unloadDelay / 20; while ((nRetries < 21) && (countAllocated.get() > 0)) { if ((nRetries % 10) == 0) { log.info(sm.getString("standardWrapper.waiting", countAllocated.toString())); } try { Thread.sleep(delay); } catch (InterruptedException e) { // Ignore } nRetries++; } } if (instanceInitialized) { PrintStream out = System.out; if (swallowOutput) { SystemLogHandler.startCapture(); } // Call the servlet destroy() method try { instanceSupport.fireInstanceEvent (InstanceEvent.BEFORE_DESTROY_EVENT, instance); if( Globals.IS_SECURITY_ENABLED) { SecurityUtil.doAsPrivilege("destroy", instance); SecurityUtil.remove(instance); } else { instance.destroy(); } instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance); // Annotation processing if (!((Context) getParent()).getIgnoreAnnotations()) { ((StandardContext)getParent()).getInstanceManager().destroyInstance(instance); } } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); } finally { // Write captured output if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } } } // Deregister the destroyed instance instance = null; if (isJspServlet && jspMonitorON != null ) { Registry.getRegistry(null, null).unregisterComponent(jspMonitorON); } if (singleThreadModel && (instancePool != null)) { try { while (!instancePool.isEmpty()) { Servlet s = instancePool.pop(); if (Globals.IS_SECURITY_ENABLED) { SecurityUtil.doAsPrivilege("destroy", s); SecurityUtil.remove(instance); } else { s.destroy(); } // Annotation processing if (!((Context) getParent()).getIgnoreAnnotations()) { ((StandardContext)getParent()).getInstanceManager().destroyInstance(s); } } } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); } instancePool = null; nInstances = 0; } singleThreadModel = false; unloading = false; fireContainerEvent("unload", this); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
Override public Void run() throws ServletException, IOException { DispatcherType type = DispatcherType.INCLUDE; if (request.getDispatcherType()==DispatcherType.ASYNC) type = DispatcherType.ASYNC; doInclude(request,response,type); return null; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
Override public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (Globals.IS_SECURITY_ENABLED) { try { PrivilegedForward dp = new PrivilegedForward(request,response); AccessController.doPrivileged(dp); } catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; } } else { doForward(request,response); } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void doForward(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Reset any output that has been buffered, but keep headers/cookies if (response.isCommitted()) { throw new IllegalStateException (sm.getString("applicationDispatcher.forward.ise")); } try { response.resetBuffer(); } catch (IllegalStateException e) { throw e; } // Set up to handle the specified request and response State state = new State(request, response, false); if (WRAP_SAME_OBJECT) { // Check SRV.8.2 / SRV.14.2.5.1 compliance checkSameObjects(request, response); } wrapResponse(state); // Handle an HTTP named dispatcher forward if ((servletPath == null) && (pathInfo == null)) { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); HttpServletRequest hrequest = state.hrequest; wrequest.setRequestURI(hrequest.getRequestURI()); wrequest.setContextPath(hrequest.getContextPath()); wrequest.setServletPath(hrequest.getServletPath()); wrequest.setPathInfo(hrequest.getPathInfo()); wrequest.setQueryString(hrequest.getQueryString()); processRequest(request,response,state); } // Handle an HTTP path-based forward else { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); String contextPath = context.getPath(); HttpServletRequest hrequest = state.hrequest; if (hrequest.getAttribute( RequestDispatcher.FORWARD_REQUEST_URI) == null) { wrequest.setAttribute(RequestDispatcher.FORWARD_REQUEST_URI, hrequest.getRequestURI()); wrequest.setAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH, hrequest.getContextPath()); wrequest.setAttribute(RequestDispatcher.FORWARD_SERVLET_PATH, hrequest.getServletPath()); wrequest.setAttribute(RequestDispatcher.FORWARD_PATH_INFO, hrequest.getPathInfo()); wrequest.setAttribute(RequestDispatcher.FORWARD_QUERY_STRING, hrequest.getQueryString()); } wrequest.setContextPath(contextPath); wrequest.setRequestURI(requestURI); wrequest.setServletPath(servletPath); wrequest.setPathInfo(pathInfo); if (queryString != null) { wrequest.setQueryString(queryString); wrequest.setQueryParams(queryString); } processRequest(request,response,state); } // This is not a real close in order to support error processing if (wrapper.getLogger().isDebugEnabled() ) wrapper.getLogger().debug(" Disabling the response for futher output"); if (response instanceof ResponseFacade) { ((ResponseFacade) response).finish(); } else { // Servlet SRV.6.2.2. The Request/Response may have been wrapped // and may no longer be instance of RequestFacade if (wrapper.getLogger().isDebugEnabled()){ wrapper.getLogger().debug( " The Response is vehiculed using a wrapper: " + response.getClass().getName() ); } // Close anyway try { PrintWriter writer = response.getWriter(); writer.close(); } catch (IllegalStateException e) { try { ServletOutputStream stream = response.getOutputStream(); stream.close(); } catch (IllegalStateException f) { // Ignore } catch (IOException f) { // Ignore } } catch (IOException e) { // Ignore } } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void processRequest(ServletRequest request, ServletResponse response, State state) throws IOException, ServletException { DispatcherType disInt = (DispatcherType) request.getAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR); if (disInt != null) { boolean doInvoke = true; if (context.getFireRequestListenersOnForwards() && !context.fireRequestInitEvent(request)) { doInvoke = false; } if (doInvoke) { if (disInt != DispatcherType.ERROR) { state.outerRequest.setAttribute (ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); state.outerRequest.setAttribute (ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, DispatcherType.FORWARD); invoke(state.outerRequest, response, state); } else { invoke(state.outerRequest, response, state); } if (context.getFireRequestListenersOnForwards()) { context.fireRequestDestroyEvent(request); } } } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
Override public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (Globals.IS_SECURITY_ENABLED) { try { PrivilegedInclude dp = new PrivilegedInclude(request,response); AccessController.doPrivileged(dp); } catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; } } else { DispatcherType type = DispatcherType.INCLUDE; if (request.getDispatcherType()==DispatcherType.ASYNC) type = DispatcherType.ASYNC; doInclude(request,response,type); } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void doInclude(ServletRequest request, ServletResponse response, DispatcherType type) throws ServletException, IOException { // Set up to handle the specified request and response State state = new State(request, response, true); if (WRAP_SAME_OBJECT) { // Check SRV.8.2 / SRV.14.2.5.1 compliance checkSameObjects(request, response); } // Create a wrapped response to use for this request wrapResponse(state); // Handle an HTTP named dispatcher include if (name != null) { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); wrequest.setAttribute(Globals.NAMED_DISPATCHER_ATTR, name); if (servletPath != null) wrequest.setServletPath(servletPath); wrequest.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, type); wrequest.setAttribute( ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); invoke(state.outerRequest, state.outerResponse, state); } // Handle an HTTP path based include else { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); String contextPath = context.getPath(); if (requestURI != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_REQUEST_URI, requestURI); if (contextPath != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH, contextPath); if (servletPath != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH, servletPath); if (pathInfo != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_PATH_INFO, pathInfo); if (queryString != null) { wrequest.setAttribute(RequestDispatcher.INCLUDE_QUERY_STRING, queryString); wrequest.setQueryParams(queryString); } wrequest.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, type); wrequest.setAttribute( ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); invoke(state.outerRequest, state.outerResponse, state); } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void invoke(ServletRequest request, ServletResponse response, State state) throws IOException, ServletException { // Checking to see if the context classloader is the current context // classloader. If it's not, we're saving it, and setting the context // classloader to the Context classloader ClassLoader oldCCL = Thread.currentThread().getContextClassLoader(); ClassLoader contextClassLoader = context.getLoader().getClassLoader(); if (oldCCL != contextClassLoader) { Thread.currentThread().setContextClassLoader(contextClassLoader); } else { oldCCL = null; } // Initialize local variables we may need HttpServletResponse hresponse = state.hresponse; Servlet servlet = null; IOException ioException = null; ServletException servletException = null; RuntimeException runtimeException = null; boolean unavailable = false; // Check for the servlet being marked unavailable if (wrapper.isUnavailable()) { wrapper.getLogger().warn( sm.getString("applicationDispatcher.isUnavailable", wrapper.getName())); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) hresponse.setDateHeader("Retry-After", available); hresponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm .getString("applicationDispatcher.isUnavailable", wrapper .getName())); unavailable = true; } // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); servletException = e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servlet = null; } // Get the FilterChain Here ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance(); ApplicationFilterChain filterChain = factory.createFilterChain(request, wrapper,servlet); // Call the service() method for the allocated servlet instance try { support.fireInstanceEvent(InstanceEvent.BEFORE_DISPATCH_EVENT, servlet, request, response); // for includes/forwards if ((servlet != null) && (filterChain != null)) { filterChain.doFilter(request, response); } // Servlet Service Method is called by the FilterChain support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); } catch (ClientAbortException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); ioException = e; } catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); ioException = e; } catch (UnavailableException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); servletException = e; wrapper.unavailable(e); } catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause); } servletException = e; } catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); runtimeException = e; } // Release the filter chain (if any) for this request try { if (filterChain != null) filterChain.release(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e); // FIXME: Exception handling needs to be similar to what is in the StandardWrapperValue } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); } // Reset the old context class loader if (oldCCL != null) Thread.currentThread().setContextClassLoader(oldCCL); // Unwrap request/response if needed // See Bugzilla 30949 unwrapRequest(state); unwrapResponse(state); // Recycle request if necessary (also BZ 30949) recycleRequestWrapper(state); // Rethrow an exception if one was thrown by the invoked servlet if (ioException != null) throw ioException; if (servletException != null) throw servletException; if (runtimeException != null) throw runtimeException; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void checkSameObjects(ServletRequest appRequest, ServletResponse appResponse) throws ServletException { ServletRequest originalRequest = ApplicationFilterChain.getLastServicedRequest(); ServletResponse originalResponse = ApplicationFilterChain.getLastServicedResponse(); // Some forwards, eg from valves will not set original values if (originalRequest == null || originalResponse == null) { return; } boolean same = false; ServletRequest dispatchedRequest = appRequest; //find the request that was passed into the service method while (originalRequest instanceof ServletRequestWrapper && ((ServletRequestWrapper) originalRequest).getRequest()!=null ) { originalRequest = ((ServletRequestWrapper) originalRequest).getRequest(); } //compare with the dispatched request while (!same) { if (originalRequest.equals(dispatchedRequest)) { same = true; } if (!same && dispatchedRequest instanceof ServletRequestWrapper) { dispatchedRequest = ((ServletRequestWrapper) dispatchedRequest).getRequest(); } else { break; } } if (!same) { throw new ServletException(sm.getString( "applicationDispatcher.specViolation.request")); } same = false; ServletResponse dispatchedResponse = appResponse; //find the response that was passed into the service method while (originalResponse instanceof ServletResponseWrapper && ((ServletResponseWrapper) originalResponse).getResponse() != null ) { originalResponse = ((ServletResponseWrapper) originalResponse).getResponse(); } //compare with the dispatched response while (!same) { if (originalResponse.equals(dispatchedResponse)) { same = true; } if (!same && dispatchedResponse instanceof ServletResponseWrapper) { dispatchedResponse = ((ServletResponseWrapper) dispatchedResponse).getResponse(); } else { break; } } if (!same) { throw new ServletException(sm.getString( "applicationDispatcher.specViolation.response")); } }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { return this._getHttpServletRequest().authenticate(response); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public void login(String username, String password) throws ServletException { this._getHttpServletRequest().login(username, password); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public void logout() throws ServletException { this._getHttpServletRequest().logout(); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public Collection<Part> getParts() throws IllegalStateException, IOException, ServletException { return this._getHttpServletRequest().getParts(); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public Part getPart(String name) throws IllegalStateException, IOException, ServletException { return this._getHttpServletRequest().getPart(name); }
// in java/javax/servlet/http/HttpServlet.java
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_get_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { NoBodyResponse response = new NoBodyResponse(resp); doGet(req, response); response.setContentLength(); }
// in java/javax/servlet/http/HttpServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_post_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_put_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_delete_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Method[] methods = getAllDeclaredMethods(this.getClass()); boolean ALLOW_GET = false; boolean ALLOW_HEAD = false; boolean ALLOW_POST = false; boolean ALLOW_PUT = false; boolean ALLOW_DELETE = false; boolean ALLOW_TRACE = true; boolean ALLOW_OPTIONS = true; for (int i=0; i<methods.length; i++) { Method m = methods[i]; if (m.getName().equals("doGet")) { ALLOW_GET = true; ALLOW_HEAD = true; } if (m.getName().equals("doPost")) ALLOW_POST = true; if (m.getName().equals("doPut")) ALLOW_PUT = true; if (m.getName().equals("doDelete")) ALLOW_DELETE = true; } String allow = null; if (ALLOW_GET) allow=METHOD_GET; if (ALLOW_HEAD) if (allow==null) allow=METHOD_HEAD; else allow += ", " + METHOD_HEAD; if (ALLOW_POST) if (allow==null) allow=METHOD_POST; else allow += ", " + METHOD_POST; if (ALLOW_PUT) if (allow==null) allow=METHOD_PUT; else allow += ", " + METHOD_PUT; if (ALLOW_DELETE) if (allow==null) allow=METHOD_DELETE; else allow += ", " + METHOD_DELETE; if (ALLOW_TRACE) if (allow==null) allow=METHOD_TRACE; else allow += ", " + METHOD_TRACE; if (ALLOW_OPTIONS) if (allow==null) allow=METHOD_OPTIONS; else allow += ", " + METHOD_OPTIONS; resp.setHeader("Allow", allow); }
// in java/javax/servlet/http/HttpServlet.java
protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int responseLength; String CRLF = "\r\n"; StringBuilder buffer = new StringBuilder("TRACE ").append(req.getRequestURI()) .append(" ").append(req.getProtocol()); Enumeration<String> reqHeaderEnum = req.getHeaderNames(); while( reqHeaderEnum.hasMoreElements() ) { String headerName = reqHeaderEnum.nextElement(); buffer.append(CRLF).append(headerName).append(": ") .append(req.getHeader(headerName)); } buffer.append(CRLF); responseLength = buffer.length(); resp.setContentType("message/http"); resp.setContentLength(responseLength); ServletOutputStream out = resp.getOutputStream(); out.print(buffer.toString()); out.close(); return; }
// in java/javax/servlet/http/HttpServlet.java
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod(); if (method.equals(METHOD_GET)) { long lastModified = getLastModified(req); if (lastModified == -1) { // servlet doesn't support if-modified-since, no reason // to go through further expensive logic doGet(req, resp); } else { long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE); if (ifModifiedSince < (lastModified / 1000 * 1000)) { // If the servlet mod time is later, call doGet() // Round down to the nearest second for a proper compare // A ifModifiedSince of -1 will always be less maybeSetLastModified(resp, lastModified); doGet(req, resp); } else { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } } } else if (method.equals(METHOD_HEAD)) { long lastModified = getLastModified(req); maybeSetLastModified(resp, lastModified); doHead(req, resp); } else if (method.equals(METHOD_POST)) { doPost(req, resp); } else if (method.equals(METHOD_PUT)) { doPut(req, resp); } else if (method.equals(METHOD_DELETE)) { doDelete(req, resp); } else if (method.equals(METHOD_OPTIONS)) { doOptions(req,resp); } else if (method.equals(METHOD_TRACE)) { doTrace(req,resp); } else { // // Note that this means NO servlet supports whatever // method was requested, anywhere on this server. // String errMsg = lStrings.getString("http.method_not_implemented"); Object[] errArgs = new Object[1]; errArgs[0] = method; errMsg = MessageFormat.format(errMsg, errArgs); resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg); } }
// in java/javax/servlet/http/HttpServlet.java
Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request; HttpServletResponse response; try { request = (HttpServletRequest) req; response = (HttpServletResponse) res; } catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); } service(request, response); }
// in java/javax/servlet/GenericServlet.java
Override public void init(ServletConfig config) throws ServletException { this.config = config; this.init(); }
// in java/javax/servlet/GenericServlet.java
public void init() throws ServletException { // NOOP by default }
(Lib) BuildException 56
              
// in java/org/apache/tomcat/buildutil/CheckEol.java
Override public void execute() throws BuildException { Mode mode = null; if ("\n".equals(eoln)) { mode = Mode.LF; } else if ("\r\n".equals(eoln)) { mode = Mode.CRLF; } else { log("Line ends check skipped, because OS line ends setting is neither LF nor CRLF.", Project.MSG_VERBOSE); return; } int count = 0; List<CheckFailure> errors = new ArrayList<CheckFailure>(); // Step through each file and check. for (FileSet fs : filesets) { DirectoryScanner ds = fs.getDirectoryScanner(getProject()); File basedir = ds.getBasedir(); String[] files = ds.getIncludedFiles(); if (files.length > 0) { log("Checking line ends in " + files.length + " file(s)"); for (int i = 0; i < files.length; i++) { File file = new File(basedir, files[i]); log("Checking file '" + file + "' for correct line ends", Project.MSG_DEBUG); try { check(file, errors, mode); } catch (IOException e) { throw new BuildException("Could not check file '" + file.getAbsolutePath() + "'", e); } count++; } } } if (count > 0) { log("Done line ends check in " + count + " file(s), " + errors.size() + " error(s) found."); } if (errors.size() > 0) { String message = "The following files have wrong line ends: " + errors; // We need to explicitly write the message to the log, because // long BuildException messages may be trimmed. E.g. I observed // this problem with Eclipse IDE 3.7. log(message, Project.MSG_ERR); throw new BuildException(message); } }
// in java/org/apache/tomcat/buildutil/Txt2Html.java
Override public void execute() throws BuildException { int count = 0; // Step through each file and convert. Iterator<FileSet> iter = filesets.iterator(); while( iter.hasNext() ) { FileSet fs = iter.next(); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); File basedir = ds.getBasedir(); String[] files = ds.getIncludedFiles(); for( int i = 0; i < files.length; i++ ) { File from = new File( basedir, files[i] ); File to = new File( todir, files[i] + ".html" ); if( !to.exists() || (from.lastModified() > to.lastModified()) ) { log( "Converting file '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath(), Project.MSG_VERBOSE ); try { convert( from, to ); } catch( IOException e ) { throw new BuildException( "Could not convert '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath() + "'", e ); } count++; } } if( count > 0 ) { log( "Converted " + count + " file" + (count > 1 ? "s" : "") + " to " + todir.getAbsolutePath() ); } } }
// in java/org/apache/catalina/ant/JMXSetTask.java
Override public void execute() throws BuildException { super.execute(); if (bean == null || attribute == null || value == null) { throw new BuildException ("Must specify 'bean', 'attribute' and 'value' attributes"); } log("Setting attribute " + attribute + " in bean " + bean + " to " + value); try { execute("/jmxproxy/?set=" + URLEncoder.encode(bean, getCharset()) + "&att=" + URLEncoder.encode(attribute, getCharset()) + "&val=" + URLEncoder.encode(value, getCharset())); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } }
// in java/org/apache/catalina/ant/ResourcesTask.java
Override public void execute() throws BuildException { super.execute(); if (type != null) { try { execute("/resources?type=" + URLEncoder.encode(type, getCharset())); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } } else { execute("/resources"); } }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
Override public void execute() throws BuildException { if ((username == null) || (password == null) || (url == null)) { throw new BuildException ("Must specify all of 'username', 'password', and 'url'"); } }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
public void execute(String command, InputStream istream, String contentType, int contentLength) throws BuildException { URLConnection conn = null; InputStreamReader reader = null; try { // Create a connection for this command conn = (new URL(url + command)).openConnection(); HttpURLConnection hconn = (HttpURLConnection) conn; // Set up standard connection characteristics hconn.setAllowUserInteraction(false); hconn.setDoInput(true); hconn.setUseCaches(false); if (istream != null) { hconn.setDoOutput(true); hconn.setRequestMethod("PUT"); if (contentType != null) { hconn.setRequestProperty("Content-Type", contentType); } if (contentLength >= 0) { hconn.setRequestProperty("Content-Length", "" + contentLength); hconn.setFixedLengthStreamingMode(contentLength); } } else { hconn.setDoOutput(false); hconn.setRequestMethod("GET"); } hconn.setRequestProperty("User-Agent", "Catalina-Ant-Task/1.0"); // Set up an authorization header with our credentials String input = username + ":" + password; String output = Base64.encode(input.getBytes(B2CConverter.ISO_8859_1)); hconn.setRequestProperty("Authorization", "Basic " + output); // Establish the connection with the server hconn.connect(); // Send the request data (if any) if (istream != null) { BufferedOutputStream ostream = new BufferedOutputStream(hconn.getOutputStream(), 1024); byte buffer[] = new byte[1024]; while (true) { int n = istream.read(buffer); if (n < 0) { break; } ostream.write(buffer, 0, n); } ostream.flush(); ostream.close(); istream.close(); } // Process the response message reader = new InputStreamReader(hconn.getInputStream(), CHARSET); StringBuilder buff = new StringBuilder(); String error = null; int msgPriority = Project.MSG_INFO; boolean first = true; while (true) { int ch = reader.read(); if (ch < 0) { break; } else if ((ch == '\r') || (ch == '\n')) { // in Win \r\n would cause handleOutput() to be called // twice, the second time with an empty string, // producing blank lines if (buff.length() > 0) { String line = buff.toString(); buff.setLength(0); if (first) { if (!line.startsWith("OK -")) { error = line; msgPriority = Project.MSG_ERR; } first = false; } handleOutput(line, msgPriority); } } else { buff.append((char) ch); } } if (buff.length() > 0) { handleOutput(buff.toString(), msgPriority); } if (error != null && isFailOnError()) { // exception should be thrown only if failOnError == true // or error line will be logged twice throw new BuildException(error); } } catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } } finally { closeRedirector(); if (reader != null) { try { reader.close(); } catch (IOException ioe) { // Ignore } reader = null; } if (istream != null) { try { istream.close(); } catch (IOException ioe) { // Ignore } } } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
Override public void execute() throws BuildException { if (testIfCondition() && testUnlessCondition()) { try { String error = null; MBeanServerConnection jmxServerConnection = getJMXConnection(); error = jmxExecute(jmxServerConnection); if (error != null && isFailOnError()) { // exception should be thrown only if failOnError == true // or error line will be logged twice throw new BuildException(error); } } catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } } finally { closeRedirector(); } } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if ((jmxServerConnection == null)) { throw new BuildException("Must open a connection!"); } else if (isEcho()) { handleOutput("JMX Connection ref=" + ref + " is open!"); } return null; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorSetTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((attribute == null || value == null)) { throw new BuildException( "Must specify a 'attribute' and 'value' for set"); } return jmxSet(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorEqualsCondition.java
Override public boolean eval() { if (value == null) { throw new BuildException("value attribute is not set"); } if ((name == null || attribute == null)) { throw new BuildException( "Must specify a 'attribute', name for equals condition"); } //FIXME check url or host/parameter String jmxValue = accessJMXValue(); if(jmxValue != null) return jmxValue.equals(value); return false; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorGetTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((attribute == null)) { throw new BuildException( "Must specify a 'attribute' for get"); } return jmxGet(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorCondition.java
Override public boolean eval() { if (operation == null) { throw new BuildException("operation attribute is not set"); } if (value == null) { throw new BuildException("value attribute is not set"); } if ((name == null || attribute == null)) { throw new BuildException( "Must specify a 'attribute', name for equals condition"); } if (testIfCondition() && testUnlessCondition()) { String jmxValue = accessJMXValue(); if (jmxValue != null) { String op = getOperation(); if ("==".equals(op)) { return jmxValue.equals(value); } else if ("!=".equals(op)) { return !jmxValue.equals(value); } else { if ("long".equals(type)) { long jvalue = Long.parseLong(jmxValue); long lvalue = Long.parseLong(value); if (">".equals(op)) { return jvalue > lvalue; } else if (">=".equals(op)) { return jvalue >= lvalue; } else if ("<".equals(op)) { return jvalue < lvalue; } else if ("<=".equals(op)) { return jvalue <= lvalue; } } else if ("double".equals(type)) { double jvalue = Double.parseDouble(jmxValue); double dvalue = Double.parseDouble(value); if (">".equals(op)) { return jvalue > dvalue; } else if (">=".equals(op)) { return jvalue >= dvalue; } else if ("<".equals(op)) { return jvalue < dvalue; } else if ("<=".equals(op)) { return jvalue <= dvalue; } } } } return false; } return true; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } return jmxQuery(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorUnregisterTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } return jmxUuregister(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorCreateTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((className == null)) { throw new BuildException( "Must specify a 'className' for get"); } return jmxCreate(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorInvokeTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((operation == null)) { throw new BuildException( "Must specify a 'operation' for call"); } return jmxInvoke(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/JMXGetTask.java
Override public void execute() throws BuildException { super.execute(); if (bean == null || attribute == null) { throw new BuildException ("Must specify 'bean' and 'attribute' attributes"); } log("Getting attribute " + attribute + " in bean " + bean ); try { execute("/jmxproxy/?get=" + URLEncoder.encode(bean, getCharset()) + "&att=" + URLEncoder.encode(attribute, getCharset())); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } }
// in java/org/apache/catalina/ant/ValidatorTask.java
Override public void execute() throws BuildException { if (path == null) { throw new BuildException("Must specify 'path'"); } File file = new File(path, Constants.ApplicationWebXml); if ((!file.exists()) || (!file.canRead())) { throw new BuildException("Cannot find web.xml"); } // Commons-logging likes having the context classloader set ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader (ValidatorTask.class.getClassLoader()); Digester digester = DigesterFactory.newDigester(true, true, null); try { file = file.getCanonicalFile(); InputStream stream = new BufferedInputStream(new FileInputStream(file)); InputSource is = new InputSource(file.toURI().toURL().toExternalForm()); is.setByteStream(stream); digester.parse(is); handleOutput("web.xml validated"); } catch (Exception e) { if (isFailOnError()) { throw new BuildException("Validation failure", e); } else { handleErrorOutput("Validation failure: " + e); } } finally { Thread.currentThread().setContextClassLoader(oldCL); closeRedirector(); } }
// in java/org/apache/catalina/ant/AbstractCatalinaCommandTask.java
public StringBuilder createQueryString(String command) throws BuildException { StringBuilder buffer = new StringBuilder(); try { buffer.append(command); if (path == null) { throw new BuildException("Must specify 'path' attribute"); } else { buffer.append("?path="); buffer.append(URLEncoder.encode(this.path, getCharset())); if (this.version != null) { buffer.append("&version="); buffer.append(URLEncoder.encode(this.version, getCharset())); } } } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } return buffer; }
// in java/org/apache/catalina/ant/JKStatusUpdateTask.java
private StringBuilder createLink() { // Building URL StringBuilder sb = new StringBuilder(); try { sb.append("?cmd=update&mime=txt"); sb.append("&w="); sb.append(URLEncoder.encode(worker, getCharset())); if (isLBMode) { //http://localhost/status?cmd=update&mime=txt&w=lb&lf=false&ls=true if ((lbRetries != null)) { // > 0 sb.append("&lr="); sb.append(lbRetries); } if ((lbRecovertime != null)) { // > 59 sb.append("&lt="); sb.append(lbRecovertime); } if ((lbStickySession != null)) { sb.append("&ls="); sb.append(lbStickySession); } if ((lbForceSession != null)) { sb.append("&lf="); sb.append(lbForceSession); } } else { //http://localhost/status?cmd=update&mime=txt&w=node1&l=lb&wf=1&wd=false&ws=false if ((workerLb != null)) { // must be configured sb.append("&l="); sb.append(URLEncoder.encode(workerLb, getCharset())); } if ((workerLoadFactor != null)) { // >= 1 sb.append("&wf="); sb.append(workerLoadFactor); } if ((workerDisabled != null)) { sb.append("&wd="); sb.append(workerDisabled); } if ((workerStopped != null)) { sb.append("&ws="); sb.append(workerStopped); } if ((workerRedirect != null)) { // other worker conrecte lb's sb.append("&wr="); } if ((workerClusterDomain != null)) { sb.append("&wc="); sb.append(URLEncoder.encode(workerClusterDomain, getCharset())); } } } catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); } return sb; }
// in java/org/apache/catalina/ant/JKStatusUpdateTask.java
protected void checkParameter() { if (worker == null) { throw new BuildException("Must specify 'worker' attribute"); } if (workerType == null) { throw new BuildException("Must specify 'workerType' attribute"); } if ("lb".equals(workerType)) { if (lbRecovertime == null && lbRetries == null) { throw new BuildException( "Must specify at a lb worker either 'lbRecovertime' or" + "'lbRetries' attribute"); } if (lbStickySession == null || lbForceSession == null) { throw new BuildException("Must specify at a lb worker either" + "'lbStickySession' and 'lbForceSession' attribute"); } if (null != lbRecovertime && 60 < lbRecovertime.intValue()) { throw new BuildException( "The 'lbRecovertime' must be greater than 59"); } if (null != lbRetries && 1 < lbRetries.intValue()) { throw new BuildException( "The 'lbRetries' must be greater than 1"); } isLBMode = true; } else if ("worker".equals(workerType)) { if (workerDisabled == null) { throw new BuildException( "Must specify at a node worker 'workerDisabled' attribute"); } if (workerStopped == null) { throw new BuildException( "Must specify at a node worker 'workerStopped' attribute"); } if (workerLoadFactor == null ) { throw new BuildException( "Must specify at a node worker 'workerLoadFactor' attribute"); } if (workerClusterDomain == null) { throw new BuildException( "Must specify at a node worker 'workerClusterDomain' attribute"); } if (workerRedirect == null) { throw new BuildException( "Must specify at a node worker 'workerRedirect' attribute"); } if (workerLb == null) { throw new BuildException("Must specify 'workerLb' attribute"); } if (workerLoadFactor.intValue() < 1) { throw new BuildException( "The 'workerLoadFactor' must be greater or equal 1"); } isLBMode = false; } else { throw new BuildException( "Only 'lb' and 'worker' supported as workerType attribute"); } }
// in java/org/apache/catalina/ant/DeployTask.java
Override public void execute() throws BuildException { super.execute(); if (path == null) { throw new BuildException ("Must specify 'path' attribute"); } if ((war == null) && (localWar == null) && (config == null) && (tag == null)) { throw new BuildException ("Must specify either 'war', 'localWar', 'config', or 'tag' attribute"); } // Building an input stream on the WAR to upload, if any BufferedInputStream stream = null; String contentType = null; int contentLength = -1; if (war != null) { if (war.startsWith("file:")) { try { URL url = new URL(war); URLConnection conn = url.openConnection(); contentLength = conn.getContentLength(); stream = new BufferedInputStream (conn.getInputStream(), 1024); } catch (IOException e) { throw new BuildException(e); } } else { try { FileInputStream fsInput = new FileInputStream(war); long size = fsInput.getChannel().size(); if (size > Integer.MAX_VALUE) throw new UnsupportedOperationException( "DeployTask does not support WAR files " + "greater than 2 Gb"); contentLength = (int) size; stream = new BufferedInputStream(fsInput, 1024); } catch (IOException e) { throw new BuildException(e); } } contentType = "application/octet-stream"; } // Building URL StringBuilder sb = new StringBuilder("/deploy?path="); try { sb.append(URLEncoder.encode(this.path, getCharset())); if ((war == null) && (config != null)) { sb.append("&config="); sb.append(URLEncoder.encode(config, getCharset())); } if ((war == null) && (localWar != null)) { sb.append("&war="); sb.append(URLEncoder.encode(localWar, getCharset())); } if (update) { sb.append("&update=true"); } if (tag != null) { sb.append("&tag="); sb.append(URLEncoder.encode(tag, getCharset())); } } catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); } execute(sb.toString(), stream, contentType, contentLength); }
// in java/org/apache/catalina/ant/BaseRedirectorHelperTask.java
public void addConfiguredRedirector(RedirectorElement redirectorElement) { if (this.redirectorElement != null) { throw new BuildException("Cannot have > 1 nested <redirector>s"); } else { this.redirectorElement = redirectorElement; } }
// in java/org/apache/catalina/ant/JMXQueryTask.java
Override public void execute() throws BuildException { super.execute(); String queryString; if (query == null) { queryString = ""; } else { try { queryString = "?qry=" + URLEncoder.encode(query, getCharset()); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } } log("Query string is " + queryString); execute ("/jmxproxy/" + queryString); }
14
              
// in java/org/apache/tomcat/buildutil/CheckEol.java
catch (IOException e) { throw new BuildException("Could not check file '" + file.getAbsolutePath() + "'", e); }
// in java/org/apache/tomcat/buildutil/Txt2Html.java
catch( IOException e ) { throw new BuildException( "Could not convert '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath() + "'", e ); }
// in java/org/apache/catalina/ant/JMXSetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/ResourcesTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/JMXGetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/ValidatorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException("Validation failure", e); } else { handleErrorOutput("Validation failure: " + e); } }
// in java/org/apache/catalina/ant/AbstractCatalinaCommandTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JKStatusUpdateTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (IOException e) { throw new BuildException(e); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (IOException e) { throw new BuildException(e); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JMXQueryTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
22
              
// in java/org/apache/tomcat/buildutil/CheckEol.java
Override public void execute() throws BuildException { Mode mode = null; if ("\n".equals(eoln)) { mode = Mode.LF; } else if ("\r\n".equals(eoln)) { mode = Mode.CRLF; } else { log("Line ends check skipped, because OS line ends setting is neither LF nor CRLF.", Project.MSG_VERBOSE); return; } int count = 0; List<CheckFailure> errors = new ArrayList<CheckFailure>(); // Step through each file and check. for (FileSet fs : filesets) { DirectoryScanner ds = fs.getDirectoryScanner(getProject()); File basedir = ds.getBasedir(); String[] files = ds.getIncludedFiles(); if (files.length > 0) { log("Checking line ends in " + files.length + " file(s)"); for (int i = 0; i < files.length; i++) { File file = new File(basedir, files[i]); log("Checking file '" + file + "' for correct line ends", Project.MSG_DEBUG); try { check(file, errors, mode); } catch (IOException e) { throw new BuildException("Could not check file '" + file.getAbsolutePath() + "'", e); } count++; } } } if (count > 0) { log("Done line ends check in " + count + " file(s), " + errors.size() + " error(s) found."); } if (errors.size() > 0) { String message = "The following files have wrong line ends: " + errors; // We need to explicitly write the message to the log, because // long BuildException messages may be trimmed. E.g. I observed // this problem with Eclipse IDE 3.7. log(message, Project.MSG_ERR); throw new BuildException(message); } }
// in java/org/apache/tomcat/buildutil/Txt2Html.java
Override public void execute() throws BuildException { int count = 0; // Step through each file and convert. Iterator<FileSet> iter = filesets.iterator(); while( iter.hasNext() ) { FileSet fs = iter.next(); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); File basedir = ds.getBasedir(); String[] files = ds.getIncludedFiles(); for( int i = 0; i < files.length; i++ ) { File from = new File( basedir, files[i] ); File to = new File( todir, files[i] + ".html" ); if( !to.exists() || (from.lastModified() > to.lastModified()) ) { log( "Converting file '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath(), Project.MSG_VERBOSE ); try { convert( from, to ); } catch( IOException e ) { throw new BuildException( "Could not convert '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath() + "'", e ); } count++; } } if( count > 0 ) { log( "Converted " + count + " file" + (count > 1 ? "s" : "") + " to " + todir.getAbsolutePath() ); } } }
// in java/org/apache/catalina/ant/JMXSetTask.java
Override public void execute() throws BuildException { super.execute(); if (bean == null || attribute == null || value == null) { throw new BuildException ("Must specify 'bean', 'attribute' and 'value' attributes"); } log("Setting attribute " + attribute + " in bean " + bean + " to " + value); try { execute("/jmxproxy/?set=" + URLEncoder.encode(bean, getCharset()) + "&att=" + URLEncoder.encode(attribute, getCharset()) + "&val=" + URLEncoder.encode(value, getCharset())); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } }
// in java/org/apache/catalina/ant/StartTask.java
Override public void execute() throws BuildException { super.execute(); execute(createQueryString("/start").toString()); }
// in java/org/apache/catalina/ant/ResourcesTask.java
Override public void execute() throws BuildException { super.execute(); if (type != null) { try { execute("/resources?type=" + URLEncoder.encode(type, getCharset())); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } } else { execute("/resources"); } }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
Override public void execute() throws BuildException { if ((username == null) || (password == null) || (url == null)) { throw new BuildException ("Must specify all of 'username', 'password', and 'url'"); } }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
public void execute(String command) throws BuildException { execute(command, null, null, -1); }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
public void execute(String command, InputStream istream, String contentType, int contentLength) throws BuildException { URLConnection conn = null; InputStreamReader reader = null; try { // Create a connection for this command conn = (new URL(url + command)).openConnection(); HttpURLConnection hconn = (HttpURLConnection) conn; // Set up standard connection characteristics hconn.setAllowUserInteraction(false); hconn.setDoInput(true); hconn.setUseCaches(false); if (istream != null) { hconn.setDoOutput(true); hconn.setRequestMethod("PUT"); if (contentType != null) { hconn.setRequestProperty("Content-Type", contentType); } if (contentLength >= 0) { hconn.setRequestProperty("Content-Length", "" + contentLength); hconn.setFixedLengthStreamingMode(contentLength); } } else { hconn.setDoOutput(false); hconn.setRequestMethod("GET"); } hconn.setRequestProperty("User-Agent", "Catalina-Ant-Task/1.0"); // Set up an authorization header with our credentials String input = username + ":" + password; String output = Base64.encode(input.getBytes(B2CConverter.ISO_8859_1)); hconn.setRequestProperty("Authorization", "Basic " + output); // Establish the connection with the server hconn.connect(); // Send the request data (if any) if (istream != null) { BufferedOutputStream ostream = new BufferedOutputStream(hconn.getOutputStream(), 1024); byte buffer[] = new byte[1024]; while (true) { int n = istream.read(buffer); if (n < 0) { break; } ostream.write(buffer, 0, n); } ostream.flush(); ostream.close(); istream.close(); } // Process the response message reader = new InputStreamReader(hconn.getInputStream(), CHARSET); StringBuilder buff = new StringBuilder(); String error = null; int msgPriority = Project.MSG_INFO; boolean first = true; while (true) { int ch = reader.read(); if (ch < 0) { break; } else if ((ch == '\r') || (ch == '\n')) { // in Win \r\n would cause handleOutput() to be called // twice, the second time with an empty string, // producing blank lines if (buff.length() > 0) { String line = buff.toString(); buff.setLength(0); if (first) { if (!line.startsWith("OK -")) { error = line; msgPriority = Project.MSG_ERR; } first = false; } handleOutput(line, msgPriority); } } else { buff.append((char) ch); } } if (buff.length() > 0) { handleOutput(buff.toString(), msgPriority); } if (error != null && isFailOnError()) { // exception should be thrown only if failOnError == true // or error line will be logged twice throw new BuildException(error); } } catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } } finally { closeRedirector(); if (reader != null) { try { reader.close(); } catch (IOException ioe) { // Ignore } reader = null; } if (istream != null) { try { istream.close(); } catch (IOException ioe) { // Ignore } } } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
Override public void execute() throws BuildException { if (testIfCondition() && testUnlessCondition()) { try { String error = null; MBeanServerConnection jmxServerConnection = getJMXConnection(); error = jmxExecute(jmxServerConnection); if (error != null && isFailOnError()) { // exception should be thrown only if failOnError == true // or error line will be logged twice throw new BuildException(error); } } catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } } finally { closeRedirector(); } } }
// in java/org/apache/catalina/ant/JMXGetTask.java
Override public void execute() throws BuildException { super.execute(); if (bean == null || attribute == null) { throw new BuildException ("Must specify 'bean' and 'attribute' attributes"); } log("Getting attribute " + attribute + " in bean " + bean ); try { execute("/jmxproxy/?get=" + URLEncoder.encode(bean, getCharset()) + "&att=" + URLEncoder.encode(attribute, getCharset())); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } }
// in java/org/apache/catalina/ant/ValidatorTask.java
Override public void execute() throws BuildException { if (path == null) { throw new BuildException("Must specify 'path'"); } File file = new File(path, Constants.ApplicationWebXml); if ((!file.exists()) || (!file.canRead())) { throw new BuildException("Cannot find web.xml"); } // Commons-logging likes having the context classloader set ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader (ValidatorTask.class.getClassLoader()); Digester digester = DigesterFactory.newDigester(true, true, null); try { file = file.getCanonicalFile(); InputStream stream = new BufferedInputStream(new FileInputStream(file)); InputSource is = new InputSource(file.toURI().toURL().toExternalForm()); is.setByteStream(stream); digester.parse(is); handleOutput("web.xml validated"); } catch (Exception e) { if (isFailOnError()) { throw new BuildException("Validation failure", e); } else { handleErrorOutput("Validation failure: " + e); } } finally { Thread.currentThread().setContextClassLoader(oldCL); closeRedirector(); } }
// in java/org/apache/catalina/ant/AbstractCatalinaCommandTask.java
public StringBuilder createQueryString(String command) throws BuildException { StringBuilder buffer = new StringBuilder(); try { buffer.append(command); if (path == null) { throw new BuildException("Must specify 'path' attribute"); } else { buffer.append("?path="); buffer.append(URLEncoder.encode(this.path, getCharset())); if (this.version != null) { buffer.append("&version="); buffer.append(URLEncoder.encode(this.version, getCharset())); } } } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } return buffer; }
// in java/org/apache/catalina/ant/StopTask.java
Override public void execute() throws BuildException { super.execute(); execute(createQueryString("/stop").toString()); }
// in java/org/apache/catalina/ant/JKStatusUpdateTask.java
Override public void execute() throws BuildException { super.execute(); checkParameter(); StringBuilder sb = createLink(); execute(sb.toString(), null, null, -1); }
// in java/org/apache/catalina/ant/UndeployTask.java
Override public void execute() throws BuildException { super.execute(); execute(createQueryString("/undeploy").toString()); }
// in java/org/apache/catalina/ant/DeployTask.java
Override public void execute() throws BuildException { super.execute(); if (path == null) { throw new BuildException ("Must specify 'path' attribute"); } if ((war == null) && (localWar == null) && (config == null) && (tag == null)) { throw new BuildException ("Must specify either 'war', 'localWar', 'config', or 'tag' attribute"); } // Building an input stream on the WAR to upload, if any BufferedInputStream stream = null; String contentType = null; int contentLength = -1; if (war != null) { if (war.startsWith("file:")) { try { URL url = new URL(war); URLConnection conn = url.openConnection(); contentLength = conn.getContentLength(); stream = new BufferedInputStream (conn.getInputStream(), 1024); } catch (IOException e) { throw new BuildException(e); } } else { try { FileInputStream fsInput = new FileInputStream(war); long size = fsInput.getChannel().size(); if (size > Integer.MAX_VALUE) throw new UnsupportedOperationException( "DeployTask does not support WAR files " + "greater than 2 Gb"); contentLength = (int) size; stream = new BufferedInputStream(fsInput, 1024); } catch (IOException e) { throw new BuildException(e); } } contentType = "application/octet-stream"; } // Building URL StringBuilder sb = new StringBuilder("/deploy?path="); try { sb.append(URLEncoder.encode(this.path, getCharset())); if ((war == null) && (config != null)) { sb.append("&config="); sb.append(URLEncoder.encode(config, getCharset())); } if ((war == null) && (localWar != null)) { sb.append("&war="); sb.append(URLEncoder.encode(localWar, getCharset())); } if (update) { sb.append("&update=true"); } if (tag != null) { sb.append("&tag="); sb.append(URLEncoder.encode(tag, getCharset())); } } catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); } execute(sb.toString(), stream, contentType, contentLength); }
// in java/org/apache/catalina/ant/ServerinfoTask.java
Override public void execute() throws BuildException { super.execute(); execute("/serverinfo"); }
// in java/org/apache/catalina/ant/SessionsTask.java
Override public void execute() throws BuildException { super.execute(); execute(createQueryString("/sessions").toString()); }
// in java/org/apache/catalina/ant/ReloadTask.java
Override public void execute() throws BuildException { super.execute(); execute(createQueryString("/reload").toString()); }
// in java/org/apache/catalina/ant/ListTask.java
Override public void execute() throws BuildException { super.execute(); execute("/list"); }
// in java/org/apache/catalina/ant/FindLeaksTask.java
Override public void execute() throws BuildException { super.execute(); execute("/findleaks?statusLine=" + Boolean.toString(statusLine)); }
// in java/org/apache/catalina/ant/JMXQueryTask.java
Override public void execute() throws BuildException { super.execute(); String queryString; if (query == null) { queryString = ""; } else { try { queryString = "?qry=" + URLEncoder.encode(query, getCharset()); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } } log("Query string is " + queryString); execute ("/jmxproxy/" + queryString); }
(Lib) RuntimeException 48
              
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
public void mapFunction(String fnQName, final Class<?> c, final String methodName, final Class<?>[] args) { java.lang.reflect.Method method; if (SecurityUtil.isPackageProtectionEnabled()) { try { method = AccessController.doPrivileged( new PrivilegedExceptionAction<Method>() { @Override public Method run() throws Exception { return c.getDeclaredMethod(methodName, args); } }); } catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); } }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
public static ProtectedFunctionMapper getMapForFunction(String fnQName, final Class<?> c, final String methodName, final Class<?>[] args) { java.lang.reflect.Method method; ProtectedFunctionMapper funcMapper; if (SecurityUtil.isPackageProtectionEnabled()) { funcMapper = AccessController.doPrivileged( new PrivilegedAction<ProtectedFunctionMapper>() { @Override public ProtectedFunctionMapper run() { return new ProtectedFunctionMapper(); } }); try { method = AccessController.doPrivileged( new PrivilegedExceptionAction<Method>() { @Override public Method run() throws Exception { return c.getDeclaredMethod(methodName, args); } }); } catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); } }
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
Override public TagFileInfo getTagFile(String shortName) { TagFileInfo tagFile = super.getTagFile(shortName); if (tagFile == null) { String path = tagFileMap.get(shortName); if (path == null) { return null; } TagInfo tagInfo = null; try { tagInfo = TagFileProcessor.parseTagFileDirectives(pc, shortName, path, pc.getJspCompilationContext().getTagFileJarResource(path), this); } catch (JasperException je) { throw new RuntimeException(je.toString(), je); } tagFile = new TagFileInfo(shortName, path, tagInfo); vec.addElement(tagFile); this.tagFiles = new TagFileInfo[vec.size()]; vec.copyInto(this.tagFiles); } return tagFile; }
// in java/org/apache/jasper/compiler/JarURLResource.java
Override public URL getEntry(String name) { try { return new URL("jar:" + jarUrl + "!/" + name); } catch (MalformedURLException e) { throw new RuntimeException("", e); } }
// in java/org/apache/jasper/JspC.java
protected void initClassLoader(JspCompilationContext clctxt) throws IOException { classPath = getClassPath(); ClassLoader jspcLoader = getClass().getClassLoader(); if (jspcLoader instanceof AntClassLoader) { classPath += File.pathSeparator + ((AntClassLoader) jspcLoader).getClasspath(); } // Turn the classPath into URLs ArrayList<URL> urls = new ArrayList<URL>(); StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { String path = tokenizer.nextToken(); try { File libFile = new File(path); urls.add(libFile.toURI().toURL()); } catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); } } File webappBase = new File(uriRoot); if (webappBase.exists()) { File classes = new File(webappBase, "/WEB-INF/classes"); try { if (classes.exists()) { classPath = classPath + File.pathSeparator + classes.getCanonicalPath(); urls.add(classes.getCanonicalFile().toURI().toURL()); } } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } File lib = new File(webappBase, "/WEB-INF/lib"); if (lib.exists() && lib.isDirectory()) { String[] libs = lib.list(); for (int i = 0; i < libs.length; i++) { if( libs[i].length() <5 ) continue; String ext=libs[i].substring( libs[i].length() - 4 ); if (! ".jar".equalsIgnoreCase(ext)) { if (".tld".equalsIgnoreCase(ext)) { log.warn("TLD files should not be placed in " + "/WEB-INF/lib"); } continue; } try { File libFile = new File(lib, libs[i]); classPath = classPath + File.pathSeparator + libFile.getAbsolutePath(); urls.add(libFile.getAbsoluteFile().toURI().toURL()); } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } } } } // What is this ?? urls.add(new File( clctxt.getRealPath("/")).getCanonicalFile().toURI().toURL()); URL urlsA[]=new URL[urls.size()]; urls.toArray(urlsA); loader = new URLClassLoader(urlsA, this.getClass().getClassLoader()); }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
Override public Binding nextElement() { try { return nextElementInternal(); } catch (NamingException e) { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public void setTicketKey(byte[] key48Bytes) { if(key48Bytes.length != 48) { throw new RuntimeException("Key must be 48 bytes"); } this.ticketKey = key48Bytes; }
// in java/org/apache/tomcat/spdy/SpdyFrame.java
public void headerName(byte[] buf, int soff, int len) { // if it's the first header, leave space for extra params and NV count. // they'll be filled in by send. if (off == 8) { if (type == SpdyConnection.TYPE_SYN_REPLY) { off = 16; } else if (type == SpdyConnection.TYPE_SYN_STREAM) { off = 20; } else if (type != SpdyConnection.TYPE_HEADERS) { off = 16; } else { throw new RuntimeException("Wrong frame type"); } } nvCount++; headerValue(buf, soff, len); }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public NetSupport getNetSupport() { if (netSupport == null) { try { Class<?> c0 = Class.forName("org.apache.tomcat.spdy.NetSupportOpenSSL"); netSupport = (NetSupport) c0.newInstance(); netSupport.setSpdyContext(this); return netSupport; } catch (Throwable t) { // ignore, openssl not supported } try { Class<?> c1 = Class.forName("org.apache.tomcat.spdy.NetSupportJava7"); netSupport = (NetSupport) c1.newInstance(); netSupport.setSpdyContext(this); return netSupport; } catch (Throwable t) { // ignore, npn not supported } // non-ssl mode must be set explicitly throw new RuntimeException("SSL NextProtoclNegotiation no supported."); } return netSupport; }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
public void ReInit(java.io.InputStream stream, String encoding) { try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jjtree.reset(); jj_gen = 0; for (int i = 0; i < 2; i++) jj_la1[i] = -1; }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
protected void stopCurrentThreadIfNeeded() { if (currentThreadShouldBeStopped()) { long lastTime = lastTimeThreadKilledItself.longValue(); if (lastTime + threadRenewalDelay < System.currentTimeMillis()) { if (lastTimeThreadKilledItself.compareAndSet(lastTime, System.currentTimeMillis() + 1)) { // OK, it's really time to dispose of this thread final String msg = sm.getString( "threadPoolExecutor.threadStoppedToAvoidPotentialLeak", Thread.currentThread().getName()); Thread.currentThread().setUncaughtExceptionHandler( new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { // yes, swallow the exception log.debug(msg); } }); throw new RuntimeException(msg); } } }
// in java/org/apache/tomcat/util/bcel/classfile/ElementValue.java
public static ElementValue readElementValue(DataInputStream dis, ConstantPool cpool) throws IOException { byte type = dis.readByte(); switch (type) { case 'B': // byte return new SimpleElementValue(PRIMITIVE_BYTE, dis .readUnsignedShort(), cpool); case 'C': // char return new SimpleElementValue(PRIMITIVE_CHAR, dis .readUnsignedShort(), cpool); case 'D': // double return new SimpleElementValue(PRIMITIVE_DOUBLE, dis .readUnsignedShort(), cpool); case 'F': // float return new SimpleElementValue(PRIMITIVE_FLOAT, dis .readUnsignedShort(), cpool); case 'I': // int return new SimpleElementValue(PRIMITIVE_INT, dis .readUnsignedShort(), cpool); case 'J': // long return new SimpleElementValue(PRIMITIVE_LONG, dis .readUnsignedShort(), cpool); case 'S': // short return new SimpleElementValue(PRIMITIVE_SHORT, dis .readUnsignedShort(), cpool); case 'Z': // boolean return new SimpleElementValue(PRIMITIVE_BOOLEAN, dis .readUnsignedShort(), cpool); case 's': // String return new SimpleElementValue(STRING, dis.readUnsignedShort(), cpool); case 'e': // Enum constant return new EnumElementValue(ENUM_CONSTANT, dis.readUnsignedShort(), dis.readUnsignedShort(), cpool); case 'c': // Class return new ClassElementValue(CLASS, dis.readUnsignedShort(), cpool); case '@': // Annotation // TODO isRuntimeVisible return new AnnotationElementValue(ANNOTATION, AnnotationEntry.read( dis, cpool), cpool); case '[': // Array int numArrayVals = dis.readUnsignedShort(); ElementValue[] evalues = new ElementValue[numArrayVals]; for (int j = 0; j < numArrayVals; j++) { evalues[j] = ElementValue.readElementValue(dis, cpool); } return new ArrayElementValue(ARRAY, evalues, cpool); default: throw new RuntimeException( "Unexpected element value kind in annotation: " + type); } }
// in java/org/apache/tomcat/util/bcel/classfile/AnnotationDefault.java
Override public Attribute copy(ConstantPool _constant_pool) { throw new RuntimeException("Not implemented yet!"); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public String constantToString( Constant c ) throws ClassFormatException { String str; int i; byte tag = c.getTag(); switch (tag) { case Constants.CONSTANT_Class: i = ((ConstantClass) c).getNameIndex(); c = getConstant(i, Constants.CONSTANT_Utf8); str = Utility.compactClassName(((ConstantUtf8) c).getBytes(), false); break; case Constants.CONSTANT_String: i = ((ConstantString) c).getStringIndex(); c = getConstant(i, Constants.CONSTANT_Utf8); str = "\"" + escape(((ConstantUtf8) c).getBytes()) + "\""; break; case Constants.CONSTANT_Utf8: str = ((ConstantUtf8) c).getBytes(); break; case Constants.CONSTANT_Double: str = String.valueOf(((ConstantDouble) c).getBytes()); break; case Constants.CONSTANT_Float: str = String.valueOf(((ConstantFloat) c).getBytes()); break; case Constants.CONSTANT_Long: str = String.valueOf(((ConstantLong) c).getBytes()); break; case Constants.CONSTANT_Integer: str = String.valueOf(((ConstantInteger) c).getBytes()); break; case Constants.CONSTANT_NameAndType: str = (constantToString(((ConstantNameAndType) c).getNameIndex(), Constants.CONSTANT_Utf8) + " " + constantToString(((ConstantNameAndType) c).getSignatureIndex(), Constants.CONSTANT_Utf8)); break; case Constants.CONSTANT_InterfaceMethodref: case Constants.CONSTANT_Methodref: case Constants.CONSTANT_Fieldref: str = (constantToString(((ConstantCP) c).getClassIndex(), Constants.CONSTANT_Class) + "." + constantToString(((ConstantCP) c).getNameAndTypeIndex(), Constants.CONSTANT_NameAndType)); break; default: // Never reached throw new RuntimeException("Unknown constant type " + tag); } return str; }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public String getConstantString( int index, byte tag ) throws ClassFormatException { Constant c; int i; c = getConstant(index, tag); /* This switch() is not that elegant, since the two classes have the * same contents, they just differ in the name of the index * field variable. * But we want to stick to the JVM naming conventions closely though * we could have solved these more elegantly by using the same * variable name or by subclassing. */ switch (tag) { case Constants.CONSTANT_Class: i = ((ConstantClass) c).getNameIndex(); break; case Constants.CONSTANT_String: i = ((ConstantString) c).getStringIndex(); break; default: throw new RuntimeException("getConstantString called with illegal tag " + tag); } // Finally get the string from the constant pool c = getConstant(i, Constants.CONSTANT_Utf8); return ((ConstantUtf8) c).getBytes(); }
// in java/org/apache/tomcat/util/bcel/classfile/EnclosingMethod.java
Override public Attribute copy(ConstantPool constant_pool) { throw new RuntimeException("Not implemented yet!"); // is this next line sufficient? // return (EnclosingMethod)clone(); }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapType.java
public void setType( byte t ) { if ((t < Constants.ITEM_Bogus) || (t > Constants.ITEM_NewObject)) { throw new RuntimeException("Illegal type for StackMapType: " + t); } type = t; }
// in java/org/apache/tomcat/util/bcel/classfile/SimpleElementValue.java
Override public String stringifyValue() { switch (type) { case PRIMITIVE_INT: ConstantInteger c = (ConstantInteger) cpool.getConstant(getIndex(), Constants.CONSTANT_Integer); return Integer.toString(c.getBytes()); case PRIMITIVE_LONG: ConstantLong j = (ConstantLong) cpool.getConstant(getIndex(), Constants.CONSTANT_Long); return Long.toString(j.getBytes()); case PRIMITIVE_DOUBLE: ConstantDouble d = (ConstantDouble) cpool.getConstant(getIndex(), Constants.CONSTANT_Double); return Double.toString(d.getBytes()); case PRIMITIVE_FLOAT: ConstantFloat f = (ConstantFloat) cpool.getConstant(getIndex(), Constants.CONSTANT_Float); return Float.toString(f.getBytes()); case PRIMITIVE_SHORT: ConstantInteger s = (ConstantInteger) cpool.getConstant(getIndex(), Constants.CONSTANT_Integer); return Integer.toString(s.getBytes()); case PRIMITIVE_BYTE: ConstantInteger b = (ConstantInteger) cpool.getConstant(getIndex(), Constants.CONSTANT_Integer); return Integer.toString(b.getBytes()); case PRIMITIVE_CHAR: ConstantInteger ch = (ConstantInteger) cpool.getConstant( getIndex(), Constants.CONSTANT_Integer); return String.valueOf((char)ch.getBytes()); case PRIMITIVE_BOOLEAN: ConstantInteger bo = (ConstantInteger) cpool.getConstant( getIndex(), Constants.CONSTANT_Integer); if (bo.getBytes() == 0) { return "false"; } return "true"; case STRING: ConstantUtf8 cu8 = (ConstantUtf8) cpool.getConstant(getIndex(), Constants.CONSTANT_Utf8); return cu8.getBytes(); default: throw new RuntimeException( "SimpleElementValue class does not know how to stringify type " + type); } }
// in java/org/apache/tomcat/util/bcel/classfile/SimpleElementValue.java
Override public void dump(DataOutputStream dos) throws IOException { dos.writeByte(type); // u1 kind of value switch (type) { case PRIMITIVE_INT: case PRIMITIVE_BYTE: case PRIMITIVE_CHAR: case PRIMITIVE_FLOAT: case PRIMITIVE_LONG: case PRIMITIVE_BOOLEAN: case PRIMITIVE_SHORT: case PRIMITIVE_DOUBLE: case STRING: dos.writeShort(getIndex()); break; default: throw new RuntimeException( "SimpleElementValue doesnt know how to write out type " + type); } }
// in java/org/apache/el/parser/ELParser.java
public void ReInit(java.io.InputStream stream, String encoding) { try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jjtree.reset(); jj_gen = 0; for (int i = 0; i < 36; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
protected static int[] commaDelimitedListToIntArray( String commaDelimitedInts) { String[] intsAsStrings = commaDelimitedListToStringArray(commaDelimitedInts); int[] ints = new int[intsAsStrings.length]; for (int i = 0; i < intsAsStrings.length; i++) { String intAsString = intsAsStrings[i]; try { ints[i] = Integer.parseInt(intAsString); } catch (NumberFormatException e) { throw new RuntimeException("Exception parsing number '" + i + "' (zero based) of comma delimited list '" + commaDelimitedInts + "'"); } } return ints; }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
Override public DataSender getNewDataSender() { try { ParallelNioSender sender = new ParallelNioSender(); AbstractSender.transferProperties(this,sender); return sender; } catch ( IOException x ) { throw new RuntimeException("Unable to open NIO selector.",x); } }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
protected void init(MapOwner owner, Channel channel, String mapContextName, long timeout, int channelSendOptions,ClassLoader[] cls) { log.info("Initializing AbstractReplicatedMap with context name:"+mapContextName); this.mapOwner = owner; this.externalLoaders = cls; this.channelSendOptions = channelSendOptions; this.channel = channel; this.rpcTimeout = timeout; this.mapname = mapContextName; //unique context is more efficient if it is stored as bytes this.mapContextName = mapContextName.getBytes(CHARSET_ISO_8859_1); if ( log.isTraceEnabled() ) log.trace("Created Lazy Map with name:"+mapContextName+", bytes:"+Arrays.toString(this.mapContextName)); //create an rpc channel and add the map as a listener this.rpcChannel = new RpcChannel(this.mapContextName, channel, this); //add this map as a message listener this.channel.addChannelListener(this); //listen for membership notifications this.channel.addMembershipListener(this); try { //broadcast our map, this just notifies other members of our existence broadcast(MapMessage.MSG_INIT, true); //transfer state from another map transferState(); //state is transferred, we are ready for messaging broadcast(MapMessage.MSG_START, true); } catch (ChannelException x) { log.warn("Unable to send map start message."); // remove listener from channel this.rpcChannel.breakdown(); this.channel.removeChannelListener(this); this.channel.removeMembershipListener(this); throw new RuntimeException("Unable to start replicated map.",x); } }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public void setValue(Serializable value) { try { if ( value != null ) valuedata = XByteBuffer.serialize(value); this.value = value; }catch ( IOException x ) { throw new RuntimeException(x); } }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public void setKey(Serializable key) { try { if (key != null) keydata = XByteBuffer.serialize(key); this.key = key; } catch (IOException x) { throw new RuntimeException(x); } }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
public String getHostname() { if ( this.hostname != null ) return hostname; else { try { if (DO_DNS_LOOKUPS) this.hostname = java.net.InetAddress.getByAddress(host).getHostName(); else this.hostname = org.apache.catalina.tribes.util.Arrays.toString(host,0,host.length,true); return this.hostname; }catch ( IOException x ) { throw new RuntimeException("Unable to parse hostname.",x); } } }
// in java/org/apache/catalina/tribes/membership/StaticMember.java
public void setHost(String host) { if ( host == null ) return; if ( host.startsWith("{") ) setHost(Arrays.fromString(host)); else try { setHostname(host); }catch (IOException x) { throw new RuntimeException(x);} }
// in java/org/apache/catalina/tribes/membership/StaticMember.java
public void setUniqueId(String id) { byte[] uuid = Arrays.fromString(id); if ( uuid==null || uuid.length != 16 ) throw new RuntimeException("UUID must be exactly 16 bytes, not:"+id); setUniqueId(uuid); }
// in java/org/apache/catalina/tribes/util/Arrays.java
public static byte[] fromString(String value) { if ( value == null ) return null; if ( !value.startsWith("{") ) throw new RuntimeException("byte arrays must be represented as {1,3,4,5,6}"); StringTokenizer t = new StringTokenizer(value,"{,}",false); byte[] result = new byte[t.countTokens()]; for (int i=0; i<result.length; i++ ) result[i] = Byte.parseByte(t.nextToken()); return result; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int read() throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.readByte()); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int available() throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.available()); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int read(final byte[] b) throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.read(b, 0, b.length)); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage() ,e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int read(final byte[] b, final int off, final int len) throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.read(b, off, len)); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public void close() throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ AccessController.doPrivileged( new PrivilegedExceptionAction<Void>(){ @Override public Void run() throws IOException{ ib.close(); return null; } }); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected Class<?> loadClassMaybePrivileged(final String className, final ClassLoader classLoader) throws ClassNotFoundException { Class<?> clazz; if (SecurityUtil.isPackageProtectionEnabled()) { try { clazz = AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() { @Override public Class<?> run() throws Exception { return loadClass(className, classLoader); } }); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); } }
// in java/org/apache/catalina/core/AsyncContextImpl.java
Override public void run() { request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCHED, null); DispatcherType type = (DispatcherType)request.getAttribute(Globals.DISPATCHER_TYPE_ATTR); try { //piggy back on the request dispatcher to ensure that filters etc get called. //TODO SERVLET3 - async should this be include/forward or a new dispatch type //javadoc suggests include with the type of DispatcherType.ASYNC request.setAttribute(Globals.DISPATCHER_TYPE_ATTR, DispatcherType.ASYNC); requestDispatcher.include(servletRequest, servletResponse); }catch (Exception x) { //log.error("Async.dispatch",x); throw new RuntimeException(x); }finally { request.setAttribute(Globals.DISPATCHER_TYPE_ATTR, type); } }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
private Object doPrivileged(final String methodName, final Object[] params) { try{ return invokeMethod(context, methodName, params); }catch(Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage(), t); } }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
private Object doPrivileged(final String methodName, final Class<?>[] clazz, Object[] params) { try{ Method method = context.getClass().getMethod(methodName, clazz); return executeMethod(method,context,params); } catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; } finally { params = null; } }
// in java/javax/servlet/http/Cookie.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e.getMessage()); } }
31
              
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
catch (JasperException je) { throw new RuntimeException(je.toString(), je); }
// in java/org/apache/jasper/compiler/JarURLResource.java
catch (MalformedURLException e) { throw new RuntimeException("", e); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (NamingException e) { throw new RuntimeException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/el/parser/ELParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/el/parser/ELParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { throw new RuntimeException("Exception parsing number '" + i + "' (zero based) of comma delimited list '" + commaDelimitedInts + "'"); }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
catch ( IOException x ) { throw new RuntimeException("Unable to open NIO selector.",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.warn("Unable to send map start message."); // remove listener from channel this.rpcChannel.breakdown(); this.channel.removeChannelListener(this); this.channel.removeMembershipListener(this); throw new RuntimeException("Unable to start replicated map.",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( IOException x ) { throw new RuntimeException(x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { throw new RuntimeException(x); }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
catch ( IOException x ) { throw new RuntimeException("Unable to parse hostname.",x); }
// in java/org/apache/catalina/tribes/membership/StaticMember.java
catch (IOException x) { throw new RuntimeException(x);}
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage() ,e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (Exception x) { //log.error("Async.dispatch",x); throw new RuntimeException(x); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch(Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage(), t); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); }
// in java/javax/servlet/http/Cookie.java
catch (CloneNotSupportedException e) { throw new RuntimeException(e.getMessage()); }
0
(Lib) EOFException 44
              
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
final boolean load(int offset, boolean changeEntity) throws IOException { // read characters int length = fCurrentEntity.mayReadChunks? (fCurrentEntity.ch.length - offset): (DEFAULT_XMLDECL_BUFFER_SIZE); int count = fCurrentEntity.reader.read(fCurrentEntity.ch, offset, length); // reset count and position boolean entityChanged = false; if (count != -1) { if (count != 0) { fCurrentEntity.count = count + offset; fCurrentEntity.position = offset; } } // end of this entity else { fCurrentEntity.count = offset; fCurrentEntity.position = offset; entityChanged = true; if (changeEntity) { endEntity(); if (fCurrentEntity == null) { throw new EOFException(); } // handle the trailing edges if (fCurrentEntity.position == fCurrentEntity.count) { load(0, false); } } } return entityChanged; }
// in java/org/apache/jasper/JspC.java
protected void mergeIntoWebXml() throws IOException { File webappBase = new File(uriRoot); File webXml = new File(webappBase, "WEB-INF/web.xml"); File webXml2 = new File(webappBase, "WEB-INF/web2.xml"); String insertStartMarker = Localizer.getMessage("jspc.webinc.insertStart"); String insertEndMarker = Localizer.getMessage("jspc.webinc.insertEnd"); BufferedReader reader = new BufferedReader(openWebxmlReader(webXml)); BufferedReader fragmentReader = new BufferedReader( openWebxmlReader(new File(webxmlFile))); PrintWriter writer = new PrintWriter(openWebxmlWriter(webXml2)); // Insert the <servlet> and <servlet-mapping> declarations boolean inserted = false; int current = reader.read(); while (current > -1) { if (current == '<') { String element = getElement(reader); if (!inserted && insertBefore.contains(element)) { // Insert generated content here writer.println(insertStartMarker); while (true) { String line = fragmentReader.readLine(); if (line == null) { writer.println(); break; } writer.println(line); } writer.println(insertEndMarker); writer.println(); writer.write(element); inserted = true; } else if (element.equals(insertStartMarker)) { // Skip the previous auto-generated content while (true) { current = reader.read(); if (current < 0) { throw new EOFException(); } if (current == '<') { element = getElement(reader); if (element.equals(insertEndMarker)) { break; } } } current = reader.read(); while (current == '\n' || current == '\r') { current = reader.read(); } continue; } else { writer.write(element); } } else { writer.write(current); } current = reader.read(); } writer.close(); reader.close(); fragmentReader.close(); FileInputStream fis = new FileInputStream(webXml2); FileOutputStream fos = new FileOutputStream(webXml); byte buf[] = new byte[512]; while (true) { int n = fis.read(buf); if (n < 0) { break; } fos.write(buf, 0, n); } fis.close(); fos.close(); if(!webXml2.delete() && log.isDebugEnabled()) log.debug(Localizer.getMessage("jspc.delete.fail", webXml2.toString())); if (!(new File(webxmlFile)).delete() && log.isDebugEnabled()) log.debug(Localizer.getMessage("jspc.delete.fail", webxmlFile)); }
// in java/org/apache/jasper/JspC.java
private String getElement(Reader reader) throws IOException { StringBuilder result = new StringBuilder(); result.append('<'); boolean done = false; while (!done) { int current = reader.read(); while (current != '>') { if (current < 0) { throw new EOFException(); } result.append((char) current); current = reader.read(); } result.append((char) current); int len = result.length(); if (len > 4 && result.substring(0, 4).equals("<!--")) { // This is a comment - make sure we are at the end if (len >= 7 && result.substring(len - 3, len).equals("-->")) { done = true; } } else { done = true; } } return result.toString(); }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
private int readSocket(byte[] buf, int pos, int n, boolean block) throws IOException { int nRead = 0; socket.getBufHandler().getReadBuffer().clear(); socket.getBufHandler().getReadBuffer().limit(n); if ( block ) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled."); nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout()); } catch ( EOFException eof ) { nRead = -1; } finally { if ( selector != null ) pool.put(selector); } } else { nRead = socket.read(socket.getBufHandler().getReadBuffer()); } if (nRead > 0) { socket.getBufHandler().getReadBuffer().flip(); socket.getBufHandler().getReadBuffer().limit(nRead); socket.getBufHandler().getReadBuffer().get(buf, pos, nRead); return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("iib.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
private int readSocket(boolean timeout, boolean block) throws IOException { int nRead = 0; socket.getBufHandler().getReadBuffer().clear(); if ( block ) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled."); nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout()); } catch ( EOFException eof ) { nRead = -1; } finally { if ( selector != null ) pool.put(selector); } } else { nRead = socket.read(socket.getBufHandler().getReadBuffer()); } if (nRead > 0) { socket.getBufHandler().getReadBuffer().flip(); socket.getBufHandler().getReadBuffer().limit(nRead); expand(nRead + pos); socket.getBufHandler().getReadBuffer().get(buf, pos, nRead); lastValid = pos + nRead; return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("iib.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
private int readSocket(boolean block, byte[] bytes, int offset, int len) throws IOException { int nRead = 0; nioChannel.getBufHandler().getReadBuffer().clear(); nioChannel.getBufHandler().getReadBuffer().limit(len); if (block) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) nioChannel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled."); } nRead = pool.read(nioChannel.getBufHandler().getReadBuffer(), nioChannel, selector, att.getTimeout()); } catch (EOFException eof) { nRead = -1; } finally { if (selector != null) { pool.put(selector); } } } else { nRead = nioChannel.read(nioChannel.getBufHandler().getReadBuffer()); } if (nRead > 0) { nioChannel.getBufHandler().getReadBuffer().flip(); nioChannel.getBufHandler().getReadBuffer().limit(nRead); nioChannel.getBufHandler().getReadBuffer().get(bytes, offset, nRead); return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("nio.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
private boolean parseHeader() throws IOException { MimeHeaders headers = request.getMimeHeaders(); byte chr = 0; while (true) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr == Constants.CR) || (chr == Constants.LF)) { if (chr == Constants.LF) { pos++; return false; } } else { break; } pos++; } // Mark the current buffer position int start = trailingHeaders.getEnd(); // // Reading the header name // Header name is always US-ASCII // boolean colon = false; while (!colon) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr >= Constants.A) && (chr <= Constants.Z)) { chr = (byte) (chr - Constants.LC_OFFSET); } if (chr == Constants.COLON) { colon = true; } else { trailingHeaders.append(chr); } pos++; } MessageBytes headerValue = headers.addValue(trailingHeaders.getBytes(), start, trailingHeaders.getEnd() - start); // Mark the current buffer position start = trailingHeaders.getEnd(); // // Reading the header value (which can be spanned over multiple lines) // boolean eol = false; boolean validLine = true; int lastSignificantChar = 0; while (validLine) { boolean space = true; // Skipping spaces while (space) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr == Constants.SP) || (chr == Constants.HT)) { pos++; } else { space = false; } } // Reading bytes until the end of the line while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if (chr == Constants.CR) { // Skip } else if (chr == Constants.LF) { eol = true; } else if (chr == Constants.SP) { trailingHeaders.append(chr); } else { trailingHeaders.append(chr); lastSignificantChar = trailingHeaders.getEnd(); } pos++; } // Checking the first character of the new line. If the character // is a LWS, then it's a multiline header // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr != Constants.SP) && (chr != Constants.HT)) { validLine = false; } else { eol = false; // Copying one extra space in the buffer (since there must // be at least one space inserted between the lines) trailingHeaders.append(chr); } } // Set the header value headerValue.setBytes(trailingHeaders.getBytes(), start, lastSignificantChar - start); return true; }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableDataOnly) throws IOException { int start = 0; // // Skipping blank lines // byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; // Mark the current buffer position start = pos; // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, start, pos - start); } pos++; } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; int end = 0; int questionPos = -1; // // Reading the URI // boolean eol = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request eol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (questionPos == -1)) { questionPos = pos; } pos++; } request.unparsedURI().setBytes(buf, start, end - start); if (questionPos >= 0) { request.queryString().setBytes(buf, questionPos + 1, end - questionPos - 1); request.requestURI().setBytes(buf, start, questionPos - start); } else { request.requestURI().setBytes(buf, start, end - start); } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; eol = true; } pos++; } if ((end - start) > 0) { request.protocol().setBytes(buf, start, end - start); } else { request.protocol().setString(""); } return true; }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
private void skipLine(int start) throws IOException { boolean eol = false; int lastRealByte = start; if (pos - 1 > start) { lastRealByte = pos - 1; } while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { // Skip } else if (buf[pos] == Constants.LF) { eol = true; } else { lastRealByte = pos; } pos++; } if (log.isDebugEnabled()) { log.debug(sm.getString("iib.invalidheader", new String(buf, start, lastRealByte - start + 1, Charset.forName("ISO-8859-1")))); } }
// in java/org/apache/coyote/http11/Http11Processor.java
Override protected void setRequestLineReadTimeout() throws IOException { /* * When there is no data in the buffer and this is not the first * request on this connection and timeouts are being used the * first read for this request may need a different timeout to * take account of time spent waiting for a processing thread. * * This is a little hacky but better than exposing the socket * and the timeout info to the InputBuffer */ if (inputBuffer.lastValid == 0 && socket.getLastAccess() > -1) { int firstReadTimeout; if (keepAliveTimeout == -1) { firstReadTimeout = 0; } else { long queueTime = System.currentTimeMillis() - socket.getLastAccess(); if (queueTime >= keepAliveTimeout) { // Queued for longer than timeout but there might be // data so use shortest possible timeout firstReadTimeout = 1; } else { // Cast is safe since queueTime must be less than // keepAliveTimeout which is an int firstReadTimeout = keepAliveTimeout - (int) queueTime; } } socket.getSocket().setSoTimeout(firstReadTimeout); if (!inputBuffer.fill()) { throw new EOFException(sm.getString("iib.eof.error")); } // Once the first byte has been read, the standard timeout should be // used so restore it here. socket.getSocket().setSoTimeout(endpoint.getSoTimeout()); } }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableData) throws IOException { int start = 0; // // Skipping blank lines // byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (useAvailableData) { return false; } if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; // Mark the current buffer position start = pos; if (pos >= lastValid) { if (useAvailableData) { return false; } if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, start, pos - start); } pos++; } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; int end = 0; int questionPos = -1; // // Reading the URI // boolean eol = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request eol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (questionPos == -1)) { questionPos = pos; } pos++; } request.unparsedURI().setBytes(buf, start, end - start); if (questionPos >= 0) { request.queryString().setBytes(buf, questionPos + 1, end - questionPos - 1); request.requestURI().setBytes(buf, start, questionPos - start); } else { request.requestURI().setBytes(buf, start, end - start); } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; eol = true; } pos++; } if ((end - start) > 0) { request.protocol().setBytes(buf, start, end - start); } else { request.protocol().setString(""); } return true; }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
private void skipLine(int start) throws IOException { boolean eol = false; int lastRealByte = start; if (pos - 1 > start) { lastRealByte = pos - 1; } while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { // Skip } else if (buf[pos] == Constants.LF) { eol = true; } else { lastRealByte = pos; } pos++; } if (log.isDebugEnabled()) { log.debug(sm.getString("iib.invalidheader", new String(buf, start, lastRealByte - start + 1, Charset.forName("ISO-8859-1")))); } }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int write(ByteBuffer buf, NioChannel socket, long writeTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int written = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) && buf.hasRemaining()) { if (keycount > 0) { //only write if we were registered for a write int cnt = socket.write(buf); //write the data if (cnt == -1) throw new EOFException(); written += cnt; if (cnt > 0) { time = System.currentTimeMillis(); //reset our timeout timer continue; //we successfully wrote, try again without a selector } } try { if ( att.getWriteLatch()==null || att.getWriteLatch().getCount()==0) att.startWriteLatch(1); poller.add(att,SelectionKey.OP_WRITE,reference); if (writeTimeout < 0) { att.awaitWriteLatch(Long.MAX_VALUE,TimeUnit.MILLISECONDS); } else { att.awaitWriteLatch(writeTimeout,TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getWriteLatch()!=null && att.getWriteLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetWriteLatch(); } if (writeTimeout > 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= writeTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_WRITE); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return written; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int read(ByteBuffer buf, NioChannel socket, long readTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int read = 0; boolean timedout = false; int keycount = 1; //assume we can read long time = System.currentTimeMillis(); //start the timeout timer try { while(!timedout) { if (keycount > 0) { //only read if we were registered for a read read = socket.read(buf); if (read == -1) throw new EOFException(); if (read > 0) break; } try { if ( att.getReadLatch()==null || att.getReadLatch().getCount()==0) att.startReadLatch(1); poller.add(att,SelectionKey.OP_READ, reference); if (readTimeout < 0) { att.awaitReadLatch(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } else { att.awaitReadLatch(readTimeout, TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getReadLatch()!=null && att.getReadLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetReadLatch(); } if (readTimeout >= 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= readTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_READ); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return read; }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int write(ByteBuffer buf, NioChannel socket, Selector selector, long writeTimeout, boolean block) throws IOException { if ( SHARED && block ) { return blockingSelector.write(buf,socket,writeTimeout); } SelectionKey key = null; int written = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) && buf.hasRemaining() ) { int cnt = 0; if ( keycount > 0 ) { //only write if we were registered for a write cnt = socket.write(buf); //write the data if (cnt == -1) throw new EOFException(); written += cnt; if (cnt > 0) { time = System.currentTimeMillis(); //reset our timeout timer continue; //we successfully wrote, try again without a selector } if (cnt==0 && (!block)) break; //don't block } if ( selector != null ) { //register OP_WRITE to the selector if (key==null) key = socket.getIOChannel().register(selector, SelectionKey.OP_WRITE); else key.interestOps(SelectionKey.OP_WRITE); keycount = selector.select(writeTimeout); } if (writeTimeout > 0 && (selector == null || keycount == 0) ) timedout = (System.currentTimeMillis()-time)>=writeTimeout; }//while if ( timedout ) throw new SocketTimeoutException(); } finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } } return written; }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int read(ByteBuffer buf, NioChannel socket, Selector selector, long readTimeout, boolean block) throws IOException { if ( SHARED && block ) { return blockingSelector.read(buf,socket,readTimeout); } SelectionKey key = null; int read = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) ) { int cnt = 0; if ( keycount > 0 ) { //only read if we were registered for a read cnt = socket.read(buf); if (cnt == -1) throw new EOFException(); read += cnt; if (cnt > 0) continue; //read some more if (cnt==0 && (read>0 || (!block) ) ) break; //we are done reading } if ( selector != null ) {//perform a blocking read //register OP_WRITE to the selector if (key==null) key = socket.getIOChannel().register(selector, SelectionKey.OP_READ); else key.interestOps(SelectionKey.OP_READ); keycount = selector.select(readTimeout); } if (readTimeout > 0 && (selector == null || keycount == 0) ) timedout = (System.currentTimeMillis()-time)>=readTimeout; }//while if ( timedout ) throw new SocketTimeoutException(); } finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } } return read; }
// in java/org/apache/catalina/websocket/WsFrame.java
public static WsFrame nextFrame(UpgradeProcessor<?> processor, boolean block) throws IOException { byte[] first = new byte[1]; int read = processor.read(block, first, 0, 1); if (read == 1) { return new WsFrame(first[0], processor); } else if (read == 0) { return null; } else if (read == -1) { throw new EOFException(sm.getString("frame.readEos")); } else { throw new IOException( sm.getString("frame.readFailed", Integer.valueOf(read))); } }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
protected boolean write() throws IOException { if ( (!isConnected()) || (this.socketChannel==null && this.dataChannel==null)) { throw new IOException("NioSender is not connected, this should not occur."); } if ( current != null ) { if ( remaining > 0 ) { //we have written everything, or we are starting a new package //protect against buffer overwrite int byteswritten = isUdpBased()?dataChannel.write(writebuf) : socketChannel.write(writebuf); if (byteswritten == -1 ) throw new EOFException(); remaining -= byteswritten; //if the entire message was written from the buffer //reset the position counter if ( remaining < 0 ) { remaining = 0; } } return (remaining==0); } //no message to send, we can consider that complete return true; }
0 2
              
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override protected boolean fill(boolean block) throws IOException, EOFException { return fill(true,block); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
protected boolean fill(boolean timeout, boolean block) throws IOException, EOFException { boolean read = false; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } // Do a simple read with a short timeout read = readSocket(timeout,block)>0; } else { lastValid = pos = end; // Do a simple read with a short timeout read = readSocket(timeout, block)>0; } return read; }
(Lib) NamingException 36
              
// in java/org/apache/naming/factory/ResourceEnvFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof ResourceEnvRef) { Reference ref = (Reference) obj; ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } } // Note: No defaults here if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/factory/BeanFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws NamingException { if (obj instanceof ResourceRef) { try { Reference ref = (Reference) obj; String beanClassName = ref.getClassName(); Class<?> beanClass = null; ClassLoader tcl = Thread.currentThread().getContextClassLoader(); if (tcl != null) { try { beanClass = tcl.loadClass(beanClassName); } catch(ClassNotFoundException e) { } } else { try { beanClass = Class.forName(beanClassName); } catch(ClassNotFoundException e) { e.printStackTrace(); } } if (beanClass == null) { throw new NamingException ("Class not found: " + beanClassName); } BeanInfo bi = Introspector.getBeanInfo(beanClass); PropertyDescriptor[] pda = bi.getPropertyDescriptors(); Object bean = beanClass.newInstance(); Enumeration<RefAddr> e = ref.getAll(); while (e.hasMoreElements()) { RefAddr ra = e.nextElement(); String propName = ra.getType(); if (propName.equals(Constants.FACTORY) || propName.equals("scope") || propName.equals("auth") || propName.equals("singleton")) { continue; } String value = (String)ra.getContent(); Object[] valueArray = new Object[1]; int i = 0; for (i = 0; i<pda.length; i++) { if (pda[i].getName().equals(propName)) { Class<?> propType = pda[i].getPropertyType(); if (propType.equals(String.class)) { valueArray[0] = value; } else if (propType.equals(Character.class) || propType.equals(char.class)) { valueArray[0] = Character.valueOf(value.charAt(0)); } else if (propType.equals(Byte.class) || propType.equals(byte.class)) { valueArray[0] = new Byte(value); } else if (propType.equals(Short.class) || propType.equals(short.class)) { valueArray[0] = new Short(value); } else if (propType.equals(Integer.class) || propType.equals(int.class)) { valueArray[0] = new Integer(value); } else if (propType.equals(Long.class) || propType.equals(long.class)) { valueArray[0] = new Long(value); } else if (propType.equals(Float.class) || propType.equals(float.class)) { valueArray[0] = new Float(value); } else if (propType.equals(Double.class) || propType.equals(double.class)) { valueArray[0] = new Double(value); } else if (propType.equals(Boolean.class) || propType.equals(boolean.class)) { valueArray[0] = Boolean.valueOf(value); } else { throw new NamingException ("String conversion for property type '" + propType.getName() + "' not available"); } Method setProp = pda[i].getWriteMethod(); if (setProp != null) { setProp.invoke(bean, valueArray); } else { throw new NamingException ("Write not allowed for property: " + propName); } break; } } if (i == pda.length) { throw new NamingException ("No set method found for property: " + propName); } } return bean; } catch (java.beans.IntrospectionException ie) { NamingException ne = new NamingException(ie.getMessage()); ne.setRootCause(ie); throw ne; } catch (java.lang.IllegalAccessException iae) { NamingException ne = new NamingException(iae.getMessage()); ne.setRootCause(iae); throw ne; } catch (java.lang.InstantiationException ie2) { NamingException ne = new NamingException(ie2.getMessage()); ne.setRootCause(ie2); throw ne; } catch (java.lang.reflect.InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } NamingException ne = new NamingException(ite.getMessage()); ne.setRootCause(ite); throw ne; } } else { return null; } }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof ServiceRef) { Reference ref = (Reference) obj; // ClassLoader ClassLoader tcl = Thread.currentThread().getContextClassLoader(); if (tcl == null) tcl = this.getClass().getClassLoader(); ServiceFactory factory = ServiceFactory.newInstance(); javax.xml.rpc.Service service = null; // Service Interface RefAddr tmp = ref.get(ServiceRef.SERVICE_INTERFACE); String serviceInterface = null; if (tmp != null) serviceInterface = (String) tmp.getContent(); // WSDL tmp = ref.get(ServiceRef.WSDL); String wsdlRefAddr = null; if (tmp != null) wsdlRefAddr = (String) tmp.getContent(); // PortComponent Hashtable<String,QName> portComponentRef = new Hashtable<String,QName>(); // Create QName object QName serviceQname = null; tmp = ref.get(ServiceRef.SERVICE_LOCAL_PART); if (tmp != null) { String serviceLocalPart = (String) tmp.getContent(); tmp = ref.get(ServiceRef.SERVICE_NAMESPACE); if (tmp == null) { serviceQname = new QName(serviceLocalPart); } else { String serviceNamespace = (String) tmp.getContent(); serviceQname = new QName(serviceNamespace, serviceLocalPart); } } Class<?> serviceInterfaceClass = null; // Create service object if (serviceInterface == null) { if (serviceQname == null) { throw new NamingException ("Could not create service-ref instance"); } try { if (wsdlRefAddr == null) { service = factory.createService( serviceQname ); } else { service = factory.createService( new URL(wsdlRefAddr), serviceQname ); } } catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; } } else { // Loading service Interface try { serviceInterfaceClass = tcl.loadClass(serviceInterface); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load service Interface"); ex.initCause(e); throw ex; } if (serviceInterfaceClass == null) { throw new NamingException ("Could not load service Interface"); } try { if (wsdlRefAddr == null) { if (!Service.class.isAssignableFrom(serviceInterfaceClass)) { throw new NamingException ("service Interface should extend javax.xml.rpc.Service"); } service = factory.loadService( serviceInterfaceClass ); } else { service = factory.loadService( new URL(wsdlRefAddr), serviceInterfaceClass, new Properties() ); } } catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; } } if (service == null) { throw new NamingException ("Cannot create service object"); } serviceQname = service.getServiceName(); serviceInterfaceClass = service.getClass(); if (wsdlRefAddr != null) { try { WSDLFactory wsdlfactory = WSDLFactory.newInstance(); WSDLReader reader = wsdlfactory.newWSDLReader(); reader.setFeature("javax.wsdl.importDocuments", true); Definition def = reader.readWSDL((new URL(wsdlRefAddr)).toExternalForm()); javax.wsdl.Service wsdlservice = def.getService(serviceQname); @SuppressWarnings("unchecked") // Can't change the API Map<String,?> ports = wsdlservice.getPorts(); Method m = serviceInterfaceClass.getMethod("setEndpointAddress", new Class[] { java.lang.String.class, java.lang.String.class }); for (Iterator<String> i = ports.keySet().iterator(); i.hasNext();) { String portName = i.next(); Port port = wsdlservice.getPort(portName); String endpoint = getSOAPLocation(port); m.invoke(service, new Object[] {port.getName(), endpoint }); portComponentRef.put(endpoint, new QName(port.getName())); } } catch (Exception e) { if (e instanceof InvocationTargetException) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } } NamingException ex = new NamingException ("Error while reading Wsdl File"); ex.initCause(e); throw ex; } } ServiceProxy proxy = new ServiceProxy(service); // Use port-component-ref for (int i = 0; i < ref.size(); i++) if (ServiceRef.SERVICEENDPOINTINTERFACE.equals(ref.get(i).getType())) { String serviceendpoint = ""; String portlink = ""; serviceendpoint = (String) ref.get(i).getContent(); if (ServiceRef.PORTCOMPONENTLINK.equals(ref.get(i + 1).getType())) { i++; portlink = (String) ref.get(i).getContent(); } portComponentRef.put(serviceendpoint, new QName(portlink)); } proxy.setPortComponentRef(portComponentRef); // Instantiate service with proxy class Class<?>[] interfaces = null; Class<?>[] serviceInterfaces = serviceInterfaceClass.getInterfaces(); interfaces = new Class[serviceInterfaces.length + 1]; for (int i = 0; i < serviceInterfaces.length; i++) { interfaces[i] = serviceInterfaces[i]; } interfaces[interfaces.length - 1] = javax.xml.rpc.Service.class; Object proxyInstance = null; try { proxyInstance = Proxy.newProxyInstance(tcl, interfaces, proxy); } catch (IllegalArgumentException e) { proxyInstance = Proxy.newProxyInstance(tcl, serviceInterfaces, proxy); } // Use handler if (((ServiceRef) ref).getHandlersSize() > 0) { HandlerRegistry handlerRegistry = service.getHandlerRegistry(); ArrayList<String> soaproles = new ArrayList<String>(); while (((ServiceRef) ref).getHandlersSize() > 0) { HandlerRef handlerRef = ((ServiceRef) ref).getHandler(); HandlerInfo handlerInfo = new HandlerInfo(); // Loading handler Class tmp = handlerRef.get(HandlerRef.HANDLER_CLASS); if ((tmp == null) || (tmp.getContent() == null)) break; Class<?> handlerClass = null; try { handlerClass = tcl.loadClass((String) tmp.getContent()); } catch(ClassNotFoundException e) { break; } // Load all datas relative to the handler : SOAPHeaders, config init element, // portNames to be set on ArrayList<QName> headers = new ArrayList<QName>(); Hashtable<String,String> config = new Hashtable<String,String>(); ArrayList<String> portNames = new ArrayList<String>(); for (int i = 0; i < handlerRef.size(); i++) if (HandlerRef.HANDLER_LOCALPART.equals(handlerRef.get(i).getType())) { String localpart = ""; String namespace = ""; localpart = (String) handlerRef.get(i).getContent(); if (HandlerRef.HANDLER_NAMESPACE.equals(handlerRef.get(i + 1).getType())) { i++; namespace = (String) handlerRef.get(i).getContent(); } QName header = new QName(namespace, localpart); headers.add(header); } else if (HandlerRef.HANDLER_PARAMNAME.equals(handlerRef.get(i).getType())) { String paramName = ""; String paramValue = ""; paramName = (String) handlerRef.get(i).getContent(); if (HandlerRef.HANDLER_PARAMVALUE.equals(handlerRef.get(i + 1).getType())) { i++; paramValue = (String) handlerRef.get(i).getContent(); } config.put(paramName, paramValue); } else if (HandlerRef.HANDLER_SOAPROLE.equals(handlerRef.get(i).getType())) { String soaprole = ""; soaprole = (String) handlerRef.get(i).getContent(); soaproles.add(soaprole); } else if (HandlerRef.HANDLER_PORTNAME.equals(handlerRef.get(i).getType())) { String portName = ""; portName = (String) handlerRef.get(i).getContent(); portNames.add(portName); } // Set the handlers informations handlerInfo.setHandlerClass(handlerClass); handlerInfo.setHeaders(headers.toArray(new QName[headers.size()])); handlerInfo.setHandlerConfig(config); if (!portNames.isEmpty()) { Iterator<String> iter = portNames.iterator(); while (iter.hasNext()) initHandlerChain(new QName(iter.next()), handlerRegistry, handlerInfo, soaproles); } else { Enumeration<QName> e = portComponentRef.elements(); while(e.hasMoreElements()) initHandlerChain(e.nextElement(), handlerRegistry, handlerInfo, soaproles); } } } return proxyInstance; } return null; }
// in java/org/apache/naming/factory/ResourceFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof ResourceRef) { Reference ref = (Reference) obj; ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch (Exception e) { if (e instanceof NamingException) throw (NamingException) e; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; } } } else { if (ref.getClassName().equals("javax.sql.DataSource")) { String javaxSqlDataSourceFactoryClassName = System.getProperty("javax.sql.DataSource.Factory", Constants.DBCP_DATASOURCE_FACTORY); try { factory = (ObjectFactory) Class.forName(javaxSqlDataSourceFactoryClassName) .newInstance(); } catch (Exception e) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; } } else if (ref.getClassName().equals("javax.mail.Session")) { String javaxMailSessionFactoryClassName = System.getProperty("javax.mail.Session.Factory", "org.apache.naming.factory.MailSessionFactory"); try { factory = (ObjectFactory) Class.forName(javaxMailSessionFactoryClassName) .newInstance(); } catch(Throwable t) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } } if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/factory/EjbFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof EjbRef) { Reference ref = (Reference) obj; // If ejb-link has been specified, resolving the link using JNDI RefAddr linkRefAddr = ref.get(EjbRef.LINK); if (linkRefAddr != null) { // Retrieving the EJB link String ejbLink = linkRefAddr.getContent().toString(); Object beanObj = (new InitialContext()).lookup(ejbLink); return beanObj; } ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch(Throwable t) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(t); throw ex; } } } else { String javaxEjbFactoryClassName = System.getProperty("javax.ejb.Factory", Constants.OPENEJB_EJB_FACTORY); try { factory = (ObjectFactory) Class.forName(javaxEjbFactoryClassName).newInstance(); } catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/factory/TransactionFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof TransactionRef) { Reference ref = (Reference) obj; ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } } if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/ContextBindings.java
public static void bindThread(Object name, Object token) throws NamingException { if (ContextAccessController.checkSecurityToken(name, token)) { Context context = contextNameBindings.get(name); if (context == null) throw new NamingException (sm.getString("contextBindings.unknownContext", name)); threadBindings.put(Thread.currentThread(), context); threadNameBindings.put(Thread.currentThread(), name); } }
// in java/org/apache/naming/ContextBindings.java
public static Context getThread() throws NamingException { Context context = threadBindings.get(Thread.currentThread()); if (context == null) throw new NamingException (sm.getString("contextBindings.noContextBoundToThread")); return context; }
// in java/org/apache/naming/ContextBindings.java
static Object getThreadName() throws NamingException { Object name = threadNameBindings.get(Thread.currentThread()); if (name == null) throw new NamingException (sm.getString("contextBindings.noContextBoundToThread")); return name; }
// in java/org/apache/naming/ContextBindings.java
public static void bindClassLoader(Object name, Object token, ClassLoader classLoader) throws NamingException { if (ContextAccessController.checkSecurityToken(name, token)) { Context context = contextNameBindings.get(name); if (context == null) throw new NamingException (sm.getString("contextBindings.unknownContext", name)); clBindings.put(classLoader, context); clNameBindings.put(classLoader, name); } }
// in java/org/apache/naming/ContextBindings.java
public static Context getClassLoader() throws NamingException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Context context = null; do { context = clBindings.get(cl); if (context != null) { return context; } } while ((cl = cl.getParent()) != null); throw new NamingException (sm.getString("contextBindings.noContextBoundToCL")); }
// in java/org/apache/naming/ContextBindings.java
static Object getClassLoaderName() throws NamingException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Object name = null; do { name = clNameBindings.get(cl); if (name != null) { return name; } } while ((cl = cl.getParent()) != null); throw new NamingException (sm.getString("contextBindings.noContextBoundToCL")); }
// in java/org/apache/naming/SelectorContext.java
protected String parseName(String name) throws NamingException { if ((!initialContext) && (name.startsWith(prefix))) { return (name.substring(prefixLength)); } else { if (initialContext) { return (name); } else { throw new NamingException (sm.getString("selectorContext.noJavaUrl")); } } }
// in java/org/apache/naming/SelectorContext.java
protected Name parseName(Name name) throws NamingException { if (!initialContext && !name.isEmpty() && name.get(0).startsWith(prefix)) { if (name.get(0).equals(prefix)) { return name.getSuffix(1); } else { Name result = name.getSuffix(1); result.add(0, name.get(0).substring(prefixLength)); return result; } } else { if (initialContext) { return name; } else { throw new NamingException( sm.getString("selectorContext.noJavaUrl")); } } }
// in java/org/apache/naming/NamingContext.java
Override public void unbind(Name name) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).unbind(name.getSuffix(1)); } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { bindings.remove(name.get(0)); } }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { return new NamingContextEnumeration(bindings.values().iterator()); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).list(name.getSuffix(1)); }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { return new NamingContextBindingsEnumeration(bindings.values().iterator(), this); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).listBindings(name.getSuffix(1)); }
// in java/org/apache/naming/NamingContext.java
Override public void destroySubcontext(Name name) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).destroySubcontext(name.getSuffix(1)); } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).close(); bindings.remove(name.get(0)); } else { throw new NotContextException (sm.getString("namingContext.contextExpected")); } } }
// in java/org/apache/naming/NamingContext.java
protected Object lookup(Name name, boolean resolveLinks) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { // If name is empty, a newly allocated naming context is returned return new NamingContext(env, this.name, bindings); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { // If the size of the name is greater that 1, then we go through a // number of subcontexts. if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).lookup(name.getSuffix(1)); } else { if ((resolveLinks) && (entry.type == NamingEntry.LINK_REF)) { String link = ((LinkRef) entry.value).getLinkName(); if (link.startsWith(".")) { // Link relative to this context return lookup(link.substring(1)); } else { return (new InitialContext(env)).lookup(link); } } else if (entry.type == NamingEntry.REFERENCE) { try { Object obj = NamingManager.getObjectInstance (entry.value, name, this, env); if(entry.value instanceof ResourceRef) { boolean singleton = Boolean.parseBoolean( (String) ((ResourceRef) entry.value).get( "singleton").getContent()); if (singleton) { entry.type = NamingEntry.ENTRY; entry.value = obj; } } return obj; } catch (NamingException e) { throw e; } catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); } } else { return entry.value; } } }
// in java/org/apache/naming/NamingContext.java
protected void bind(Name name, Object obj, boolean rebind) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (name.size() > 1) { if (entry == null) { throw new NameNotFoundException(sm.getString( "namingContext.nameNotBound", name, name.get(0))); } if (entry.type == NamingEntry.CONTEXT) { if (rebind) { ((Context) entry.value).rebind(name.getSuffix(1), obj); } else { ((Context) entry.value).bind(name.getSuffix(1), obj); } } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if ((!rebind) && (entry != null)) { throw new NameAlreadyBoundException (sm.getString("namingContext.alreadyBound", name.get(0))); } else { // Getting the type of the object and wrapping it within a new // NamingEntry Object toBind = NamingManager.getStateToBind(obj, name, this, env); if (toBind instanceof Context) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.CONTEXT); } else if (toBind instanceof LinkRef) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.LINK_REF); } else if (toBind instanceof Reference) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else if (toBind instanceof Referenceable) { toBind = ((Referenceable) toBind).getReference(); entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else { entry = new NamingEntry(name.get(0), toBind, NamingEntry.ENTRY); } bindings.put(name.get(0), entry); } } }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void unbind(String name) throws NamingException { File file = file(name); if (file == null) throw new NameNotFoundException( sm.getString("resources.notFound", name)); if (!file.delete()) throw new NamingException (sm.getString("resources.unbindFailed", name)); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void rename(String oldName, String newName) throws NamingException { File file = file(oldName); if (file == null) throw new NameNotFoundException (sm.getString("resources.notFound", oldName)); File newFile = new File(base, newName); if (!file.renameTo(newFile)) { throw new NamingException(sm.getString("resources.renameFail", oldName, newName)); } }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void rebind(String name, Object obj, Attributes attrs) throws NamingException { // Note: No custom attributes allowed // Check obj type File file = new File(base, name); InputStream is = null; if (obj instanceof Resource) { try { is = ((Resource) obj).streamContent(); } catch (IOException e) { // Ignore } } else if (obj instanceof InputStream) { is = (InputStream) obj; } else if (obj instanceof DirContext) { if (file.exists()) { if (!file.delete()) throw new NamingException (sm.getString("resources.bindFailed", name)); } if (!file.mkdir()) throw new NamingException (sm.getString("resources.bindFailed", name)); } if (is == null) throw new NamingException (sm.getString("resources.bindFailed", name)); // Open os try { FileOutputStream os = null; byte buffer[] = new byte[BUFFER_SIZE]; int len = -1; try { os = new FileOutputStream(file); while (true) { len = is.read(buffer); if (len == -1) break; os.write(buffer, 0, len); } } finally { if (os != null) os.close(); is.close(); } } catch (IOException e) { NamingException ne = new NamingException (sm.getString("resources.bindFailed", e)); ne.initCause(e); throw ne; } }
// in java/org/apache/naming/resources/FileDirContext.java
Override public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException (sm.getString("resources.alreadyBound", name)); if (!file.mkdir()) throw new NamingException (sm.getString("resources.bindFailed", name)); return (DirContext) lookup(name); }
1
              
// in java/org/apache/naming/NamingContext.java
catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); }
256
              
// in java/org/apache/naming/factory/BeanFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws NamingException { if (obj instanceof ResourceRef) { try { Reference ref = (Reference) obj; String beanClassName = ref.getClassName(); Class<?> beanClass = null; ClassLoader tcl = Thread.currentThread().getContextClassLoader(); if (tcl != null) { try { beanClass = tcl.loadClass(beanClassName); } catch(ClassNotFoundException e) { } } else { try { beanClass = Class.forName(beanClassName); } catch(ClassNotFoundException e) { e.printStackTrace(); } } if (beanClass == null) { throw new NamingException ("Class not found: " + beanClassName); } BeanInfo bi = Introspector.getBeanInfo(beanClass); PropertyDescriptor[] pda = bi.getPropertyDescriptors(); Object bean = beanClass.newInstance(); Enumeration<RefAddr> e = ref.getAll(); while (e.hasMoreElements()) { RefAddr ra = e.nextElement(); String propName = ra.getType(); if (propName.equals(Constants.FACTORY) || propName.equals("scope") || propName.equals("auth") || propName.equals("singleton")) { continue; } String value = (String)ra.getContent(); Object[] valueArray = new Object[1]; int i = 0; for (i = 0; i<pda.length; i++) { if (pda[i].getName().equals(propName)) { Class<?> propType = pda[i].getPropertyType(); if (propType.equals(String.class)) { valueArray[0] = value; } else if (propType.equals(Character.class) || propType.equals(char.class)) { valueArray[0] = Character.valueOf(value.charAt(0)); } else if (propType.equals(Byte.class) || propType.equals(byte.class)) { valueArray[0] = new Byte(value); } else if (propType.equals(Short.class) || propType.equals(short.class)) { valueArray[0] = new Short(value); } else if (propType.equals(Integer.class) || propType.equals(int.class)) { valueArray[0] = new Integer(value); } else if (propType.equals(Long.class) || propType.equals(long.class)) { valueArray[0] = new Long(value); } else if (propType.equals(Float.class) || propType.equals(float.class)) { valueArray[0] = new Float(value); } else if (propType.equals(Double.class) || propType.equals(double.class)) { valueArray[0] = new Double(value); } else if (propType.equals(Boolean.class) || propType.equals(boolean.class)) { valueArray[0] = Boolean.valueOf(value); } else { throw new NamingException ("String conversion for property type '" + propType.getName() + "' not available"); } Method setProp = pda[i].getWriteMethod(); if (setProp != null) { setProp.invoke(bean, valueArray); } else { throw new NamingException ("Write not allowed for property: " + propName); } break; } } if (i == pda.length) { throw new NamingException ("No set method found for property: " + propName); } } return bean; } catch (java.beans.IntrospectionException ie) { NamingException ne = new NamingException(ie.getMessage()); ne.setRootCause(ie); throw ne; } catch (java.lang.IllegalAccessException iae) { NamingException ne = new NamingException(iae.getMessage()); ne.setRootCause(iae); throw ne; } catch (java.lang.InstantiationException ie2) { NamingException ne = new NamingException(ie2.getMessage()); ne.setRootCause(ie2); throw ne; } catch (java.lang.reflect.InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } NamingException ne = new NamingException(ite.getMessage()); ne.setRootCause(ite); throw ne; } } else { return null; } }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws NamingException { Object result = super.getObjectInstance(obj, name, nameCtx, environment); // Can we process this request? if (result!=null) { Reference ref = (Reference) obj; RefAddr userAttr = ref.get("username"); RefAddr passAttr = ref.get("password"); if (userAttr.getContent()!=null && passAttr.getContent()!=null) { result = wrapDataSource(result,userAttr.getContent().toString(), passAttr.getContent().toString()); } } return result; }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
protected Object wrapDataSource(Object datasource, String username, String password) throws NamingException { try { Class<?> proxyClass = Proxy.getProxyClass(datasource.getClass().getClassLoader(), datasource.getClass().getInterfaces()); Constructor<?> proxyConstructor = proxyClass.getConstructor(new Class[] { InvocationHandler.class }); DataSourceHandler handler = new DataSourceHandler((DataSource)datasource, username, password); return proxyConstructor.newInstance(handler); }catch (Exception x) { if (x instanceof InvocationTargetException) { Throwable cause = x.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } if (cause instanceof Exception) { x = (Exception) cause; } } if (x instanceof NamingException) throw (NamingException)x; else { NamingException nx = new NamingException(x.getMessage()); nx.initCause(x); throw nx; } } }
// in java/org/apache/naming/factory/ResourceLinkFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws NamingException { if (!(obj instanceof ResourceLinkRef)) return null; // Can we process this request? Reference ref = (Reference) obj; // Read the global ref addr String globalName = null; RefAddr refAddr = ref.get(ResourceLinkRef.GLOBALNAME); if (refAddr != null) { globalName = refAddr.getContent().toString(); Object result = null; result = globalContext.lookup(globalName); // FIXME: Check type return result; } return (null); }
// in java/org/apache/naming/ContextBindings.java
public static void bindThread(Object name, Object token) throws NamingException { if (ContextAccessController.checkSecurityToken(name, token)) { Context context = contextNameBindings.get(name); if (context == null) throw new NamingException (sm.getString("contextBindings.unknownContext", name)); threadBindings.put(Thread.currentThread(), context); threadNameBindings.put(Thread.currentThread(), name); } }
// in java/org/apache/naming/ContextBindings.java
public static Context getThread() throws NamingException { Context context = threadBindings.get(Thread.currentThread()); if (context == null) throw new NamingException (sm.getString("contextBindings.noContextBoundToThread")); return context; }
// in java/org/apache/naming/ContextBindings.java
static Object getThreadName() throws NamingException { Object name = threadNameBindings.get(Thread.currentThread()); if (name == null) throw new NamingException (sm.getString("contextBindings.noContextBoundToThread")); return name; }
// in java/org/apache/naming/ContextBindings.java
public static void bindClassLoader(Object name, Object token, ClassLoader classLoader) throws NamingException { if (ContextAccessController.checkSecurityToken(name, token)) { Context context = contextNameBindings.get(name); if (context == null) throw new NamingException (sm.getString("contextBindings.unknownContext", name)); clBindings.put(classLoader, context); clNameBindings.put(classLoader, name); } }
// in java/org/apache/naming/ContextBindings.java
public static Context getClassLoader() throws NamingException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Context context = null; do { context = clBindings.get(cl); if (context != null) { return context; } } while ((cl = cl.getParent()) != null); throw new NamingException (sm.getString("contextBindings.noContextBoundToCL")); }
// in java/org/apache/naming/ContextBindings.java
static Object getClassLoaderName() throws NamingException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Object name = null; do { name = clNameBindings.get(cl); if (name != null) { return name; } } while ((cl = cl.getParent()) != null); throw new NamingException (sm.getString("contextBindings.noContextBoundToCL")); }
// in java/org/apache/naming/SelectorContext.java
Override public Object lookup(Name name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingName", "lookup", name)); } // Strip the URL header // Find the appropriate NamingContext according to the current bindings // Execute the lookup on that context return getBoundContext().lookup(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public Object lookup(String name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingString", "lookup", name)); } // Strip the URL header // Find the appropriate NamingContext according to the current bindings // Execute the lookup on that context return getBoundContext().lookup(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public void bind(Name name, Object obj) throws NamingException { getBoundContext().bind(parseName(name), obj); }
// in java/org/apache/naming/SelectorContext.java
Override public void bind(String name, Object obj) throws NamingException { getBoundContext().bind(parseName(name), obj); }
// in java/org/apache/naming/SelectorContext.java
Override public void rebind(Name name, Object obj) throws NamingException { getBoundContext().rebind(parseName(name), obj); }
// in java/org/apache/naming/SelectorContext.java
Override public void rebind(String name, Object obj) throws NamingException { getBoundContext().rebind(parseName(name), obj); }
// in java/org/apache/naming/SelectorContext.java
Override public void unbind(Name name) throws NamingException { getBoundContext().unbind(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public void unbind(String name) throws NamingException { getBoundContext().unbind(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public void rename(Name oldName, Name newName) throws NamingException { getBoundContext().rename(parseName(oldName), parseName(newName)); }
// in java/org/apache/naming/SelectorContext.java
Override public void rename(String oldName, String newName) throws NamingException { getBoundContext().rename(parseName(oldName), parseName(newName)); }
// in java/org/apache/naming/SelectorContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingName", "list", name)); } return getBoundContext().list(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public NamingEnumeration<NameClassPair> list(String name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingString", "list", name)); } return getBoundContext().list(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingName", "listBindings", name)); } return getBoundContext().listBindings(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public NamingEnumeration<Binding> listBindings(String name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingString", "listBindings", name)); } return getBoundContext().listBindings(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public void destroySubcontext(Name name) throws NamingException { getBoundContext().destroySubcontext(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public void destroySubcontext(String name) throws NamingException { getBoundContext().destroySubcontext(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public Context createSubcontext(Name name) throws NamingException { return getBoundContext().createSubcontext(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public Context createSubcontext(String name) throws NamingException { return getBoundContext().createSubcontext(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public Object lookupLink(Name name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingName", "lookupLink", name)); } return getBoundContext().lookupLink(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public Object lookupLink(String name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingString", "lookupLink", name)); } return getBoundContext().lookupLink(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public NameParser getNameParser(Name name) throws NamingException { return getBoundContext().getNameParser(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public NameParser getNameParser(String name) throws NamingException { return getBoundContext().getNameParser(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public Name composeName(Name name, Name prefix) throws NamingException { Name prefixClone = (Name) prefix.clone(); return prefixClone.addAll(name); }
// in java/org/apache/naming/SelectorContext.java
Override public String composeName(String name, String prefix) throws NamingException { return prefix + "/" + name; }
// in java/org/apache/naming/SelectorContext.java
Override public Object addToEnvironment(String propName, Object propVal) throws NamingException { return getBoundContext().addToEnvironment(propName, propVal); }
// in java/org/apache/naming/SelectorContext.java
Override public Object removeFromEnvironment(String propName) throws NamingException { return getBoundContext().removeFromEnvironment(propName); }
// in java/org/apache/naming/SelectorContext.java
Override public Hashtable<?,?> getEnvironment() throws NamingException { return getBoundContext().getEnvironment(); }
// in java/org/apache/naming/SelectorContext.java
Override public void close() throws NamingException { getBoundContext().close(); }
// in java/org/apache/naming/SelectorContext.java
Override public String getNameInNamespace() throws NamingException { return prefix; }
// in java/org/apache/naming/SelectorContext.java
protected Context getBoundContext() throws NamingException { if (initialContext) { String ICName = IC_PREFIX; if (ContextBindings.isThreadBound()) { ICName += ContextBindings.getThreadName(); } else if (ContextBindings.isClassLoaderBound()) { ICName += ContextBindings.getClassLoaderName(); } Context initialContext = ContextBindings.getContext(ICName); if (initialContext == null) { // Allocating a new context and binding it to the appropriate // name initialContext = new NamingContext(env, ICName); ContextBindings.bindContext(ICName, initialContext); } return initialContext; } else { if (ContextBindings.isThreadBound()) { return ContextBindings.getThread(); } else { return ContextBindings.getClassLoader(); } } }
// in java/org/apache/naming/SelectorContext.java
protected String parseName(String name) throws NamingException { if ((!initialContext) && (name.startsWith(prefix))) { return (name.substring(prefixLength)); } else { if (initialContext) { return (name); } else { throw new NamingException (sm.getString("selectorContext.noJavaUrl")); } } }
// in java/org/apache/naming/SelectorContext.java
protected Name parseName(Name name) throws NamingException { if (!initialContext && !name.isEmpty() && name.get(0).startsWith(prefix)) { if (name.get(0).equals(prefix)) { return name.getSuffix(1); } else { Name result = name.getSuffix(1); result.add(0, name.get(0).substring(prefixLength)); return result; } } else { if (initialContext) { return name; } else { throw new NamingException( sm.getString("selectorContext.noJavaUrl")); } } }
// in java/org/apache/naming/NameParserImpl.java
Override public Name parse(String name) throws NamingException { return new CompositeName(name); }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
Override public Binding next() throws NamingException { return nextElementInternal(); }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
Override public boolean hasMore() throws NamingException { return iterator.hasNext(); }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
Override public void close() throws NamingException { }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
private Binding nextElementInternal() throws NamingException { NamingEntry entry = iterator.next(); Object value; // If the entry is a reference, resolve it if (entry.type == NamingEntry.REFERENCE || entry.type == NamingEntry.LINK_REF) { try { value = ctx.lookup(new CompositeName(entry.name)); } catch (NamingException e) { throw e; } catch (Exception e) { NamingException ne = new NamingException(e.getMessage()); ne.initCause(e); throw ne; } } else { value = entry.value; } return new Binding(entry.name, value.getClass().getName(), value, true); }
// in java/org/apache/naming/NamingContextEnumeration.java
Override public NameClassPair next() throws NamingException { return nextElement(); }
// in java/org/apache/naming/NamingContextEnumeration.java
Override public boolean hasMore() throws NamingException { return iterator.hasNext(); }
// in java/org/apache/naming/NamingContextEnumeration.java
Override public void close() throws NamingException { }
// in java/org/apache/naming/NamingContext.java
Override public Object lookup(Name name) throws NamingException { return lookup(name, true); }
// in java/org/apache/naming/NamingContext.java
Override public Object lookup(String name) throws NamingException { return lookup(new CompositeName(name), true); }
// in java/org/apache/naming/NamingContext.java
Override public void bind(Name name, Object obj) throws NamingException { bind(name, obj, false); }
// in java/org/apache/naming/NamingContext.java
Override public void bind(String name, Object obj) throws NamingException { bind(new CompositeName(name), obj); }
// in java/org/apache/naming/NamingContext.java
Override public void rebind(Name name, Object obj) throws NamingException { bind(name, obj, true); }
// in java/org/apache/naming/NamingContext.java
Override public void rebind(String name, Object obj) throws NamingException { rebind(new CompositeName(name), obj); }
// in java/org/apache/naming/NamingContext.java
Override public void unbind(Name name) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).unbind(name.getSuffix(1)); } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { bindings.remove(name.get(0)); } }
// in java/org/apache/naming/NamingContext.java
Override public void unbind(String name) throws NamingException { unbind(new CompositeName(name)); }
// in java/org/apache/naming/NamingContext.java
Override public void rename(Name oldName, Name newName) throws NamingException { Object value = lookup(oldName); bind(newName, value); unbind(oldName); }
// in java/org/apache/naming/NamingContext.java
Override public void rename(String oldName, String newName) throws NamingException { rename(new CompositeName(oldName), new CompositeName(newName)); }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { return new NamingContextEnumeration(bindings.values().iterator()); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).list(name.getSuffix(1)); }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<NameClassPair> list(String name) throws NamingException { return list(new CompositeName(name)); }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { return new NamingContextBindingsEnumeration(bindings.values().iterator(), this); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).listBindings(name.getSuffix(1)); }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<Binding> listBindings(String name) throws NamingException { return listBindings(new CompositeName(name)); }
// in java/org/apache/naming/NamingContext.java
Override public void destroySubcontext(Name name) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).destroySubcontext(name.getSuffix(1)); } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).close(); bindings.remove(name.get(0)); } else { throw new NotContextException (sm.getString("namingContext.contextExpected")); } } }
// in java/org/apache/naming/NamingContext.java
Override public void destroySubcontext(String name) throws NamingException { destroySubcontext(new CompositeName(name)); }
// in java/org/apache/naming/NamingContext.java
Override public Context createSubcontext(Name name) throws NamingException { if (!checkWritable()) { return null; } NamingContext newContext = new NamingContext(env, this.name); bind(name, newContext); newContext.setExceptionOnFailedWrite(getExceptionOnFailedWrite()); return newContext; }
// in java/org/apache/naming/NamingContext.java
Override public Context createSubcontext(String name) throws NamingException { return createSubcontext(new CompositeName(name)); }
// in java/org/apache/naming/NamingContext.java
Override public Object lookupLink(Name name) throws NamingException { return lookup(name, false); }
// in java/org/apache/naming/NamingContext.java
Override public Object lookupLink(String name) throws NamingException { return lookup(new CompositeName(name), false); }
// in java/org/apache/naming/NamingContext.java
Override public NameParser getNameParser(Name name) throws NamingException { while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) return nameParser; if (name.size() > 1) { Object obj = bindings.get(name.get(0)); if (obj instanceof Context) { return ((Context) obj).getNameParser(name.getSuffix(1)); } else { throw new NotContextException (sm.getString("namingContext.contextExpected")); } } return nameParser; }
// in java/org/apache/naming/NamingContext.java
Override public NameParser getNameParser(String name) throws NamingException { return getNameParser(new CompositeName(name)); }
// in java/org/apache/naming/NamingContext.java
Override public Name composeName(Name name, Name prefix) throws NamingException { prefix = (Name) prefix.clone(); return prefix.addAll(name); }
// in java/org/apache/naming/NamingContext.java
Override public String composeName(String name, String prefix) throws NamingException { return prefix + "/" + name; }
// in java/org/apache/naming/NamingContext.java
Override public Object addToEnvironment(String propName, Object propVal) throws NamingException { return env.put(propName, propVal); }
// in java/org/apache/naming/NamingContext.java
Override public Object removeFromEnvironment(String propName) throws NamingException { return env.remove(propName); }
// in java/org/apache/naming/NamingContext.java
Override public Hashtable<?,?> getEnvironment() throws NamingException { return env; }
// in java/org/apache/naming/NamingContext.java
Override public void close() throws NamingException { if (!checkWritable()) { return; } env.clear(); }
// in java/org/apache/naming/NamingContext.java
Override public String getNameInNamespace() throws NamingException { throw new OperationNotSupportedException (sm.getString("namingContext.noAbsoluteName")); //FIXME ? }
// in java/org/apache/naming/NamingContext.java
protected Object lookup(Name name, boolean resolveLinks) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { // If name is empty, a newly allocated naming context is returned return new NamingContext(env, this.name, bindings); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { // If the size of the name is greater that 1, then we go through a // number of subcontexts. if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).lookup(name.getSuffix(1)); } else { if ((resolveLinks) && (entry.type == NamingEntry.LINK_REF)) { String link = ((LinkRef) entry.value).getLinkName(); if (link.startsWith(".")) { // Link relative to this context return lookup(link.substring(1)); } else { return (new InitialContext(env)).lookup(link); } } else if (entry.type == NamingEntry.REFERENCE) { try { Object obj = NamingManager.getObjectInstance (entry.value, name, this, env); if(entry.value instanceof ResourceRef) { boolean singleton = Boolean.parseBoolean( (String) ((ResourceRef) entry.value).get( "singleton").getContent()); if (singleton) { entry.type = NamingEntry.ENTRY; entry.value = obj; } } return obj; } catch (NamingException e) { throw e; } catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); } } else { return entry.value; } } }
// in java/org/apache/naming/NamingContext.java
protected void bind(Name name, Object obj, boolean rebind) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (name.size() > 1) { if (entry == null) { throw new NameNotFoundException(sm.getString( "namingContext.nameNotBound", name, name.get(0))); } if (entry.type == NamingEntry.CONTEXT) { if (rebind) { ((Context) entry.value).rebind(name.getSuffix(1), obj); } else { ((Context) entry.value).bind(name.getSuffix(1), obj); } } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if ((!rebind) && (entry != null)) { throw new NameAlreadyBoundException (sm.getString("namingContext.alreadyBound", name.get(0))); } else { // Getting the type of the object and wrapping it within a new // NamingEntry Object toBind = NamingManager.getStateToBind(obj, name, this, env); if (toBind instanceof Context) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.CONTEXT); } else if (toBind instanceof LinkRef) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.LINK_REF); } else if (toBind instanceof Reference) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else if (toBind instanceof Referenceable) { toBind = ((Referenceable) toBind).getReference(); entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else { entry = new NamingEntry(name.get(0), toBind, NamingEntry.ENTRY); } bindings.put(name.get(0), entry); } } }
// in java/org/apache/naming/NamingContext.java
protected boolean checkWritable() throws NamingException { if (isWritable()) { return true; } else { if (exceptionOnFailedWrite) { throw new javax.naming.OperationNotSupportedException( sm.getString("namingContext.readOnly")); } } return false; }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void unbind(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void rename(String oldName, String newName) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<NameClassPair> list(String name) throws NamingException { return list(getEscapedJndiName(name)); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { if (name.isEmpty()) return new NamingContextEnumeration(list(entries).iterator()); Entry entry = treeLookup(name); if (entry == null) throw new NameNotFoundException (sm.getString("resources.notFound", name)); return new NamingContextEnumeration(list(entry).iterator()); }
// in java/org/apache/naming/resources/WARDirContext.java
Override protected List<NamingEntry> doListBindings(String strName) throws NamingException { Name name = getEscapedJndiName(strName); if (name.isEmpty()) return list(entries); Entry entry = treeLookup(name); if (entry == null) return null; return list(entry); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void destroySubcontext(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public Object lookupLink(String name) throws NamingException { // Note : Links are not supported return lookup(name); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public String getNameInNamespace() throws NamingException { return docBase; }
// in java/org/apache/naming/resources/WARDirContext.java
Override protected Attributes doGetAttributes(String name, String[] attrIds) throws NamingException { return getAttributes(getEscapedJndiName(name), attrIds); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { Entry entry = null; if (name.isEmpty()) entry = entries; else entry = treeLookup(name); if (entry == null) return null; ZipEntry zipEntry = entry.getEntry(); ResourceAttributes attrs = new ResourceAttributes(); attrs.setCreationDate(new Date(zipEntry.getTime())); attrs.setName(entry.getName()); if (!zipEntry.isDirectory()) attrs.setResourceType(""); else attrs.setCollection(true); attrs.setContentLength(zipEntry.getSize()); attrs.setLastModified(zipEntry.getTime()); return attrs; }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void bind(String name, Object obj, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void rebind(String name, Object obj, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public DirContext getSchema(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public DirContext getSchemaClassDefinition(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void unbind(String name) throws NamingException { File file = file(name); if (file == null) throw new NameNotFoundException( sm.getString("resources.notFound", name)); if (!file.delete()) throw new NamingException (sm.getString("resources.unbindFailed", name)); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void rename(String oldName, String newName) throws NamingException { File file = file(oldName); if (file == null) throw new NameNotFoundException (sm.getString("resources.notFound", oldName)); File newFile = new File(base, newName); if (!file.renameTo(newFile)) { throw new NamingException(sm.getString("resources.renameFail", oldName, newName)); } }
// in java/org/apache/naming/resources/FileDirContext.java
Override public NamingEnumeration<NameClassPair> list(String name) throws NamingException { File file = file(name); if (file == null) throw new NameNotFoundException (sm.getString("resources.notFound", name)); return new NamingContextEnumeration(list(file).iterator()); }
// in java/org/apache/naming/resources/FileDirContext.java
Override protected List<NamingEntry> doListBindings(String name) throws NamingException { File file = file(name); if (file == null) return null; return list(file); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void destroySubcontext(String name) throws NamingException { unbind(name); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public Object lookupLink(String name) throws NamingException { // Note : Links are not supported return lookup(name); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public String getNameInNamespace() throws NamingException { return docBase; }
// in java/org/apache/naming/resources/FileDirContext.java
Override protected Attributes doGetAttributes(String name, String[] attrIds) throws NamingException { // Building attribute list File file = file(name); if (file == null) return null; return new FileResourceAttributes(file); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void bind(String name, Object obj, Attributes attrs) throws NamingException { // Note: No custom attributes allowed File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException (sm.getString("resources.alreadyBound", name)); rebind(name, obj, attrs); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void rebind(String name, Object obj, Attributes attrs) throws NamingException { // Note: No custom attributes allowed // Check obj type File file = new File(base, name); InputStream is = null; if (obj instanceof Resource) { try { is = ((Resource) obj).streamContent(); } catch (IOException e) { // Ignore } } else if (obj instanceof InputStream) { is = (InputStream) obj; } else if (obj instanceof DirContext) { if (file.exists()) { if (!file.delete()) throw new NamingException (sm.getString("resources.bindFailed", name)); } if (!file.mkdir()) throw new NamingException (sm.getString("resources.bindFailed", name)); } if (is == null) throw new NamingException (sm.getString("resources.bindFailed", name)); // Open os try { FileOutputStream os = null; byte buffer[] = new byte[BUFFER_SIZE]; int len = -1; try { os = new FileOutputStream(file); while (true) { len = is.read(buffer); if (len == -1) break; os.write(buffer, 0, len); } } finally { if (os != null) os.close(); is.close(); } } catch (IOException e) { NamingException ne = new NamingException (sm.getString("resources.bindFailed", e)); ne.initCause(e); throw ne; } }
// in java/org/apache/naming/resources/FileDirContext.java
Override public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException (sm.getString("resources.alreadyBound", name)); if (!file.mkdir()) throw new NamingException (sm.getString("resources.bindFailed", name)); return (DirContext) lookup(name); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public DirContext getSchema(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public DirContext getSchemaClassDefinition(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { return null; }
// in java/org/apache/naming/resources/FileDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { return null; }
// in java/org/apache/naming/resources/FileDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException { return null; }
// in java/org/apache/naming/resources/FileDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { return null; }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final Object lookup(Name name) throws NamingException { return lookup(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final Object lookup(String name) throws NamingException { // First check for aliases if (!aliases.isEmpty()) { AliasResult result = findAlias(name); if (result.dirContext != null) { return result.dirContext.lookup(result.aliasName); } } // Next do a standard lookup Object obj = doLookup(name); if (obj != null) return obj; // Check the alternate locations for (DirContext altDirContext : altDirContexts) { try { obj = altDirContext.lookup("/META-INF/resources" + name); if (obj != null) return obj; } catch ( NamingException ex) { // ignore } } // Really not found throw new NameNotFoundException( sm.getString("resources.notFound", name)); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void bind(Name name, Object obj) throws NamingException { bind(name.toString(), obj); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void bind(String name, Object obj) throws NamingException { bind(name, obj, null); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void rebind(Name name, Object obj) throws NamingException { rebind(name.toString(), obj); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void rebind(String name, Object obj) throws NamingException { rebind(name, obj, null); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void unbind(Name name) throws NamingException { unbind(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void rename(Name oldName, Name newName) throws NamingException { rename(oldName.toString(), newName.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { return list(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final NamingEnumeration<Binding> listBindings(Name name) throws NamingException { return listBindings(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final NamingEnumeration<Binding> listBindings(String name) throws NamingException { if (!aliases.isEmpty()) { AliasResult result = findAlias(name); if (result.dirContext != null) { return result.dirContext.listBindings(result.aliasName); } } // Next do a standard lookup List<NamingEntry> bindings = doListBindings(name); // Check the alternate locations List<NamingEntry> altBindings = null; for (DirContext altDirContext : altDirContexts) { if (altDirContext instanceof BaseDirContext) { altBindings = ((BaseDirContext) altDirContext).doListBindings( "/META-INF/resources" + name); } if (altBindings != null) { if (bindings == null) { bindings = altBindings; } else { bindings.addAll(altBindings); } } } if (bindings != null) { return new NamingContextBindingsEnumeration(bindings.iterator(), this); } // Really not found throw new NameNotFoundException( sm.getString("resources.notFound", name)); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void destroySubcontext(Name name) throws NamingException { destroySubcontext(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Context createSubcontext(Name name) throws NamingException { return createSubcontext(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Context createSubcontext(String name) throws NamingException { return createSubcontext(name, null); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Object lookupLink(Name name) throws NamingException { return lookupLink(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public NameParser getNameParser(Name name) throws NamingException { return new NameParserImpl(); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public NameParser getNameParser(String name) throws NamingException { return new NameParserImpl(); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Name composeName(Name name, Name prefix) throws NamingException { Name clone = (Name) prefix.clone(); return clone.addAll(name); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public String composeName(String name, String prefix) throws NamingException { return prefix + "/" + name; }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Object addToEnvironment(String propName, Object propVal) throws NamingException { return env.put(propName, propVal); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Object removeFromEnvironment(String propName) throws NamingException { return env.remove(propName); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Hashtable<String,Object> getEnvironment() throws NamingException { return env; }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void close() throws NamingException { env.clear(); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Attributes getAttributes(Name name) throws NamingException { return getAttributes(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Attributes getAttributes(String name) throws NamingException { return getAttributes(name, null); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { return getAttributes(name.toString(), attrIds); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final Attributes getAttributes(String name, String[] attrIds) throws NamingException { // First check for aliases if (!aliases.isEmpty()) { AliasResult result = findAlias(name); if (result.dirContext != null) { return result.dirContext.getAttributes( result.aliasName, attrIds); } } // Next do a standard lookup Attributes attrs = doGetAttributes(name, attrIds); if (attrs != null) return attrs; // Check the alternate locations for (DirContext altDirContext : altDirContexts) { if (altDirContext instanceof BaseDirContext) attrs = ((BaseDirContext) altDirContext).doGetAttributes( "/META-INF/resources" + name, attrIds); else { try { attrs = altDirContext.getAttributes(name, attrIds); } catch (NamingException ne) { // Ignore } } if (attrs != null) return attrs; } // Really not found throw new NameNotFoundException( sm.getString("resources.notFound", name)); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void modifyAttributes(Name name, int mod_op, Attributes attrs) throws NamingException { modifyAttributes(name.toString(), mod_op, attrs); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException { modifyAttributes(name.toString(), mods); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void bind(Name name, Object obj, Attributes attrs) throws NamingException { bind(name.toString(), obj, attrs); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void rebind(Name name, Object obj, Attributes attrs) throws NamingException { rebind(name.toString(), obj, attrs); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException { return createSubcontext(name.toString(), attrs); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public DirContext getSchema(Name name) throws NamingException { return getSchema(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public DirContext getSchemaClassDefinition(Name name) throws NamingException { return getSchemaClassDefinition(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { return search(name.toString(), matchingAttributes, attributesToReturn); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes) throws NamingException { return search(name.toString(), matchingAttributes); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public NamingEnumeration<SearchResult> search (Name name, String filter, SearchControls cons) throws NamingException { return search(name.toString(), filter, cons); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public NamingEnumeration<SearchResult> search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { return search(name.toString(), filterExpr, filterArgs, cons); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Object lookup(Name name) throws NamingException { CacheEntry entry = cacheLookup(name.toString()); if (entry != null) { if (!entry.exists) { throw NOT_FOUND_EXCEPTION; } if (entry.resource != null) { // Check content caching. return entry.resource; } else { return entry.context; } } Object object = dirContext.lookup(parseName(name)); if (object instanceof InputStream) return new Resource((InputStream) object); else return object; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Object lookup(String name) throws NamingException { CacheEntry entry = cacheLookup(name); if (entry != null) { if (!entry.exists) { throw NOT_FOUND_EXCEPTION; } if (entry.resource != null) { return entry.resource; } else { return entry.context; } } Object object = dirContext.lookup(parseName(name)); if (object instanceof InputStream) { return new Resource((InputStream) object); } else if (object instanceof DirContext) { return object; } else if (object instanceof Resource) { return object; } else { return new Resource(new ByteArrayInputStream (object.toString().getBytes(Constants.ISO_8859_1))); } }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void bind(Name name, Object obj) throws NamingException { dirContext.bind(parseName(name), obj); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void bind(String name, Object obj) throws NamingException { dirContext.bind(parseName(name), obj); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void rebind(Name name, Object obj) throws NamingException { dirContext.rebind(parseName(name), obj); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void rebind(String name, Object obj) throws NamingException { dirContext.rebind(parseName(name), obj); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void unbind(Name name) throws NamingException { dirContext.unbind(parseName(name)); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void unbind(String name) throws NamingException { dirContext.unbind(parseName(name)); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void rename(Name oldName, Name newName) throws NamingException { dirContext.rename(parseName(oldName), parseName(newName)); cacheUnload(oldName.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void rename(String oldName, String newName) throws NamingException { dirContext.rename(parseName(oldName), parseName(newName)); cacheUnload(oldName); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { return dirContext.list(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<NameClassPair> list(String name) throws NamingException { return dirContext.list(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { return dirContext.listBindings(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<Binding> listBindings(String name) throws NamingException { return dirContext.listBindings(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void destroySubcontext(Name name) throws NamingException { dirContext.destroySubcontext(parseName(name)); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void destroySubcontext(String name) throws NamingException { dirContext.destroySubcontext(parseName(name)); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Context createSubcontext(Name name) throws NamingException { Context context = dirContext.createSubcontext(parseName(name)); cacheUnload(name.toString()); return context; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Context createSubcontext(String name) throws NamingException { Context context = dirContext.createSubcontext(parseName(name)); cacheUnload(name); return context; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Object lookupLink(Name name) throws NamingException { return dirContext.lookupLink(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Object lookupLink(String name) throws NamingException { return dirContext.lookupLink(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NameParser getNameParser(Name name) throws NamingException { return dirContext.getNameParser(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NameParser getNameParser(String name) throws NamingException { return dirContext.getNameParser(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Name composeName(Name name, Name prefix) throws NamingException { Name prefixClone = (Name) prefix.clone(); return prefixClone.addAll(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public String composeName(String name, String prefix) throws NamingException { return prefix + "/" + name; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Object addToEnvironment(String propName, Object propVal) throws NamingException { return dirContext.addToEnvironment(propName, propVal); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Object removeFromEnvironment(String propName) throws NamingException { return dirContext.removeFromEnvironment(propName); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Hashtable<?,?> getEnvironment() throws NamingException { return dirContext.getEnvironment(); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void close() throws NamingException { dirContext.close(); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public String getNameInNamespace() throws NamingException { return dirContext.getNameInNamespace(); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Attributes getAttributes(Name name) throws NamingException { CacheEntry entry = cacheLookup(name.toString()); if (entry != null) { if (!entry.exists) { throw NOT_FOUND_EXCEPTION; } return entry.attributes; } Attributes attributes = dirContext.getAttributes(parseName(name)); if (!(attributes instanceof ResourceAttributes)) { attributes = new ResourceAttributes(attributes); } return attributes; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Attributes getAttributes(String name) throws NamingException { CacheEntry entry = cacheLookup(name); if (entry != null) { if (!entry.exists) { throw NOT_FOUND_EXCEPTION; } return entry.attributes; } Attributes attributes = dirContext.getAttributes(parseName(name)); if (!(attributes instanceof ResourceAttributes)) { attributes = new ResourceAttributes(attributes); } return attributes; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { Attributes attributes = dirContext.getAttributes(parseName(name), attrIds); if (!(attributes instanceof ResourceAttributes)) { attributes = new ResourceAttributes(attributes); } return attributes; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Attributes getAttributes(String name, String[] attrIds) throws NamingException { Attributes attributes = dirContext.getAttributes(parseName(name), attrIds); if (!(attributes instanceof ResourceAttributes)) { attributes = new ResourceAttributes(attributes); } return attributes; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void modifyAttributes(Name name, int mod_op, Attributes attrs) throws NamingException { dirContext.modifyAttributes(parseName(name), mod_op, attrs); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { dirContext.modifyAttributes(parseName(name), mod_op, attrs); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException { dirContext.modifyAttributes(parseName(name), mods); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { dirContext.modifyAttributes(parseName(name), mods); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void bind(Name name, Object obj, Attributes attrs) throws NamingException { dirContext.bind(parseName(name), obj, attrs); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void bind(String name, Object obj, Attributes attrs) throws NamingException { dirContext.bind(parseName(name), obj, attrs); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void rebind(Name name, Object obj, Attributes attrs) throws NamingException { dirContext.rebind(parseName(name), obj, attrs); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void rebind(String name, Object obj, Attributes attrs) throws NamingException { dirContext.rebind(parseName(name), obj, attrs); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException { DirContext context = dirContext.createSubcontext(parseName(name), attrs); cacheUnload(name.toString()); return context; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { DirContext context = dirContext.createSubcontext(parseName(name), attrs); cacheUnload(name); return context; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public DirContext getSchema(Name name) throws NamingException { return dirContext.getSchema(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public DirContext getSchema(String name) throws NamingException { return dirContext.getSchema(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public DirContext getSchemaClassDefinition(Name name) throws NamingException { return dirContext.getSchemaClassDefinition(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public DirContext getSchemaClassDefinition(String name) throws NamingException { return dirContext.getSchemaClassDefinition(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { return dirContext.search(parseName(name), matchingAttributes, attributesToReturn); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { return dirContext.search(parseName(name), matchingAttributes, attributesToReturn); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes) throws NamingException { return dirContext.search(parseName(name), matchingAttributes); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { return dirContext.search(parseName(name), matchingAttributes); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(Name name, String filter, SearchControls cons) throws NamingException { return dirContext.search(parseName(name), filter, cons); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException { return dirContext.search(parseName(name), filter, cons); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { return dirContext.search(parseName(name), filterExpr, filterArgs, cons); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { return dirContext.search(parseName(name), filterExpr, filterArgs, cons); }
// in java/org/apache/naming/resources/ProxyDirContext.java
protected String parseName(String name) throws NamingException { return name; }
// in java/org/apache/naming/resources/ProxyDirContext.java
protected Name parseName(Name name) throws NamingException { return name; }
// in java/org/apache/naming/resources/VirtualDirContext.java
Override public Attributes getAttributes(String name) throws NamingException { NamingException initialException; try { // first try the normal processing, if it fails try with extra // resources Attributes attributes = super.getAttributes(name); return attributes; } catch (NamingException exc) { initialException = exc; } if (mappedResourcePaths != null) { for (Map.Entry<String, List<String>> mapping : mappedResourcePaths.entrySet()) { String path = mapping.getKey(); List<String> dirList = mapping.getValue(); String resourcesDir = dirList.get(0); if (name.equals(path)) { File f = new File(resourcesDir); if (f.exists() && f.canRead()) { return new FileResourceAttributes(f); } } path += "/"; if (name.startsWith(path)) { String res = name.substring(path.length()); File f = new File(resourcesDir + "/" + res); if (f.exists() && f.canRead()) { return new FileResourceAttributes(f); } } } } throw initialException; }
// in java/org/apache/naming/resources/RecyclableNamingEnumeration.java
Override public E next() throws NamingException { return nextElement(); }
// in java/org/apache/naming/resources/RecyclableNamingEnumeration.java
Override public boolean hasMore() throws NamingException { return enumeration.hasMoreElements(); }
// in java/org/apache/naming/resources/RecyclableNamingEnumeration.java
Override public void close() throws NamingException { // NO-OP }
// in java/org/apache/catalina/realm/JNDIRealm.java
public synchronized Principal authenticate(DirContext context, String username, String credentials) throws NamingException { if (username == null || username.equals("") || credentials == null || credentials.equals("")) { if (containerLog.isDebugEnabled()) containerLog.debug("username null or empty: returning null principal."); return (null); } if (userPatternArray != null) { for (int curUserPattern = 0; curUserPattern < userPatternFormatArray.length; curUserPattern++) { // Retrieve user information User user = getUser(context, username, credentials, curUserPattern); if (user != null) { try { // Check the user's credentials if (checkCredentials(context, user, credentials)) { // Search for additional roles List<String> roles = getRoles(context, user); if (containerLog.isDebugEnabled()) { Iterator<String> it = roles.iterator(); // TODO: Use a single log message while (it.hasNext()) { containerLog.debug("Found role: " + it.next()); } } return (new GenericPrincipal(username, credentials, roles)); } } catch (InvalidNameException ine) { // Log the problem for posterity containerLog.warn(sm.getString("jndiRealm.exception"), ine); // ignore; this is probably due to a name not fitting // the search path format exactly, as in a fully- // qualified name being munged into a search path // that already contains cn= or vice-versa } } } return null; } else { // Retrieve user information User user = getUser(context, username, credentials); if (user == null) return (null); // Check the user's credentials if (!checkCredentials(context, user, credentials)) return (null); // Search for additional roles List<String> roles = getRoles(context, user); if (containerLog.isDebugEnabled()) { Iterator<String> it = roles.iterator(); // TODO: Use a single log message while (it.hasNext()) { containerLog.debug("Found role: " + it.next()); } } // Create and return a suitable Principal for this user return (new GenericPrincipal(username, credentials, roles)); } }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected User getUser(DirContext context, String username) throws NamingException { return getUser(context, username, null, -1); }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected User getUser(DirContext context, String username, String credentials) throws NamingException { return getUser(context, username, credentials, -1); }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected User getUser(DirContext context, String username, String credentials, int curUserPattern) throws NamingException { User user = null; // Get attributes to retrieve from user entry ArrayList<String> list = new ArrayList<String>(); if (userPassword != null) list.add(userPassword); if (userRoleName != null) list.add(userRoleName); String[] attrIds = new String[list.size()]; list.toArray(attrIds); // Use pattern or search for user entry if (userPatternFormatArray != null && curUserPattern >= 0) { user = getUserByPattern(context, username, credentials, attrIds, curUserPattern); } else { user = getUserBySearch(context, username, attrIds); } return user; }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected User getUserByPattern(DirContext context, String username, String[] attrIds, String dn) throws NamingException { // If no attributes are requested, no need to look for them if (attrIds == null || attrIds.length == 0) { return new User(username, dn, null, null); } // Get required attributes from user entry Attributes attrs = null; try { attrs = context.getAttributes(dn, attrIds); } catch (NameNotFoundException e) { return (null); } if (attrs == null) return (null); // Retrieve value of userPassword String password = null; if (userPassword != null) password = getAttributeValue(userPassword, attrs); // Retrieve values of userRoleName attribute ArrayList<String> roles = null; if (userRoleName != null) roles = addAttributeValues(userRoleName, attrs, roles); return new User(username, dn, password, roles); }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected User getUserByPattern(DirContext context, String username, String credentials, String[] attrIds, int curUserPattern) throws NamingException { User user = null; if (username == null || userPatternFormatArray[curUserPattern] == null) return (null); // Form the dn from the user pattern String dn = userPatternFormatArray[curUserPattern].format(new String[] { username }); try { user = getUserByPattern(context, username, attrIds, dn); } catch (NameNotFoundException e) { return (null); } catch (NamingException e) { // If the getUserByPattern() call fails, try it again with the // credentials of the user that we're searching for try { userCredentialsAdd(context, dn, credentials); user = getUserByPattern(context, username, attrIds, dn); } finally { userCredentialsRemove(context); } } return user; }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected User getUserBySearch(DirContext context, String username, String[] attrIds) throws NamingException { if (username == null || userSearchFormat == null) return (null); // Form the search filter String filter = userSearchFormat.format(new String[] { username }); // Set up the search controls SearchControls constraints = new SearchControls(); if (userSubtree) { constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); } else { constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); } constraints.setCountLimit(sizeLimit); constraints.setTimeLimit(timeLimit); // Specify the attributes to be retrieved if (attrIds == null) attrIds = new String[0]; constraints.setReturningAttributes(attrIds); NamingEnumeration<SearchResult> results = context.search(userBase, filter, constraints); // Fail if no entries found try { if (results == null || !results.hasMore()) { return (null); } } catch (PartialResultException ex) { if (!adCompat) throw ex; else return (null); } // Get result for the first entry found SearchResult result = results.next(); // Check no further entries were found try { if (results.hasMore()) { if(containerLog.isInfoEnabled()) containerLog.info("username " + username + " has multiple entries"); return (null); } } catch (PartialResultException ex) { if (!adCompat) throw ex; } String dn = getDistinguishedName(context, userBase, result); if (containerLog.isTraceEnabled()) containerLog.trace(" entry found for " + username + " with dn " + dn); // Get the entry's attributes Attributes attrs = result.getAttributes(); if (attrs == null) return null; // Retrieve value of userPassword String password = null; if (userPassword != null) password = getAttributeValue(userPassword, attrs); // Retrieve values of userRoleName attribute ArrayList<String> roles = null; if (userRoleName != null) roles = addAttributeValues(userRoleName, attrs, roles); return new User(username, dn, password, roles); }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected boolean checkCredentials(DirContext context, User user, String credentials) throws NamingException { boolean validated = false; if (userPassword == null) { validated = bindAsUser(context, user, credentials); } else { validated = compareCredentials(context, user, credentials); } if (containerLog.isTraceEnabled()) { if (validated) { containerLog.trace(sm.getString("jndiRealm.authenticateSuccess", user.getUserName())); } else { containerLog.trace(sm.getString("jndiRealm.authenticateFailure", user.getUserName())); } } return (validated); }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected boolean compareCredentials(DirContext context, User info, String credentials) throws NamingException { if (info == null || credentials == null) return (false); String password = info.getPassword(); if (password == null) return (false); // Validate the credentials specified by the user if (containerLog.isTraceEnabled()) containerLog.trace(" validating credentials"); boolean validated = false; if (hasMessageDigest()) { // Some directories prefix the password with the hash type // The string is in a format compatible with Base64.encode not // the Hex encoding of the parent class. if (password.startsWith("{MD5}") || password.startsWith("{SHA}")) { /* sync since super.digest() does this same thing */ synchronized (this) { password = password.substring(5); md.reset(); md.update(credentials.getBytes(B2CConverter.ISO_8859_1)); String digestedPassword = Base64.encode(md.digest()); validated = password.equals(digestedPassword); } } else if (password.startsWith("{SSHA}")) { // Bugzilla 32938 /* sync since super.digest() does this same thing */ synchronized (this) { password = password.substring(6); md.reset(); md.update(credentials.getBytes(B2CConverter.ISO_8859_1)); // Decode stored password. ByteChunk pwbc = new ByteChunk(password.length()); try { pwbc.append(password.getBytes(B2CConverter.ISO_8859_1), 0, password.length()); } catch (IOException e) { // Should never happen containerLog.error("Could not append password bytes to chunk: ", e); } CharChunk decoded = new CharChunk(); Base64.decode(pwbc, decoded); char[] pwarray = decoded.getBuffer(); // Split decoded password into hash and salt. final int saltpos = 20; byte[] hash = new byte[saltpos]; for (int i=0; i< hash.length; i++) { hash[i] = (byte) pwarray[i]; } byte[] salt = new byte[pwarray.length - saltpos]; for (int i=0; i< salt.length; i++) salt[i] = (byte)pwarray[i+saltpos]; md.update(salt); byte[] dp = md.digest(); validated = Arrays.equals(dp, hash); } // End synchronized(this) block } else { // Hex hashes should be compared case-insensitive validated = (digest(credentials).equalsIgnoreCase(password)); } } else validated = (digest(credentials).equals(password)); return (validated); }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected boolean bindAsUser(DirContext context, User user, String credentials) throws NamingException { if (credentials == null || user == null) return (false); String dn = user.getDN(); if (dn == null) return (false); // Validate the credentials specified by the user if (containerLog.isTraceEnabled()) { containerLog.trace(" validating credentials by binding as the user"); } userCredentialsAdd(context, dn, credentials); // Elicit an LDAP bind operation boolean validated = false; try { if (containerLog.isTraceEnabled()) { containerLog.trace(" binding as " + dn); } context.getAttributes("", null); validated = true; } catch (AuthenticationException e) { if (containerLog.isTraceEnabled()) { containerLog.trace(" bind attempt failed"); } } userCredentialsRemove(context); return (validated); }
// in java/org/apache/catalina/realm/JNDIRealm.java
private void userCredentialsAdd(DirContext context, String dn, String credentials) throws NamingException { // Set up security environment to bind as the user context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn); context.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
private void userCredentialsRemove(DirContext context) throws NamingException { // Restore the original security environment if (connectionName != null) { context.addToEnvironment(Context.SECURITY_PRINCIPAL, connectionName); } else { context.removeFromEnvironment(Context.SECURITY_PRINCIPAL); } if (connectionPassword != null) { context.addToEnvironment(Context.SECURITY_CREDENTIALS, connectionPassword); } else { context.removeFromEnvironment(Context.SECURITY_CREDENTIALS); } }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected List<String> getRoles(DirContext context, User user) throws NamingException { if (user == null) return (null); String dn = user.getDN(); String username = user.getUserName(); if (dn == null || username == null) return (null); if (containerLog.isTraceEnabled()) containerLog.trace(" getRoles(" + dn + ")"); // Start with roles retrieved from the user entry List<String> list = new ArrayList<String>(); List<String> userRoles = user.getRoles(); if (userRoles != null) { list.addAll(userRoles); } if (commonRole != null) list.add(commonRole); if (containerLog.isTraceEnabled()) { containerLog.trace(" Found " + list.size() + " user internal roles"); for (int i=0; i<list.size(); i++) containerLog.trace( " Found user internal role " + list.get(i)); } // Are we configured to do role searches? if ((roleFormat == null) || (roleName == null)) return (list); // Set up parameters for an appropriate search String filter = roleFormat.format(new String[] { doRFC2254Encoding(dn), username }); SearchControls controls = new SearchControls(); if (roleSubtree) controls.setSearchScope(SearchControls.SUBTREE_SCOPE); else controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); controls.setReturningAttributes(new String[] {roleName}); String base = null; if (roleBaseFormat != null) { NameParser np = context.getNameParser(""); Name name = np.parse(dn); String nameParts[] = new String[name.size()]; for (int i = 0; i < name.size(); i++) { nameParts[i] = name.get(i); } base = roleBaseFormat.format(nameParts); } // Perform the configured search and process the results NamingEnumeration<SearchResult> results = null; try { if (roleSearchAsUser) { userCredentialsAdd(context, dn, user.getPassword()); } results = context.search(base, filter, controls); } finally { if (roleSearchAsUser) { userCredentialsRemove(context); } } if (results == null) return (list); // Should never happen, but just in case ... HashMap<String, String> groupMap = new HashMap<String, String>(); try { while (results.hasMore()) { SearchResult result = results.next(); Attributes attrs = result.getAttributes(); if (attrs == null) continue; String dname = getDistinguishedName(context, roleBase, result); String name = getAttributeValue(roleName, attrs); if (name != null && dname != null) { groupMap.put(dname, name); } } } catch (PartialResultException ex) { if (!adCompat) throw ex; } Set<String> keys = groupMap.keySet(); if (containerLog.isTraceEnabled()) { containerLog.trace(" Found " + keys.size() + " direct roles"); for (String key: keys) { containerLog.trace( " Found direct role " + key + " -> " + groupMap.get(key)); } } // if nested group search is enabled, perform searches for nested groups until no new group is found if (getRoleNested()) { // The following efficient algorithm is known as memberOf Algorithm, as described in "Practices in // Directory Groups". It avoids group slurping and handles cyclic group memberships as well. // See http://middleware.internet2.edu/dir/ for details Map<String, String> newGroups = new HashMap<String,String>(groupMap); while (!newGroups.isEmpty()) { Map<String, String> newThisRound = new HashMap<String, String>(); // Stores the groups we find in this iteration for (Entry<String, String> group : newGroups.entrySet()) { filter = roleFormat.format(new String[] { group.getKey(), group.getValue() }); if (containerLog.isTraceEnabled()) { containerLog.trace("Perform a nested group search with base "+ roleBase + " and filter " + filter); } results = context.search(roleBase, filter, controls); try { while (results.hasMore()) { SearchResult result = results.next(); Attributes attrs = result.getAttributes(); if (attrs == null) continue; String dname = getDistinguishedName(context, roleBase, result); String name = getAttributeValue(roleName, attrs); if (name != null && dname != null && !groupMap.keySet().contains(dname)) { groupMap.put(dname, name); newThisRound.put(dname, name); if (containerLog.isTraceEnabled()) { containerLog.trace(" Found nested role " + dname + " -> " + name); } } } } catch (PartialResultException ex) { if (!adCompat) throw ex; } } newGroups = newThisRound; } } list.addAll(groupMap.values()); return list; }
// in java/org/apache/catalina/realm/JNDIRealm.java
private String getAttributeValue(String attrId, Attributes attrs) throws NamingException { if (containerLog.isTraceEnabled()) containerLog.trace(" retrieving attribute " + attrId); if (attrId == null || attrs == null) return null; Attribute attr = attrs.get(attrId); if (attr == null) return (null); Object value = attr.get(); if (value == null) return (null); String valueString = null; if (value instanceof byte[]) valueString = new String((byte[]) value); else valueString = value.toString(); return valueString; }
// in java/org/apache/catalina/realm/JNDIRealm.java
private ArrayList<String> addAttributeValues(String attrId, Attributes attrs, ArrayList<String> values) throws NamingException{ if (containerLog.isTraceEnabled()) containerLog.trace(" retrieving values for attribute " + attrId); if (attrId == null || attrs == null) return values; if (values == null) values = new ArrayList<String>(); Attribute attr = attrs.get(attrId); if (attr == null) return (values); NamingEnumeration<?> e = attr.getAll(); try { while(e.hasMore()) { String value = (String)e.next(); values.add(value); } } catch (PartialResultException ex) { if (!adCompat) throw ex; } return values; }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected synchronized Principal getPrincipal(DirContext context, String username, GSSCredential gssCredential) throws NamingException { User user = null; List<String> roles = null; try { if (gssCredential != null && isUseDelegatedCredential()) { // Set up context context.addToEnvironment( Context.SECURITY_AUTHENTICATION, "GSSAPI"); context.addToEnvironment( "javax.security.sasl.server.authentication", "true"); context.addToEnvironment( "javax.security.sasl.qop", "auth-conf"); // Note: Subject already set in SPNEGO authenticator so no need // for Subject.doAs() here } user = getUser(context, username); if (user != null) { roles = getRoles(context, user); } } finally { try { context.removeFromEnvironment( Context.SECURITY_AUTHENTICATION); } catch (NamingException e) { // Ignore } try { context.removeFromEnvironment( "javax.security.sasl.server.authentication"); } catch (NamingException e) { // Ignore } try { context.removeFromEnvironment( "javax.security.sasl.qop"); } catch (NamingException e) { // Ignore } } if (user != null) { return new GenericPrincipal(user.getUserName(), user.getPassword(), roles, null, null, gssCredential); } return null; }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected DirContext open() throws NamingException { // Do nothing if there is a directory server connection already open if (context != null) return (context); try { // Ensure that we have a directory context available context = new InitialDirContext(getDirectoryContextEnvironment()); } catch (Exception e) { connectionAttempt = 1; // log the first exception. containerLog.warn(sm.getString("jndiRealm.exception"), e); // Try connecting to the alternate url. context = new InitialDirContext(getDirectoryContextEnvironment()); } finally { // reset it in case the connection times out. // the primary may come back. connectionAttempt = 0; } return (context); }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected String getDistinguishedName(DirContext context, String base, SearchResult result) throws NamingException { // Get the entry's distinguished name. For relative results, this means // we need to composite a name with the base name, the context name, and // the result name. For non-relative names, use the returned name. if (result.isRelative()) { if (containerLog.isTraceEnabled()) { containerLog.trace(" search returned relative name: " + result.getName()); } NameParser parser = context.getNameParser(""); Name contextName = parser.parse(context.getNameInNamespace()); Name baseName = parser.parse(base); // Bugzilla 32269 Name entryName = parser.parse(new CompositeName(result.getName()).get(0)); Name name = contextName.addAll(baseName); name = name.addAll(entryName); return name.toString(); } else { String absoluteName = result.getName(); if (containerLog.isTraceEnabled()) containerLog.trace(" search returned absolute name: " + result.getName()); try { // Normalize the name by running it through the name parser. NameParser parser = context.getNameParser(""); URI userNameUri = new URI(absoluteName); String pathComponent = userNameUri.getPath(); // Should not ever have an empty path component, since that is /{DN} if (pathComponent.length() < 1 ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); } Name name = parser.parse(pathComponent.substring(1)); return name.toString(); } catch ( URISyntaxException e ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); } } }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
protected void createMBeans(String prefix, Context context) throws NamingException { if (log.isDebugEnabled()) { log.debug("Creating MBeans for Global JNDI Resources in Context '" + prefix + "'"); } try { NamingEnumeration<Binding> bindings = context.listBindings(""); while (bindings.hasMore()) { Binding binding = bindings.next(); String name = prefix + binding.getName(); Object value = context.lookup(binding.getName()); if (log.isDebugEnabled()) { log.debug("Checking resource " + name); } if (value instanceof Context) { createMBeans(name + "/", (Context) value); } else if (value instanceof UserDatabase) { try { createMBeans(name, (UserDatabase) value); } catch (Exception e) { log.error("Exception creating UserDatabase MBeans for " + name, e); } } } } catch( RuntimeException ex) { log.error("RuntimeException " + ex); } catch( OperationNotSupportedException ex) { log.error("Operation not supported " + ex); } }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
Filter getFilter() throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { // Return the existing filter instance, if any if (this.filter != null) return (this.filter); // Identify the class loader we will be using String filterClass = filterDef.getFilterClass(); this.filter = (Filter) getInstanceManager().newInstance(filterClass); initFilter(); return (this.filter); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
void setFilterDef(FilterDef filterDef) throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { this.filterDef = filterDef; if (filterDef == null) { // Release any previously allocated filter instance if (this.filter != null){ if (Globals.IS_SECURITY_ENABLED) { try{ SecurityUtil.doAsPrivilege("destroy", filter); } catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); } SecurityUtil.remove(filter); } else { filter.destroy(); } if (!context.getIgnoreAnnotations()) { try { ((StandardContext) context).getInstanceManager().destroyInstance(this.filter); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); } } } this.filter = null; } else { // Allocate a new filter instance if necessary if (filterDef.getFilter() == null) { getFilter(); } } }
// in java/org/apache/catalina/core/ApplicationContext.java
private static void listCollectionPaths(Set<String> set, DirContext resources, String path) throws NamingException { Enumeration<Binding> childPaths = resources.listBindings(path); while (childPaths.hasMoreElements()) { Binding binding = childPaths.nextElement(); String name = binding.getName(); StringBuilder childPath = new StringBuilder(path); if (!"/".equals(path) && !path.endsWith("/")) childPath.append("/"); childPath.append(name); Object object = binding.getObject(); if (object instanceof DirContext) { childPath.append("/"); } set.add(childPath.toString()); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { Class<?> clazz = loadClassMaybePrivileged(className, classLoader); return newInstance(clazz.newInstance(), clazz); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(final String className, final ClassLoader classLoader) throws IllegalAccessException, NamingException, InvocationTargetException, InstantiationException, ClassNotFoundException { Class<?> clazz = classLoader.loadClass(className); return newInstance(clazz.newInstance(), clazz); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public void newInstance(Object o) throws IllegalAccessException, InvocationTargetException, NamingException { newInstance(o, o.getClass()); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
private Object newInstance(Object instance, Class<?> clazz) throws IllegalAccessException, InvocationTargetException, NamingException { if (!ignoreAnnotations) { Map<String, String> injections = injectionMap.get(clazz.getName()); populateAnnotationsCache(clazz, injections); processAnnotations(instance, injections); postConstruct(instance, clazz); } return instance; }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected void populateAnnotationsCache(Class<?> clazz, Map<String, String> injections) throws IllegalAccessException, InvocationTargetException, NamingException { List<AnnotationCacheEntry> annotations = null; while (clazz != null) { AnnotationCacheEntry[] annotationsArray = null; synchronized (annotationCache) { annotationsArray = annotationCache.get(clazz); } if (annotationsArray == null) { if (annotations == null) { annotations = new ArrayList<AnnotationCacheEntry>(); } else { annotations.clear(); } if (context != null) { // Initialize fields annotations for resource injection if // JNDI is enabled Field[] fields = null; if (Globals.IS_SECURITY_ENABLED) { final Class<?> clazz2 = clazz; fields = AccessController.doPrivileged( new PrivilegedAction<Field[]>(){ @Override public Field[] run(){ return clazz2.getDeclaredFields(); } }); } else { fields = clazz.getDeclaredFields(); } for (Field field : fields) { if (injections != null && injections.containsKey(field.getName())) { annotations.add(new AnnotationCacheEntry( field.getName(), null, injections.get(field.getName()), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(Resource.class)) { Resource annotation = field.getAnnotation(Resource.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(EJB.class)) { EJB annotation = field.getAnnotation(EJB.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(WebServiceRef.class)) { WebServiceRef annotation = field.getAnnotation(WebServiceRef.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(PersistenceContext.class)) { PersistenceContext annotation = field.getAnnotation(PersistenceContext.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(PersistenceUnit.class)) { PersistenceUnit annotation = field.getAnnotation(PersistenceUnit.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } } } // Initialize methods annotations Method[] methods = null; if (Globals.IS_SECURITY_ENABLED) { final Class<?> clazz2 = clazz; methods = AccessController.doPrivileged( new PrivilegedAction<Method[]>(){ @Override public Method[] run(){ return clazz2.getDeclaredMethods(); } }); } else { methods = clazz.getDeclaredMethods(); } Method postConstruct = null; Method preDestroy = null; for (Method method : methods) { String methodName = method.getName(); if (context != null) { // Resource injection only if JNDI is enabled if (injections != null && methodName.startsWith("set") && methodName.length() > 3) { String fieldName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); if (injections.containsKey(fieldName)) { annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), injections.get(method.getName()), AnnotationCacheEntryType.SETTER)); break; } } if (method.isAnnotationPresent(Resource.class)) { Resource annotation = method.getAnnotation(Resource.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(EJB.class)) { EJB annotation = method.getAnnotation(EJB.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(WebServiceRef.class)) { WebServiceRef annotation = method.getAnnotation(WebServiceRef.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(PersistenceContext.class)) { PersistenceContext annotation = method.getAnnotation(PersistenceContext.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(PersistenceUnit.class)) { PersistenceUnit annotation = method.getAnnotation(PersistenceUnit.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } } if (method.isAnnotationPresent(PostConstruct.class)) { if ((postConstruct != null) || (method.getParameterTypes().length != 0) || (Modifier.isStatic(method.getModifiers())) || (method.getExceptionTypes().length > 0) || (!method.getReturnType().getName().equals("void"))) { throw new IllegalArgumentException( "Invalid PostConstruct annotation"); } postConstruct = method; } if (method.isAnnotationPresent(PreDestroy.class)) { if ((preDestroy != null || method.getParameterTypes().length != 0) || (Modifier.isStatic(method.getModifiers())) || (method.getExceptionTypes().length > 0) || (!method.getReturnType().getName().equals("void"))) { throw new IllegalArgumentException( "Invalid PreDestroy annotation"); } preDestroy = method; } } if (postConstruct != null) { annotations.add(new AnnotationCacheEntry( postConstruct.getName(), postConstruct.getParameterTypes(), null, AnnotationCacheEntryType.POST_CONSTRUCT)); } if (preDestroy != null) { annotations.add(new AnnotationCacheEntry( preDestroy.getName(), preDestroy.getParameterTypes(), null, AnnotationCacheEntryType.PRE_DESTROY)); } if (annotations.isEmpty()) { // Use common object to save memory annotationsArray = ANNOTATIONS_EMPTY; } else { annotationsArray = annotations.toArray( new AnnotationCacheEntry[annotations.size()]); } synchronized (annotationCache) { annotationCache.put(clazz, annotationsArray); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected void processAnnotations(Object instance, Map<String, String> injections) throws IllegalAccessException, InvocationTargetException, NamingException { if (context == null) { // No resource injection return; } Class<?> clazz = instance.getClass(); while (clazz != null) { AnnotationCacheEntry[] annotations; synchronized (annotationCache) { annotations = annotationCache.get(clazz); } for (AnnotationCacheEntry entry : annotations) { if (entry.getType() == AnnotationCacheEntryType.SETTER) { lookupMethodResource(context, instance, getMethod(clazz, entry), entry.getName(), clazz); } else if (entry.getType() == AnnotationCacheEntryType.FIELD) { lookupFieldResource(context, instance, getField(clazz, entry), entry.getName(), clazz); } } clazz = clazz.getSuperclass(); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected static void lookupFieldResource(Context context, Object instance, Field field, String name, Class<?> clazz) throws NamingException, IllegalAccessException { Object lookedupResource; boolean accessibility; String normalizedName = normalize(name); if ((normalizedName != null) && (normalizedName.length() > 0)) { lookedupResource = context.lookup(normalizedName); } else { lookedupResource = context.lookup(clazz.getName() + "/" + field.getName()); } synchronized (field) { accessibility = field.isAccessible(); field.setAccessible(true); field.set(instance, lookedupResource); field.setAccessible(accessibility); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected static void lookupMethodResource(Context context, Object instance, Method method, String name, Class<?> clazz) throws NamingException, IllegalAccessException, InvocationTargetException { if (!method.getName().startsWith("set") || method.getName().length() < 4 || method.getParameterTypes().length != 1 || !method.getReturnType().getName().equals("void")) { throw new IllegalArgumentException("Invalid method resource injection annotation"); } Object lookedupResource; boolean accessibility; String normalizedName = normalize(name); if ((normalizedName != null) && (normalizedName.length() > 0)) { lookedupResource = context.lookup(normalizedName); } else { lookedupResource = context.lookup( clazz.getName() + "/" + getName(method)); } synchronized (method) { accessibility = method.isAccessible(); method.setAccessible(true); method.invoke(instance, lookedupResource); method.setAccessible(accessibility); } }
// in java/org/apache/catalina/core/NamingContextListener.java
private void createNamingContext() throws NamingException { // Creating the comp subcontext if (container instanceof Server) { compCtx = namingContext; envCtx = namingContext; } else { compCtx = namingContext.createSubcontext("comp"); envCtx = compCtx.createSubcontext("env"); } int i; if (log.isDebugEnabled()) log.debug("Creating JNDI naming context"); if (namingResources == null) { namingResources = new NamingResources(); namingResources.setContainer(container); } // Resource links ContextResourceLink[] resourceLinks = namingResources.findResourceLinks(); for (i = 0; i < resourceLinks.length; i++) { addResourceLink(resourceLinks[i]); } // Resources ContextResource[] resources = namingResources.findResources(); for (i = 0; i < resources.length; i++) { addResource(resources[i]); } // Resources Env ContextResourceEnvRef[] resourceEnvRefs = namingResources.findResourceEnvRefs(); for (i = 0; i < resourceEnvRefs.length; i++) { addResourceEnvRef(resourceEnvRefs[i]); } // Environment entries ContextEnvironment[] contextEnvironments = namingResources.findEnvironments(); for (i = 0; i < contextEnvironments.length; i++) { addEnvironment(contextEnvironments[i]); } // EJB references ContextEjb[] ejbs = namingResources.findEjbs(); for (i = 0; i < ejbs.length; i++) { addEjb(ejbs[i]); } // WebServices references ContextService[] services = namingResources.findServices(); for (i = 0; i < services.length; i++) { addService(services[i]); } // Binding a User Transaction reference if (container instanceof Context) { try { Reference ref = new TransactionRef(); compCtx.bind("UserTransaction", ref); ContextTransaction transaction = namingResources.getTransaction(); if (transaction != null) { Iterator<String> params = transaction.listProperties(); while (params.hasNext()) { String paramName = params.next(); String paramValue = (String) transaction.getProperty(paramName); StringRefAddr refAddr = new StringRefAddr(paramName, paramValue); ref.add(refAddr); } } } catch (NameAlreadyBoundException e) { // Ignore because UserTransaction was obviously // added via ResourceLink } catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); } } // Binding the resources directory context if (container instanceof Context) { try { compCtx.bind("Resources", ((Container) container).getResources()); } catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); } } }
// in java/org/apache/catalina/core/NamingContextListener.java
private void createSubcontexts(javax.naming.Context ctx, String name) throws NamingException { javax.naming.Context currentContext = ctx; StringTokenizer tokenizer = new StringTokenizer(name, "/"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if ((!token.equals("")) && (tokenizer.hasMoreTokens())) { try { currentContext = currentContext.createSubcontext(token); } catch (NamingException e) { // Silent catch. Probably an object is already bound in // the context. currentContext = (javax.naming.Context) currentContext.lookup(token); } } } }
(Domain) LifecycleException 33
              
// in java/org/apache/catalina/startup/FailedContext.java
Override protected void startInternal() throws LifecycleException { throw new LifecycleException( sm.getString("failedContext.start", getName())); }
// in java/org/apache/catalina/loader/WebappLoader.java
Override protected void startInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug(sm.getString("webappLoader.starting")); if (container.getResources() == null) { log.info("No resources for " + container); setState(LifecycleState.STARTING); return; } // Register a stream handler factory for the JNDI protocol URLStreamHandlerFactory streamHandlerFactory = DirContextURLStreamHandlerFactory.getInstance(); if (first) { first = false; try { URL.setURLStreamHandlerFactory(streamHandlerFactory); } catch (Exception e) { // Log and continue anyway, this is not critical log.error("Error registering jndi stream handler", e); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This is likely a dual registration log.info("Dual registration of jndi stream handler: " + t.getMessage()); } } // Construct a class loader based on our current repositories list try { classLoader = createClassLoader(); classLoader.setResources(container.getResources()); classLoader.setDelegate(this.delegate); classLoader.setSearchExternalFirst(searchExternalFirst); for (int i = 0; i < repositories.length; i++) { classLoader.addRepository(repositories[i]); } // Configure our repositories setRepositories(); setClassPath(); setPermissions(); ((Lifecycle) classLoader).start(); // Binding the Webapp class loader to the directory context DirContextURLStreamHandler.bind(classLoader, this.container.getResources()); String contextName = container.getName(); if (!contextName.startsWith("/")) { contextName = "/" + contextName; } ObjectName cloname = new ObjectName(container.getDomain() + ":type=WebappClassLoader,context=" + contextName + ",host=" + container.getParent().getName()); Registry.getRegistry(null, null) .registerComponent(classLoader, cloname, null); } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error( "LifecycleException ", t ); throw new LifecycleException("start: ", t); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/realm/MemoryRealm.java
Override protected void startInternal() throws LifecycleException { // Validate the existence of our database file File file = new File(pathname); if (!file.isAbsolute()) file = new File(getContainer().getCatalinaBase(), pathname); if (!file.exists() || !file.canRead()) throw new LifecycleException (sm.getString("memoryRealm.loadExist", file.getAbsolutePath())); // Load the contents of the database file if (log.isDebugEnabled()) log.debug(sm.getString("memoryRealm.loadPath", file.getAbsolutePath())); Digester digester = getDigester(); try { synchronized (digester) { digester.push(this); digester.parse(file); } } catch (Exception e) { throw new LifecycleException (sm.getString("memoryRealm.readXml"), e); } finally { digester.reset(); } super.startInternal(); }
// in java/org/apache/catalina/realm/JNDIRealm.java
Override protected void startInternal() throws LifecycleException { // Validate that we can open our connection try { open(); } catch (NamingException e) { throw new LifecycleException(sm.getString("jndiRealm.open"), e); } super.startInternal(); }
// in java/org/apache/catalina/realm/UserDatabaseRealm.java
Override protected void startInternal() throws LifecycleException { try { Context context = getServer().getGlobalNamingContext(); database = (UserDatabase) context.lookup(resourceName); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); containerLog.error(sm.getString("userDatabaseRealm.lookup", resourceName), e); database = null; } if (database == null) { throw new LifecycleException (sm.getString("userDatabaseRealm.noDatabase", resourceName)); } super.startInternal(); }
// in java/org/apache/catalina/realm/RealmBase.java
Override protected void startInternal() throws LifecycleException { // Create a MessageDigest instance for credentials, if desired if (digest != null) { try { md = MessageDigest.getInstance(digest); } catch (NoSuchAlgorithmException e) { throw new LifecycleException (sm.getString("realmBase.algorithm", digest), e); } } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/realm/RealmBase.java
private static X509UsernameRetriever createUsernameRetriever(String className) throws LifecycleException { if(null == className || "".equals(className.trim())) return new X509SubjectDnRetriever(); try { @SuppressWarnings("unchecked") Class<? extends X509UsernameRetriever> clazz = (Class<? extends X509UsernameRetriever>)Class.forName(className); return clazz.newInstance(); } catch (ClassNotFoundException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassNotFoundException", className), e); } catch (InstantiationException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.InstantiationException", className), e); } catch (IllegalAccessException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.IllegalAccessException", className), e); } catch (ClassCastException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e); } }
// in java/org/apache/catalina/valves/RequestFilterValve.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); if (!allowValid || !denyValid) { throw new LifecycleException( sm.getString("requestFilterValve.configInvalid")); } }
// in java/org/apache/catalina/valves/RequestFilterValve.java
Override protected synchronized void startInternal() throws LifecycleException { if (!allowValid || !denyValid) { throw new LifecycleException( sm.getString("requestFilterValve.configInvalid")); } super.startInternal(); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
Override protected synchronized void startInternal() throws LifecycleException { try { open() ; } catch (SQLException e) { throw new LifecycleException(e); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/ha/context/ReplicatedContext.java
Override protected synchronized void startInternal() throws LifecycleException { try { CatalinaCluster catclust = (CatalinaCluster)this.getCluster(); if (this.context == null) this.context = new ReplApplContext(this); if ( catclust != null ) { ReplicatedMap<String,Object> map = new ReplicatedMap<String,Object>(this, catclust.getChannel(),DEFAULT_REPL_TIMEOUT, getName(),getClassLoaders()); map.setChannelSendOptions(mapSendOptions); ((ReplApplContext)this.context).setAttributeMap(map); if (getAltDDName() != null) context.setAttribute(Globals.ALT_DD_ATTR, getAltDDName()); } super.startInternal(); } catch ( Exception x ) { log.error("Unable to start ReplicatedContext",x); throw new LifecycleException("Failed to start ReplicatedContext",x); } }
// in java/org/apache/catalina/ha/session/BackupManager.java
Override protected synchronized void startInternal() throws LifecycleException { super.startInternal(); try { if (getCluster() == null) { Cluster cluster = getContainer().getCluster(); if (cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster)cluster); } else { throw new LifecycleException( sm.getString("backupManager.noCluster", getName())); } } cluster.registerManager(this); LazyReplicatedMap<String,Session> map = new LazyReplicatedMap<String,Session>(this, cluster.getChannel(), rpcTimeout, getMapName(), getClassLoaders()); map.setChannelSendOptions(mapSendOptions); this.sessions = map; } catch ( Exception x ) { log.error(sm.getString("backupManager.startUnable", getName()),x); throw new LifecycleException(sm.getString("backupManager.startFailed", getName()),x); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOn.java
Override protected synchronized void startInternal() throws LifecycleException { clusterSSOListener = new ClusterSingleSignOnListener(); clusterSSOListener.setClusterSSO(this); // Load the cluster component, if any try { //the channel is already running Cluster cluster = getCluster(); // stop remove cluster binding if(cluster == null) { Container host = getContainer(); if(host != null && host instanceof Host) { cluster = host.getCluster(); if(cluster != null && cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster) cluster); getCluster().addClusterListener(clusterSSOListener); } else { Container engine = host.getParent(); if(engine != null && engine instanceof Engine) { cluster = engine.getCluster(); if(cluster != null && cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster) cluster); getCluster().addClusterListener(clusterSSOListener); } } else { cluster = null; } } } } if (cluster == null) { throw new LifecycleException( "There is no Cluster for ClusterSingleSignOn"); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new LifecycleException( "ClusterSingleSignOn exception during clusterLoad " + t); } super.startInternal(); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
Override protected void startInternal() throws LifecycleException { if (log.isInfoEnabled()) log.info("Cluster is about to start"); try { checkDefaults(); registerClusterValve(); channel.addMembershipListener(this); channel.addChannelListener(this); channel.start(channelStartOptions); if (clusterDeployer != null) clusterDeployer.start(); //register JMX objects ClusterJmxHelper.registerDefaultCluster(this); // Notify our interested LifecycleListeners } catch (Exception x) { log.error("Unable to start cluster.", x); throw new LifecycleException(x); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/connector/Connector.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); // Initialize adapter adapter = new CoyoteAdapter(this); protocolHandler.setAdapter(adapter); // Make sure parseBodyMethodsSet has a default if( null == parseBodyMethodsSet ) { setParseBodyMethods(getParseBodyMethods()); } try { protocolHandler.init(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerInitializationFailed"), e); } // Initialize mapper listener mapperListener.init(); }
// in java/org/apache/catalina/connector/Connector.java
Override protected void startInternal() throws LifecycleException { // Validate settings before starting if (getPort() < 0) { throw new LifecycleException(sm.getString( "coyoteConnector.invalidPort", Integer.valueOf(getPort()))); } setState(LifecycleState.STARTING); try { protocolHandler.start(); } catch (Exception e) { String errPrefix = ""; if(this.service != null) { errPrefix += "service.getName(): \"" + this.service.getName() + "\"; "; } throw new LifecycleException (errPrefix + " " + sm.getString ("coyoteConnector.protocolHandlerStartFailed"), e); } mapperListener.start(); }
// in java/org/apache/catalina/connector/Connector.java
Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); try { protocolHandler.stop(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerStopFailed"), e); } mapperListener.stop(); }
// in java/org/apache/catalina/connector/Connector.java
Override protected void destroyInternal() throws LifecycleException { mapperListener.destroy(); try { protocolHandler.destroy(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerDestroyFailed"), e); } if (getService() != null) { getService().removeConnector(this); } super.destroyInternal(); }
// in java/org/apache/catalina/core/ContainerBase.java
Override protected synchronized void startInternal() throws LifecycleException { // Start our subordinate components, if any if ((loader != null) && (loader instanceof Lifecycle)) ((Lifecycle) loader).start(); logger = null; getLogger(); if ((manager != null) && (manager instanceof Lifecycle)) ((Lifecycle) manager).start(); if ((cluster != null) && (cluster instanceof Lifecycle)) ((Lifecycle) cluster).start(); Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) ((Lifecycle) realm).start(); if ((resources != null) && (resources instanceof Lifecycle)) ((Lifecycle) resources).start(); // Start our child containers, if any Container children[] = findChildren(); List<Future<Void>> results = new ArrayList<Future<Void>>(); for (int i = 0; i < children.length; i++) { results.add(startStopExecutor.submit(new StartChild(children[i]))); } boolean fail = false; for (Future<Void> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString("containerBase.threadedStartFailed"), e); fail = true; } } if (fail) { throw new LifecycleException( sm.getString("containerBase.threadedStartFailed")); } // Start the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle) ((Lifecycle) pipeline).start(); setState(LifecycleState.STARTING); // Start our thread threadStart(); }
// in java/org/apache/catalina/core/ContainerBase.java
Override protected synchronized void stopInternal() throws LifecycleException { // Stop our thread threadStop(); setState(LifecycleState.STOPPING); // Stop the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle && ((Lifecycle) pipeline).getState().isAvailable()) { ((Lifecycle) pipeline).stop(); } // Stop our child containers, if any Container children[] = findChildren(); List<Future<Void>> results = new ArrayList<Future<Void>>(); for (int i = 0; i < children.length; i++) { results.add(startStopExecutor.submit(new StopChild(children[i]))); } boolean fail = false; for (Future<Void> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString("containerBase.threadedStopFailed"), e); fail = true; } } if (fail) { throw new LifecycleException( sm.getString("containerBase.threadedStopFailed")); } // Stop our subordinate components, if any if ((resources != null) && (resources instanceof Lifecycle)) { ((Lifecycle) resources).stop(); } Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) { ((Lifecycle) realm).stop(); } if ((cluster != null) && (cluster instanceof Lifecycle)) { ((Lifecycle) cluster).stop(); } if ((manager != null) && (manager instanceof Lifecycle) && ((Lifecycle) manager).getState().isAvailable() ) { ((Lifecycle) manager).stop(); } if ((loader != null) && (loader instanceof Lifecycle)) { ((Lifecycle) loader).stop(); } }
// in java/org/apache/catalina/core/StandardService.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); if (container != null) { container.init(); } // Initialize any Executors for (Executor executor : findExecutors()) { if (executor instanceof JmxEnabled) { ((JmxEnabled) executor).setDomain(getDomain()); } executor.init(); } // Initialize our defined Connectors synchronized (connectors) { for (Connector connector : connectors) { try { connector.init(); } catch (Exception e) { String message = sm.getString( "standardService.connector.initFailed", connector); log.error(message, e); if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) throw new LifecycleException(message); } } } }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void init() throws LifecycleException { if (!state.equals(LifecycleState.NEW)) { invalidTransition(Lifecycle.BEFORE_INIT_EVENT); } setStateInternal(LifecycleState.INITIALIZING, null, false); try { initInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); } setStateInternal(LifecycleState.INITIALIZED, null, false); }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void start() throws LifecycleException { if (LifecycleState.STARTING_PREP.equals(state) || LifecycleState.STARTING.equals(state) || LifecycleState.STARTED.equals(state)) { if (log.isDebugEnabled()) { Exception e = new LifecycleException(); log.debug(sm.getString("lifecycleBase.alreadyStarted", toString()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("lifecycleBase.alreadyStarted", toString())); } return; } if (state.equals(LifecycleState.NEW)) { init(); } else if (state.equals(LifecycleState.FAILED)){ stop(); } else if (!state.equals(LifecycleState.INITIALIZED) && !state.equals(LifecycleState.STOPPED)) { invalidTransition(Lifecycle.BEFORE_START_EVENT); } setStateInternal(LifecycleState.STARTING_PREP, null, false); try { startInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.startFail",toString()), t); } if (state.equals(LifecycleState.FAILED) || state.equals(LifecycleState.MUST_STOP)) { stop(); } else { // Shouldn't be necessary but acts as a check that sub-classes are // doing what they are supposed to. if (!state.equals(LifecycleState.STARTING)) { invalidTransition(Lifecycle.AFTER_START_EVENT); } setStateInternal(LifecycleState.STARTED, null, false); } }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void stop() throws LifecycleException { if (LifecycleState.STOPPING_PREP.equals(state) || LifecycleState.STOPPING.equals(state) || LifecycleState.STOPPED.equals(state)) { if (log.isDebugEnabled()) { Exception e = new LifecycleException(); log.debug(sm.getString("lifecycleBase.alreadyStopped", toString()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("lifecycleBase.alreadyStopped", toString())); } return; } if (state.equals(LifecycleState.NEW)) { state = LifecycleState.STOPPED; return; } if (!state.equals(LifecycleState.STARTED) && !state.equals(LifecycleState.FAILED) && !state.equals(LifecycleState.MUST_STOP)) { invalidTransition(Lifecycle.BEFORE_STOP_EVENT); } if (state.equals(LifecycleState.FAILED)) { // Don't transition to STOPPING_PREP as that would briefly mark the // component as available but do ensure the BEFORE_STOP_EVENT is // fired fireLifecycleEvent(BEFORE_STOP_EVENT, null); } else { setStateInternal(LifecycleState.STOPPING_PREP, null, false); } try { stopInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.stopFail",toString()), t); } if (state.equals(LifecycleState.MUST_DESTROY)) { // Complete stop process first setStateInternal(LifecycleState.STOPPED, null, false); destroy(); } else { // Shouldn't be necessary but acts as a check that sub-classes are // doing what they are supposed to. if (!state.equals(LifecycleState.STOPPING)) { invalidTransition(Lifecycle.AFTER_STOP_EVENT); } setStateInternal(LifecycleState.STOPPED, null, false); } }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void destroy() throws LifecycleException { if (LifecycleState.FAILED.equals(state)) { try { // Triggers clean-up stop(); } catch (LifecycleException e) { // Just log. Still want to destroy. log.warn(sm.getString("lifecycleBase.destroyStopFail"), e); } } if (LifecycleState.DESTROYING.equals(state) || LifecycleState.DESTROYED.equals(state)) { if (log.isDebugEnabled()) { Exception e = new LifecycleException(); log.debug(sm.getString("lifecycleBase.alreadyDestroyed", toString()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("lifecycleBase.alreadyDestroyed", toString())); } return; } if (!state.equals(LifecycleState.STOPPED) && !state.equals(LifecycleState.FAILED) && !state.equals(LifecycleState.NEW) && !state.equals(LifecycleState.INITIALIZED)) { invalidTransition(Lifecycle.BEFORE_DESTROY_EVENT); } setStateInternal(LifecycleState.DESTROYING, null, false); try { destroyInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); } setStateInternal(LifecycleState.DESTROYED, null, false); }
// in java/org/apache/catalina/util/LifecycleBase.java
private void invalidTransition(String type) throws LifecycleException { String msg = sm.getString("lifecycleBase.invalidTransition", type, toString(), state); throw new LifecycleException(msg); }
22
              
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error( "LifecycleException ", t ); throw new LifecycleException("start: ", t); }
// in java/org/apache/catalina/realm/MemoryRealm.java
catch (Exception e) { throw new LifecycleException (sm.getString("memoryRealm.readXml"), e); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { throw new LifecycleException(sm.getString("jndiRealm.open"), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { throw new LifecycleException (sm.getString("realmBase.algorithm", digest), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassNotFoundException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassNotFoundException", className), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (InstantiationException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.InstantiationException", className), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (IllegalAccessException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.IllegalAccessException", className), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassCastException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { throw new LifecycleException(e); }
// in java/org/apache/catalina/ha/context/ReplicatedContext.java
catch ( Exception x ) { log.error("Unable to start ReplicatedContext",x); throw new LifecycleException("Failed to start ReplicatedContext",x); }
// in java/org/apache/catalina/ha/session/BackupManager.java
catch ( Exception x ) { log.error(sm.getString("backupManager.startUnable", getName()),x); throw new LifecycleException(sm.getString("backupManager.startFailed", getName()),x); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOn.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new LifecycleException( "ClusterSingleSignOn exception during clusterLoad " + t); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to start cluster.", x); throw new LifecycleException(x); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerInitializationFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { String errPrefix = ""; if(this.service != null) { errPrefix += "service.getName(): \"" + this.service.getName() + "\"; "; } throw new LifecycleException (errPrefix + " " + sm.getString ("coyoteConnector.protocolHandlerStartFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerStopFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerDestroyFailed"), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { String message = sm.getString( "standardService.connector.initFailed", connector); log.error(message, e); if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) throw new LifecycleException(message); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.startFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.stopFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); }
122
              
// in java/org/apache/catalina/startup/FailedContext.java
Override protected void startInternal() throws LifecycleException { throw new LifecycleException( sm.getString("failedContext.start", getName())); }
// in java/org/apache/catalina/startup/FailedContext.java
Override protected void stopInternal() throws LifecycleException { // NO-OP // Allow stop to complete since it is used for clean-up }
// in java/org/apache/catalina/startup/Tomcat.java
public void init() throws LifecycleException { getServer(); getConnector(); server.init(); }
// in java/org/apache/catalina/startup/Tomcat.java
public void start() throws LifecycleException { getServer(); getConnector(); server.start(); }
// in java/org/apache/catalina/startup/Tomcat.java
public void stop() throws LifecycleException { getServer(); server.stop(); }
// in java/org/apache/catalina/startup/Tomcat.java
public void destroy() throws LifecycleException { getServer(); server.destroy(); // Could null out objects here }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public void start() throws LifecycleException { started = true; String encoding = null; try { encoding = System.getProperty("file.encoding"); } catch (SecurityException e) { return; } if (encoding.indexOf("EBCDIC")!=-1) { needConvert = true; } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public void stop() throws LifecycleException { // Clearing references should be done before setting started to // false, due to possible side effects clearReferences(); started = false; int length = files.length; for (int i = 0; i < length; i++) { files[i] = null; } length = jarFiles.length; for (int i = 0; i < length; i++) { try { if (jarFiles[i] != null) { jarFiles[i].close(); } } catch (IOException e) { // Ignore } jarFiles[i] = null; } notFoundResources.clear(); resourceEntries.clear(); resources = null; repositories = null; repositoryURLs = null; files = null; jarFiles = null; jarRealFiles = null; jarPath = null; jarNames = null; lastModifiedDates = null; paths = null; hasExternalRepositories = false; parent = null; permissionList.clear(); loaderPC.clear(); if (loaderDir != null) { deleteDir(loaderDir); } }
// in java/org/apache/catalina/loader/WebappLoader.java
Override protected void startInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug(sm.getString("webappLoader.starting")); if (container.getResources() == null) { log.info("No resources for " + container); setState(LifecycleState.STARTING); return; } // Register a stream handler factory for the JNDI protocol URLStreamHandlerFactory streamHandlerFactory = DirContextURLStreamHandlerFactory.getInstance(); if (first) { first = false; try { URL.setURLStreamHandlerFactory(streamHandlerFactory); } catch (Exception e) { // Log and continue anyway, this is not critical log.error("Error registering jndi stream handler", e); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This is likely a dual registration log.info("Dual registration of jndi stream handler: " + t.getMessage()); } } // Construct a class loader based on our current repositories list try { classLoader = createClassLoader(); classLoader.setResources(container.getResources()); classLoader.setDelegate(this.delegate); classLoader.setSearchExternalFirst(searchExternalFirst); for (int i = 0; i < repositories.length; i++) { classLoader.addRepository(repositories[i]); } // Configure our repositories setRepositories(); setClassPath(); setPermissions(); ((Lifecycle) classLoader).start(); // Binding the Webapp class loader to the directory context DirContextURLStreamHandler.bind(classLoader, this.container.getResources()); String contextName = container.getName(); if (!contextName.startsWith("/")) { contextName = "/" + contextName; } ObjectName cloname = new ObjectName(container.getDomain() + ":type=WebappClassLoader,context=" + contextName + ",host=" + container.getParent().getName()); Registry.getRegistry(null, null) .registerComponent(classLoader, cloname, null); } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error( "LifecycleException ", t ); throw new LifecycleException("start: ", t); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/loader/WebappLoader.java
Override protected void stopInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug(sm.getString("webappLoader.stopping")); setState(LifecycleState.STOPPING); // Remove context attributes as appropriate if (container instanceof Context) { ServletContext servletContext = ((Context) container).getServletContext(); servletContext.removeAttribute(Globals.CLASS_PATH_ATTR); } // Throw away our current class loader ((Lifecycle) classLoader).stop(); DirContextURLStreamHandler.unbind(classLoader); try { String contextName = container.getName(); if (!contextName.startsWith("/")) { contextName = "/" + contextName; } ObjectName cloname = new ObjectName(container.getDomain() + ":type=WebappClassLoader,context=" + contextName + ",host=" + container.getParent().getName()); Registry.getRegistry(null, null).unregisterComponent(cloname); } catch (Exception e) { log.error("LifecycleException ", e); } classLoader = null; }
// in java/org/apache/catalina/loader/VirtualWebappLoader.java
Override protected void startInternal() throws LifecycleException { // just add any jar/directory set in virtual classpath to the // repositories list before calling start on the standard WebappLoader StringTokenizer tkn = new StringTokenizer(virtualClasspath, ";"); Set<String> set = new LinkedHashSet<String>(); while (tkn.hasMoreTokens()) { String token = tkn.nextToken().trim(); if (token.isEmpty()) { continue; } if (log.isDebugEnabled()) log.debug(sm.getString("virtualWebappLoader.token", token)); if (token.endsWith("*.jar")) { // glob token = token.substring(0, token.length() - "*.jar".length()); File directory = new File(token); if (!directory.isDirectory()) { if (log.isDebugEnabled()) { log.debug(sm.getString( "virtualWebappLoader.token.notDirectory", directory.getAbsolutePath())); } continue; } if (log.isDebugEnabled()) { log.debug(sm.getString( "virtualWebappLoader.token.glob.dir", directory.getAbsolutePath())); } String filenames[] = directory.list(); Arrays.sort(filenames); for (int j = 0; j < filenames.length; j++) { String filename = filenames[j].toLowerCase(Locale.ENGLISH); if (!filename.endsWith(".jar")) continue; File file = new File(directory, filenames[j]); if (!file.isFile()) { if (log.isDebugEnabled()) { log.debug(sm.getString( "virtualWebappLoader.token.notFile", file.getAbsolutePath())); } continue; } if (log.isDebugEnabled()) { log.debug(sm.getString( "virtualWebappLoader.token.file", file.getAbsolutePath())); } set.add(file.toURI().toString()); } } else { // single file or directory File file = new File(token); if (!file.exists()) { if (log.isDebugEnabled()) { log.debug(sm.getString( "virtualWebappLoader.token.notExists", file.getAbsolutePath())); } continue; } if (log.isDebugEnabled()) { log.debug(sm.getString( "virtualWebappLoader.token.file", file.getAbsolutePath())); } set.add(file.toURI().toString()); } } for (String repository: set) { addRepository(repository); } super.startInternal(); }
// in java/org/apache/catalina/realm/MemoryRealm.java
Override protected void startInternal() throws LifecycleException { // Validate the existence of our database file File file = new File(pathname); if (!file.isAbsolute()) file = new File(getContainer().getCatalinaBase(), pathname); if (!file.exists() || !file.canRead()) throw new LifecycleException (sm.getString("memoryRealm.loadExist", file.getAbsolutePath())); // Load the contents of the database file if (log.isDebugEnabled()) log.debug(sm.getString("memoryRealm.loadPath", file.getAbsolutePath())); Digester digester = getDigester(); try { synchronized (digester) { digester.push(this); digester.parse(file); } } catch (Exception e) { throw new LifecycleException (sm.getString("memoryRealm.readXml"), e); } finally { digester.reset(); } super.startInternal(); }
// in java/org/apache/catalina/realm/CombinedRealm.java
Override protected void startInternal() throws LifecycleException { // Start 'sub-realms' then this one Iterator<Realm> iter = realms.iterator(); while (iter.hasNext()) { Realm realm = iter.next(); if (realm instanceof Lifecycle) { try { ((Lifecycle) realm).start(); } catch (LifecycleException e) { // If realm doesn't start can't authenticate against it iter.remove(); log.error(sm.getString("combinedRealm.realmStartFail", realm.getClass().getName()), e); } } } super.startInternal(); }
// in java/org/apache/catalina/realm/CombinedRealm.java
Override protected void stopInternal() throws LifecycleException { // Stop this realm, then the sub-realms (reverse order to start) super.stopInternal(); for (Realm realm : realms) { if (realm instanceof Lifecycle) { ((Lifecycle) realm).stop(); } } }
// in java/org/apache/catalina/realm/JNDIRealm.java
Override protected void startInternal() throws LifecycleException { // Validate that we can open our connection try { open(); } catch (NamingException e) { throw new LifecycleException(sm.getString("jndiRealm.open"), e); } super.startInternal(); }
// in java/org/apache/catalina/realm/JNDIRealm.java
Override protected void stopInternal() throws LifecycleException { super.stopInternal(); // Close any open directory server connection close(this.context); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
Override protected void startInternal() throws LifecycleException { // Create the roles PreparedStatement string StringBuilder temp = new StringBuilder("SELECT "); temp.append(roleNameCol); temp.append(" FROM "); temp.append(userRoleTable); temp.append(" WHERE "); temp.append(userNameCol); temp.append(" = ?"); preparedRoles = temp.toString(); // Create the credentials PreparedStatement string temp = new StringBuilder("SELECT "); temp.append(userCredCol); temp.append(" FROM "); temp.append(userTable); temp.append(" WHERE "); temp.append(userNameCol); temp.append(" = ?"); preparedCredentials = temp.toString(); super.startInternal(); }
// in java/org/apache/catalina/realm/UserDatabaseRealm.java
Override protected void startInternal() throws LifecycleException { try { Context context = getServer().getGlobalNamingContext(); database = (UserDatabase) context.lookup(resourceName); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); containerLog.error(sm.getString("userDatabaseRealm.lookup", resourceName), e); database = null; } if (database == null) { throw new LifecycleException (sm.getString("userDatabaseRealm.noDatabase", resourceName)); } super.startInternal(); }
// in java/org/apache/catalina/realm/UserDatabaseRealm.java
Override protected void stopInternal() throws LifecycleException { // Perform normal superclass finalization super.stopInternal(); // Release reference to our user database database = null; }
// in java/org/apache/catalina/realm/LockOutRealm.java
Override protected void startInternal() throws LifecycleException { // Configure the list of failed users to delete the oldest entry once it // exceeds the specified size failedUsers = new LinkedHashMap<String, LockRecord>(cacheSize, 0.75f, true) { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry( Map.Entry<String, LockRecord> eldest) { if (size() > cacheSize) { // Check to see if this element has been removed too quickly long timeInCache = (System.currentTimeMillis() - eldest.getValue().getLastFailureTime())/1000; if (timeInCache < cacheRemovalWarningTime) { log.warn(sm.getString("lockOutRealm.removeWarning", eldest.getKey(), Long.valueOf(timeInCache))); } return true; } return false; } }; super.startInternal(); }
// in java/org/apache/catalina/realm/JAASRealm.java
Override protected void startInternal() throws LifecycleException { // These need to be called after loading configuration, in case // useContextClassLoader appears after them in xml config parseClassNames(userClassNames, userClasses); parseClassNames(roleClassNames, roleClasses); super.startInternal(); }
// in java/org/apache/catalina/realm/RealmBase.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); // We want logger as soon as possible if (container != null) { this.containerLog = container.getLogger(); } x509UsernameRetriever = createUsernameRetriever(x509UsernameRetrieverClassName); }
// in java/org/apache/catalina/realm/RealmBase.java
Override protected void startInternal() throws LifecycleException { // Create a MessageDigest instance for credentials, if desired if (digest != null) { try { md = MessageDigest.getInstance(digest); } catch (NoSuchAlgorithmException e) { throw new LifecycleException (sm.getString("realmBase.algorithm", digest), e); } } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/realm/RealmBase.java
Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); // Clean up allocated resources md = null; }
// in java/org/apache/catalina/realm/RealmBase.java
private static X509UsernameRetriever createUsernameRetriever(String className) throws LifecycleException { if(null == className || "".equals(className.trim())) return new X509SubjectDnRetriever(); try { @SuppressWarnings("unchecked") Class<? extends X509UsernameRetriever> clazz = (Class<? extends X509UsernameRetriever>)Class.forName(className); return clazz.newInstance(); } catch (ClassNotFoundException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassNotFoundException", className), e); } catch (InstantiationException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.InstantiationException", className), e); } catch (IllegalAccessException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.IllegalAccessException", className), e); } catch (ClassCastException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e); } }
// in java/org/apache/catalina/realm/JDBCRealm.java
Override protected void startInternal() throws LifecycleException { // Validate that we can open our connection - but let tomcat // startup in case the database is temporarily unavailable try { open(); } catch (SQLException e) { containerLog.error(sm.getString("jdbcRealm.open"), e); } super.startInternal(); }
// in java/org/apache/catalina/realm/JDBCRealm.java
Override protected void stopInternal() throws LifecycleException { super.stopInternal(); // Close any open DB connection close(this.dbConnection); }
// in java/org/apache/catalina/session/StandardManager.java
Override protected synchronized void startInternal() throws LifecycleException { super.startInternal(); // Load unloaded sessions, if any try { load(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardManager.managerLoad"), t); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/session/StandardManager.java
Override protected synchronized void stopInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug("Stopping"); setState(LifecycleState.STOPPING); // Write out sessions try { unload(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardManager.managerUnload"), t); } // Expire all active sessions Session sessions[] = findSessions(); for (int i = 0; i < sessions.length; i++) { Session session = sessions[i]; try { if (session.isValid()) { session.expire(); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } finally { // Measure against memory leaking if references to the session // object are kept in a shared field somewhere session.recycle(); } } // Require a new random number generator if we are restarted super.stopInternal(); }
// in java/org/apache/catalina/session/StoreBase.java
Override protected synchronized void startInternal() throws LifecycleException { setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/session/StoreBase.java
Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); }
// in java/org/apache/catalina/session/ManagerBase.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); setDistributable(((Context) getContainer()).getDistributable()); }
// in java/org/apache/catalina/session/ManagerBase.java
Override protected void startInternal() throws LifecycleException { // Ensure caches for timing stats are the right size by filling with // nulls. while (sessionCreationTiming.size() < TIMING_STATS_CACHE_SIZE) { sessionCreationTiming.add(null); } while (sessionExpirationTiming.size() < TIMING_STATS_CACHE_SIZE) { sessionExpirationTiming.add(null); } sessionIdGenerator = new SessionIdGenerator(); sessionIdGenerator.setJvmRoute(getJvmRoute()); sessionIdGenerator.setSecureRandomAlgorithm(getSecureRandomAlgorithm()); sessionIdGenerator.setSecureRandomClass(getSecureRandomClass()); sessionIdGenerator.setSecureRandomProvider(getSecureRandomProvider()); sessionIdGenerator.setSessionIdLength(getSessionIdLength()); // Force initialization of the random number generator if (log.isDebugEnabled()) log.debug("Force random number initialization starting"); sessionIdGenerator.generateSessionId(); if (log.isDebugEnabled()) log.debug("Force random number initialization completed"); }
// in java/org/apache/catalina/session/ManagerBase.java
Override protected void stopInternal() throws LifecycleException { this.sessionIdGenerator = null; }
// in java/org/apache/catalina/session/JDBCStore.java
Override protected synchronized void startInternal() throws LifecycleException { if (dataSourceName == null) { // If not using a connection pool, open a connection to the database this.dbConnection = getConnection(); } super.startInternal(); }
// in java/org/apache/catalina/session/JDBCStore.java
Override protected synchronized void stopInternal() throws LifecycleException { super.stopInternal(); // Close and release everything associated with our db. if (dbConnection != null) { try { dbConnection.commit(); } catch (SQLException e) { // Ignore } close(dbConnection); } }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override protected synchronized void startInternal() throws LifecycleException { super.startInternal(); if (store == null) log.error("No Store configured, persistence disabled"); else if (store instanceof Lifecycle) ((Lifecycle)store).start(); setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override protected synchronized void stopInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug("Stopping"); setState(LifecycleState.STOPPING); if (getStore() != null && saveOnRestart) { unload(); } else { // Expire all active sessions Session sessions[] = findSessions(); for (int i = 0; i < sessions.length; i++) { StandardSession session = (StandardSession) sessions[i]; if (!session.isValid()) continue; session.expire(); } } if (getStore() != null && getStore() instanceof Lifecycle) ((Lifecycle)getStore()).stop(); // Require a new random number generator if we are restarted super.stopInternal(); }
// in java/org/apache/catalina/valves/RequestFilterValve.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); if (!allowValid || !denyValid) { throw new LifecycleException( sm.getString("requestFilterValve.configInvalid")); } }
// in java/org/apache/catalina/valves/RequestFilterValve.java
Override protected synchronized void startInternal() throws LifecycleException { if (!allowValid || !denyValid) { throw new LifecycleException( sm.getString("requestFilterValve.configInvalid")); } super.startInternal(); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
Override protected synchronized void startInternal() throws LifecycleException { if (container instanceof Context) { container.addLifecycleListener(this); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); if (container instanceof Context) { container.removeLifecycleListener(this); } }
// in java/org/apache/catalina/valves/CrawlerSessionManagerValve.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); uaPattern = Pattern.compile(crawlerUserAgents); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
Override protected synchronized void startInternal() throws LifecycleException { try { open() ; } catch (SQLException e) { throw new LifecycleException(e); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); close() ; }
// in java/org/apache/catalina/valves/StuckThreadDetectionValve.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); if (log.isDebugEnabled()) { log.debug("Monitoring stuck threads with threshold = " + threshold + " sec"); } }
// in java/org/apache/catalina/valves/SemaphoreValve.java
Override protected synchronized void startInternal() throws LifecycleException { semaphore = new Semaphore(concurrency, fairness); setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/valves/SemaphoreValve.java
Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); semaphore = null; }
// in java/org/apache/catalina/valves/AccessLogValve.java
Override protected synchronized void startInternal() throws LifecycleException { // Initialize the Date formatters String format = getFileDateFormat(); if (format == null || format.length() == 0) { format = "yyyy-MM-dd"; setFileDateFormat(format); } fileDateFormatter = new SimpleDateFormat(format, Locale.US); fileDateFormatter.setTimeZone(timezone); dateStamp = fileDateFormatter.format(new Date(System.currentTimeMillis())); open(); setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/valves/AccessLogValve.java
Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); close(); }
// in java/org/apache/catalina/valves/ValveBase.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); containerLog = getContainer().getLogger(); }
// in java/org/apache/catalina/valves/ValveBase.java
Override protected synchronized void startInternal() throws LifecycleException { setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/valves/ValveBase.java
Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
Override protected synchronized void startInternal() throws LifecycleException { // Look up the SingleSignOn implementation in our request processing // path, if there is one Container parent = context.getParent(); while ((sso == null) && (parent != null)) { Valve valves[] = parent.getPipeline().getValves(); for (int i = 0; i < valves.length; i++) { if (valves[i] instanceof SingleSignOn) { sso = (SingleSignOn) valves[i]; break; } } if (sso == null) { parent = parent.getParent(); } } if (log.isDebugEnabled()) { if (sso != null) { log.debug("Found SingleSignOn Valve at " + sso); } else { log.debug("No SingleSignOn Valve is present"); } } sessionIdGenerator = new SessionIdGenerator(); sessionIdGenerator.setSecureRandomAlgorithm(getSecureRandomAlgorithm()); sessionIdGenerator.setSecureRandomClass(getSecureRandomClass()); sessionIdGenerator.setSecureRandomProvider(getSecureRandomProvider()); super.startInternal(); }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
Override protected synchronized void stopInternal() throws LifecycleException { super.stopInternal(); sso = null; }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
Override protected synchronized void startInternal() throws LifecycleException { super.startInternal(); // Generate a random secret key if (getKey() == null) { setKey(sessionIdGenerator.generateSessionId()); } // Generate the opaque string the same way if (getOpaque() == null) { setOpaque(sessionIdGenerator.generateSessionId()); } cnonces = new LinkedHashMap<String, DigestAuthenticator.NonceInfo>() { private static final long serialVersionUID = 1L; private static final long LOG_SUPPRESS_TIME = 5 * 60 * 1000; private long lastLog = 0; @Override protected boolean removeEldestEntry( Map.Entry<String,NonceInfo> eldest) { // This is called from a sync so keep it simple long currentTime = System.currentTimeMillis(); if (size() > getCnonceCacheSize()) { if (lastLog < currentTime && currentTime - eldest.getValue().getTimestamp() < getNonceValidity()) { // Replay attack is possible log.warn(sm.getString( "digestAuthenticator.cacheRemove")); lastLog = currentTime + LOG_SUPPRESS_TIME; } return true; } return false; } }; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); // Kerberos configuration file location String krb5Conf = System.getProperty(Constants.KRB5_CONF_PROPERTY); if (krb5Conf == null) { // System property not set, use the Tomcat default File krb5ConfFile = new File(container.getCatalinaBase(), Constants.DEFAULT_KRB5_CONF); System.setProperty(Constants.KRB5_CONF_PROPERTY, krb5ConfFile.getAbsolutePath()); } // JAAS configuration file location String jaasConf = System.getProperty(Constants.JAAS_CONF_PROPERTY); if (jaasConf == null) { // System property not set, use the Tomcat default File jaasConfFile = new File(container.getCatalinaBase(), Constants.DEFAULT_JAAS_CONF); System.setProperty(Constants.JAAS_CONF_PROPERTY, jaasConfFile.getAbsolutePath()); } // This property must be false for SPNEGO to work System.setProperty(Constants.USE_SUBJECT_CREDS_ONLY_PROPERTY, "false"); }
// in java/org/apache/catalina/deploy/NamingResources.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); // Set this before we register currently known naming resources to avoid // timing issues. Duplication registration is not an issue. resourceRequireExplicitRegistration = true; for (ContextResource cr : resources.values()) { try { MBeanUtils.createMBean(cr); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", cr.getName()), e); } } for (ContextEnvironment ce : envs.values()) { try { MBeanUtils.createMBean(ce); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", ce.getName()), e); } } for (ContextResourceLink crl : resourceLinks.values()) { try { MBeanUtils.createMBean(crl); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", crl.getName()), e); } } }
// in java/org/apache/catalina/deploy/NamingResources.java
Override protected void startInternal() throws LifecycleException { fireLifecycleEvent(CONFIGURE_START_EVENT, null); setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/deploy/NamingResources.java
Override protected void stopInternal() throws LifecycleException { cleanUp(); setState(LifecycleState.STOPPING); fireLifecycleEvent(CONFIGURE_STOP_EVENT, null); }
// in java/org/apache/catalina/deploy/NamingResources.java
Override protected void destroyInternal() throws LifecycleException { // Set this before we de-register currently known naming resources to // avoid timing issues. Duplication de-registration is not an issue. resourceRequireExplicitRegistration = false; // Destroy in reverse order to create, although it should not matter for (ContextResourceLink crl : resourceLinks.values()) { try { MBeanUtils.destroyMBean(crl); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", crl.getName()), e); } } for (ContextEnvironment ce : envs.values()) { try { MBeanUtils.destroyMBean(ce); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", ce.getName()), e); } } for (ContextResource cr : resources.values()) { try { MBeanUtils.destroyMBean(cr); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", cr.getName()), e); } } super.destroyInternal(); }
// in java/org/apache/catalina/ha/context/ReplicatedContext.java
Override protected synchronized void startInternal() throws LifecycleException { try { CatalinaCluster catclust = (CatalinaCluster)this.getCluster(); if (this.context == null) this.context = new ReplApplContext(this); if ( catclust != null ) { ReplicatedMap<String,Object> map = new ReplicatedMap<String,Object>(this, catclust.getChannel(),DEFAULT_REPL_TIMEOUT, getName(),getClassLoaders()); map.setChannelSendOptions(mapSendOptions); ((ReplApplContext)this.context).setAttributeMap(map); if (getAltDDName() != null) context.setAttribute(Globals.ALT_DD_ATTR, getAltDDName()); } super.startInternal(); } catch ( Exception x ) { log.error("Unable to start ReplicatedContext",x); throw new LifecycleException("Failed to start ReplicatedContext",x); } }
// in java/org/apache/catalina/ha/context/ReplicatedContext.java
Override protected synchronized void stopInternal() throws LifecycleException { super.stopInternal(); Map<String,Object> map = ((ReplApplContext)this.context).getAttributeMap(); if ( map!=null && map instanceof ReplicatedMap) { ((ReplicatedMap<?,?>)map).breakdown(); } }
// in java/org/apache/catalina/ha/session/JvmRouteBinderValve.java
Override protected synchronized void startInternal() throws LifecycleException { if (cluster == null) { Container hostContainer = getContainer(); // compatibility with JvmRouteBinderValve version 1.1 // ( setup at context.xml or context.xml.default ) if (!(hostContainer instanceof Host)) { if (log.isWarnEnabled()) { log.warn(sm.getString("jvmRoute.configure.warn")); } hostContainer = hostContainer.getParent(); } if (hostContainer instanceof Host && ((Host) hostContainer).getCluster() != null) { cluster = (CatalinaCluster) ((Host) hostContainer).getCluster(); } else { Container engine = hostContainer.getParent() ; if (engine instanceof Engine && ((Engine) engine).getCluster() != null) { cluster = (CatalinaCluster) ((Engine) engine).getCluster(); } } } if (log.isInfoEnabled()) { log.info(sm.getString("jvmRoute.valve.started")); if (cluster == null) { log.info(sm.getString("jvmRoute.noCluster")); } } super.startInternal(); }
// in java/org/apache/catalina/ha/session/JvmRouteBinderValve.java
Override protected synchronized void stopInternal() throws LifecycleException { super.stopInternal(); cluster = null; numberOfSessions = 0; if (log.isInfoEnabled()) { log.info(sm.getString("jvmRoute.valve.stopped")); } }
// in java/org/apache/catalina/ha/session/BackupManager.java
Override protected synchronized void startInternal() throws LifecycleException { super.startInternal(); try { if (getCluster() == null) { Cluster cluster = getContainer().getCluster(); if (cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster)cluster); } else { throw new LifecycleException( sm.getString("backupManager.noCluster", getName())); } } cluster.registerManager(this); LazyReplicatedMap<String,Session> map = new LazyReplicatedMap<String,Session>(this, cluster.getChannel(), rpcTimeout, getMapName(), getClassLoaders()); map.setChannelSendOptions(mapSendOptions); this.sessions = map; } catch ( Exception x ) { log.error(sm.getString("backupManager.startUnable", getName()),x); throw new LifecycleException(sm.getString("backupManager.startFailed", getName()),x); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/ha/session/BackupManager.java
Override protected synchronized void stopInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug(sm.getString("backupManager.stopped", getName())); setState(LifecycleState.STOPPING); if (sessions instanceof LazyReplicatedMap) { LazyReplicatedMap<String,Session> map = (LazyReplicatedMap<String,Session>)sessions; map.breakdown(); } cluster.removeManager(this); super.stopInternal(); }
// in java/org/apache/catalina/ha/session/JvmRouteSessionIDBinderListener.java
public void start() throws LifecycleException { if (started) return; getCluster().addClusterListener(this); started = true; if (log.isInfoEnabled()) log.info(sm.getString("jvmRoute.clusterListener.started")); }
// in java/org/apache/catalina/ha/session/JvmRouteSessionIDBinderListener.java
public void stop() throws LifecycleException { started = false; getCluster().removeClusterListener(this); if (log.isInfoEnabled()) log.info(sm.getString("jvmRoute.clusterListener.stopped")); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
Override protected synchronized void startInternal() throws LifecycleException { super.startInternal(); // Load unloaded sessions, if any try { //the channel is already running Cluster cluster = getCluster() ; // stop remove cluster binding //wow, how many nested levels of if statements can we have ;) if(cluster == null) { Container context = getContainer() ; if(context != null && context instanceof Context) { Container host = context.getParent() ; if(host != null && host instanceof Host) { cluster = host.getCluster(); if(cluster != null && cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster) cluster) ; } else { Container engine = host.getParent() ; if(engine != null && engine instanceof Engine) { cluster = engine.getCluster(); if(cluster != null && cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster) cluster) ; } } else { cluster = null ; } } } } } if (cluster == null) { log.error(sm.getString("deltaManager.noCluster", getName())); return; } else { if (log.isInfoEnabled()) { String type = "unknown" ; if( cluster.getContainer() instanceof Host){ type = "Host" ; } else if( cluster.getContainer() instanceof Engine){ type = "Engine" ; } log.info(sm.getString("deltaManager.registerCluster", getName(), type, cluster.getClusterName())); } } if (log.isInfoEnabled()) log.info(sm.getString("deltaManager.startClustering", getName())); //to survice context reloads, as only a stop/start is called, not // createManager cluster.registerManager(this); getAllClusterSessions(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("deltaManager.managerLoad"), t); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
Override protected synchronized void stopInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.stopped", getName())); setState(LifecycleState.STOPPING); // Expire all active sessions if (log.isInfoEnabled()) log.info(sm.getString("deltaManager.expireSessions", getName())); Session sessions[] = findSessions(); for (int i = 0; i < sessions.length; i++) { DeltaSession session = (DeltaSession) sessions[i]; if (!session.isValid()) continue; try { session.expire(true, isExpireSessionsOnShutdown()); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } // Require a new random number generator if we are restarted getCluster().removeManager(this); super.stopInternal(); replicationValve = null; }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOn.java
Override protected synchronized void startInternal() throws LifecycleException { clusterSSOListener = new ClusterSingleSignOnListener(); clusterSSOListener.setClusterSSO(this); // Load the cluster component, if any try { //the channel is already running Cluster cluster = getCluster(); // stop remove cluster binding if(cluster == null) { Container host = getContainer(); if(host != null && host instanceof Host) { cluster = host.getCluster(); if(cluster != null && cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster) cluster); getCluster().addClusterListener(clusterSSOListener); } else { Container engine = host.getParent(); if(engine != null && engine instanceof Engine) { cluster = engine.getCluster(); if(cluster != null && cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster) cluster); getCluster().addClusterListener(clusterSSOListener); } } else { cluster = null; } } } } if (cluster == null) { throw new LifecycleException( "There is no Cluster for ClusterSingleSignOn"); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new LifecycleException( "ClusterSingleSignOn exception during clusterLoad " + t); } super.startInternal(); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOn.java
Override protected synchronized void stopInternal() throws LifecycleException { super.stopInternal(); if (getCluster() != null) { getCluster().removeClusterListener(clusterSSOListener); } }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
Override public void stop() throws LifecycleException { started = false; getCluster().removeClusterListener(this); count = 0; if (watcher != null) { watcher.clear(); watcher = null; } if (log.isInfoEnabled()) log.info(sm.getString("farmWarDeployer.stopped")); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
Override protected void startInternal() throws LifecycleException { if (log.isInfoEnabled()) log.info("Cluster is about to start"); try { checkDefaults(); registerClusterValve(); channel.addMembershipListener(this); channel.addChannelListener(this); channel.start(channelStartOptions); if (clusterDeployer != null) clusterDeployer.start(); //register JMX objects ClusterJmxHelper.registerDefaultCluster(this); // Notify our interested LifecycleListeners } catch (Exception x) { log.error("Unable to start cluster.", x); throw new LifecycleException(x); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); if (clusterDeployer != null) clusterDeployer.stop(); this.managers.clear(); try { if ( clusterDeployer != null ) clusterDeployer.setCluster(null); channel.stop(channelStartOptions); channel.removeChannelListener(this); channel.removeMembershipListener(this); this.unregisterClusterValve(); //unregister JMX objects ClusterJmxHelper.unregisterDefaultCluster(this); } catch (Exception x) { log.error("Unable to stop cluster valve.", x); } }
// in java/org/apache/catalina/connector/Connector.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); // Initialize adapter adapter = new CoyoteAdapter(this); protocolHandler.setAdapter(adapter); // Make sure parseBodyMethodsSet has a default if( null == parseBodyMethodsSet ) { setParseBodyMethods(getParseBodyMethods()); } try { protocolHandler.init(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerInitializationFailed"), e); } // Initialize mapper listener mapperListener.init(); }
// in java/org/apache/catalina/connector/Connector.java
Override protected void startInternal() throws LifecycleException { // Validate settings before starting if (getPort() < 0) { throw new LifecycleException(sm.getString( "coyoteConnector.invalidPort", Integer.valueOf(getPort()))); } setState(LifecycleState.STARTING); try { protocolHandler.start(); } catch (Exception e) { String errPrefix = ""; if(this.service != null) { errPrefix += "service.getName(): \"" + this.service.getName() + "\"; "; } throw new LifecycleException (errPrefix + " " + sm.getString ("coyoteConnector.protocolHandlerStartFailed"), e); } mapperListener.start(); }
// in java/org/apache/catalina/connector/Connector.java
Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); try { protocolHandler.stop(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerStopFailed"), e); } mapperListener.stop(); }
// in java/org/apache/catalina/connector/Connector.java
Override protected void destroyInternal() throws LifecycleException { mapperListener.destroy(); try { protocolHandler.destroy(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerDestroyFailed"), e); } if (getService() != null) { getService().removeConnector(this); } super.destroyInternal(); }
// in java/org/apache/catalina/connector/MapperListener.java
Override public void startInternal() throws LifecycleException { setState(LifecycleState.STARTING); // Find any components that have already been initialized since the // MBean listener won't be notified as those components will have // already registered their MBeans findDefaultHost(); Engine engine = (Engine) connector.getService().getContainer(); addListeners(engine); Container[] conHosts = engine.findChildren(); for (Container conHost : conHosts) { Host host = (Host) conHost; if (!LifecycleState.NEW.equals(host.getState())) { // Registering the host will register the context and wrappers registerHost(host); } } }
// in java/org/apache/catalina/connector/MapperListener.java
Override public void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
Override protected void initInternal() throws LifecycleException { // NOOP - Don't register this Valve in JMX }
// in java/org/apache/catalina/core/StandardHost.java
Override protected synchronized void startInternal() throws LifecycleException { // Set error report valve String errorValve = getErrorReportValveClass(); if ((errorValve != null) && (!errorValve.equals(""))) { try { boolean found = false; Valve[] valves = getPipeline().getValves(); for (Valve valve : valves) { if (errorValve.equals(valve.getClass().getName())) { found = true; break; } } if(!found) { Valve valve = (Valve) Class.forName(errorValve).newInstance(); getPipeline().addValve(valve); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString( "standardHost.invalidErrorReportValveClass", errorValve), t); } } super.startInternal(); }
// in java/org/apache/catalina/core/ContainerBase.java
Override protected void initInternal() throws LifecycleException { BlockingQueue<Runnable> startStopQueue = new LinkedBlockingQueue<Runnable>(); startStopExecutor = new ThreadPoolExecutor( getStartStopThreadsInternal(), getStartStopThreadsInternal(), 10, TimeUnit.SECONDS, startStopQueue); startStopExecutor.allowCoreThreadTimeOut(true); super.initInternal(); }
// in java/org/apache/catalina/core/ContainerBase.java
Override protected synchronized void startInternal() throws LifecycleException { // Start our subordinate components, if any if ((loader != null) && (loader instanceof Lifecycle)) ((Lifecycle) loader).start(); logger = null; getLogger(); if ((manager != null) && (manager instanceof Lifecycle)) ((Lifecycle) manager).start(); if ((cluster != null) && (cluster instanceof Lifecycle)) ((Lifecycle) cluster).start(); Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) ((Lifecycle) realm).start(); if ((resources != null) && (resources instanceof Lifecycle)) ((Lifecycle) resources).start(); // Start our child containers, if any Container children[] = findChildren(); List<Future<Void>> results = new ArrayList<Future<Void>>(); for (int i = 0; i < children.length; i++) { results.add(startStopExecutor.submit(new StartChild(children[i]))); } boolean fail = false; for (Future<Void> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString("containerBase.threadedStartFailed"), e); fail = true; } } if (fail) { throw new LifecycleException( sm.getString("containerBase.threadedStartFailed")); } // Start the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle) ((Lifecycle) pipeline).start(); setState(LifecycleState.STARTING); // Start our thread threadStart(); }
// in java/org/apache/catalina/core/ContainerBase.java
Override protected synchronized void stopInternal() throws LifecycleException { // Stop our thread threadStop(); setState(LifecycleState.STOPPING); // Stop the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle && ((Lifecycle) pipeline).getState().isAvailable()) { ((Lifecycle) pipeline).stop(); } // Stop our child containers, if any Container children[] = findChildren(); List<Future<Void>> results = new ArrayList<Future<Void>>(); for (int i = 0; i < children.length; i++) { results.add(startStopExecutor.submit(new StopChild(children[i]))); } boolean fail = false; for (Future<Void> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString("containerBase.threadedStopFailed"), e); fail = true; } } if (fail) { throw new LifecycleException( sm.getString("containerBase.threadedStopFailed")); } // Stop our subordinate components, if any if ((resources != null) && (resources instanceof Lifecycle)) { ((Lifecycle) resources).stop(); } Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) { ((Lifecycle) realm).stop(); } if ((cluster != null) && (cluster instanceof Lifecycle)) { ((Lifecycle) cluster).stop(); } if ((manager != null) && (manager instanceof Lifecycle) && ((Lifecycle) manager).getState().isAvailable() ) { ((Lifecycle) manager).stop(); } if ((loader != null) && (loader instanceof Lifecycle)) { ((Lifecycle) loader).stop(); } }
// in java/org/apache/catalina/core/ContainerBase.java
Override protected void destroyInternal() throws LifecycleException { if ((manager != null) && (manager instanceof Lifecycle)) { ((Lifecycle) manager).destroy(); } Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) { ((Lifecycle) realm).destroy(); } if ((cluster != null) && (cluster instanceof Lifecycle)) { ((Lifecycle) cluster).destroy(); } if ((loader != null) && (loader instanceof Lifecycle)) { ((Lifecycle) loader).destroy(); } // Stop the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle) { ((Lifecycle) pipeline).destroy(); } // Remove children now this container is being destroyed for (Container child : findChildren()) { removeChild(child); } // Required if the child is destroyed directly. if (parent != null) { parent.removeChild(this); } // If init fails, this may be null if (startStopExecutor != null) { startStopExecutor.shutdownNow(); } super.destroyInternal(); }
// in java/org/apache/catalina/core/ContainerBase.java
Override public Void call() throws LifecycleException { child.start(); return null; }
// in java/org/apache/catalina/core/ContainerBase.java
Override public Void call() throws LifecycleException { if (child.getState().isAvailable()) { child.stop(); } return null; }
// in java/org/apache/catalina/core/StandardServer.java
Override protected void startInternal() throws LifecycleException { fireLifecycleEvent(CONFIGURE_START_EVENT, null); setState(LifecycleState.STARTING); globalNamingResources.start(); // Start our defined Services synchronized (services) { for (int i = 0; i < services.length; i++) { services[i].start(); } } }
// in java/org/apache/catalina/core/StandardServer.java
Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); fireLifecycleEvent(CONFIGURE_STOP_EVENT, null); // Stop our defined Services for (int i = 0; i < services.length; i++) { services[i].stop(); } globalNamingResources.stop(); stopAwait(); }
// in java/org/apache/catalina/core/StandardServer.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); // Register global String cache // Note although the cache is global, if there are multiple Servers // present in the JVM (may happen when embedding) then the same cache // will be registered under multiple names onameStringCache = register(new StringCache(), "type=StringCache"); // Register the MBeanFactory MBeanFactory factory = new MBeanFactory(); factory.setContainer(this); onameMBeanFactory = register(factory, "type=MBeanFactory"); // Register the naming resources globalNamingResources.init(); // Populate the extension validator with JARs from common and shared // class loaders if (getCatalina() != null) { ClassLoader cl = getCatalina().getParentClassLoader(); // Walk the class loader hierarchy. Stop at the system class loader. // This will add the shared (if present) and common class loaders while (cl != null && cl != ClassLoader.getSystemClassLoader()) { if (cl instanceof URLClassLoader) { URL[] urls = ((URLClassLoader) cl).getURLs(); for (URL url : urls) { if (url.getProtocol().equals("file")) { try { File f = new File (url.toURI()); if (f.isFile() && f.getName().endsWith(".jar")) { ExtensionValidator.addSystemResource(f); } } catch (URISyntaxException e) { // Ignore } catch (IOException e) { // Ignore } } } } cl = cl.getParent(); } } // Initialize our defined Services for (int i = 0; i < services.length; i++) { services[i].init(); } }
// in java/org/apache/catalina/core/StandardServer.java
Override protected void destroyInternal() throws LifecycleException { // Destroy our defined Services for (int i = 0; i < services.length; i++) { services[i].destroy(); } globalNamingResources.destroy(); unregister(onameMBeanFactory); unregister(onameStringCache); super.destroyInternal(); }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
Override protected void startInternal() throws LifecycleException { taskqueue = new TaskQueue(maxQueueSize); TaskThreadFactory tf = new TaskThreadFactory(namePrefix,daemon,getThreadPriority()); executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), maxIdleTime, TimeUnit.MILLISECONDS,taskqueue, tf); if (prestartminSpareThreads) { executor.prestartAllCoreThreads(); } taskqueue.setParent(executor); setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); if ( executor != null ) executor.shutdownNow(); executor = null; taskqueue = null; }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
Override protected void destroyInternal() throws LifecycleException { super.destroyInternal(); }
// in java/org/apache/catalina/core/StandardService.java
Override protected void startInternal() throws LifecycleException { if(log.isInfoEnabled()) log.info(sm.getString("standardService.start.name", this.name)); setState(LifecycleState.STARTING); // Start our defined Container first if (container != null) { synchronized (container) { container.start(); } } synchronized (executors) { for (Executor executor: executors) { executor.start(); } } // Start our defined Connectors second synchronized (connectors) { for (Connector connector: connectors) { try { // If it has already failed, don't try and start it if (connector.getState() != LifecycleState.FAILED) { connector.start(); } } catch (Exception e) { log.error(sm.getString( "standardService.connector.startFailed", connector), e); } } } }
// in java/org/apache/catalina/core/StandardService.java
Override protected void stopInternal() throws LifecycleException { // Pause connectors first synchronized (connectors) { for (Connector connector: connectors) { try { connector.pause(); } catch (Exception e) { log.error(sm.getString( "standardService.connector.pauseFailed", connector), e); } } } if(log.isInfoEnabled()) log.info(sm.getString("standardService.stop.name", this.name)); setState(LifecycleState.STOPPING); // Stop our defined Container second if (container != null) { synchronized (container) { container.stop(); } } // Now stop the connectors synchronized (connectors) { for (Connector connector: connectors) { if (!LifecycleState.STARTED.equals( connector.getState())) { // Connectors only need stopping if they are currently // started. They may have failed to start or may have been // stopped (e.g. via a JMX call) continue; } try { connector.stop(); } catch (Exception e) { log.error(sm.getString( "standardService.connector.stopFailed", connector), e); } } } synchronized (executors) { for (Executor executor: executors) { executor.stop(); } } }
// in java/org/apache/catalina/core/StandardService.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); if (container != null) { container.init(); } // Initialize any Executors for (Executor executor : findExecutors()) { if (executor instanceof JmxEnabled) { ((JmxEnabled) executor).setDomain(getDomain()); } executor.init(); } // Initialize our defined Connectors synchronized (connectors) { for (Connector connector : connectors) { try { connector.init(); } catch (Exception e) { String message = sm.getString( "standardService.connector.initFailed", connector); log.error(message, e); if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) throw new LifecycleException(message); } } } }
// in java/org/apache/catalina/core/StandardService.java
Override protected void destroyInternal() throws LifecycleException { // Destroy our defined Connectors synchronized (connectors) { for (Connector connector : connectors) { try { connector.destroy(); } catch (Exception e) { log.error(sm.getString( "standardService.connector.destroyfailed", connector), e); } } } // Destroy any Executors for (Executor executor : findExecutors()) { executor.destroy(); } if (container != null) { container.destroy(); } super.destroyInternal(); }
// in java/org/apache/catalina/core/StandardContext.java
Override protected synchronized void startInternal() throws LifecycleException { if(log.isDebugEnabled()) log.debug("Starting " + getBaseName()); // Send j2ee.state.starting notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.starting", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } setConfigured(false); boolean ok = true; // Currently this is effectively a NO-OP but needs to be called to // ensure the NamingResources follows the correct lifecycle if (namingResources != null) { namingResources.start(); } // Add missing components as necessary if (webappResources == null) { // (1) Required by Loader if (log.isDebugEnabled()) log.debug("Configuring default Resources"); try { if ((getDocBase() != null) && (getDocBase().endsWith(".war")) && (!(new File(getBasePath())).isDirectory())) setResources(new WARDirContext()); else setResources(new FileDirContext()); } catch (IllegalArgumentException e) { log.error("Error initializing resources: " + e.getMessage()); ok = false; } } if (ok) { if (!resourcesStart()) { log.error( "Error in resourceStart()"); ok = false; } } if (getLoader() == null) { WebappLoader webappLoader = new WebappLoader(getParentClassLoader()); webappLoader.setDelegate(getDelegate()); setLoader(webappLoader); } // Initialize character set mapper getCharsetMapper(); // Post work directory postWorkDirectory(); // Validate required extensions boolean dependencyCheck = true; try { dependencyCheck = ExtensionValidator.validateApplication (getResources(), this); } catch (IOException ioe) { log.error("Error in dependencyCheck", ioe); dependencyCheck = false; } if (!dependencyCheck) { // do not make application available if depency check fails ok = false; } // Reading the "catalina.useNaming" environment variable String useNamingProperty = System.getProperty("catalina.useNaming"); if ((useNamingProperty != null) && (useNamingProperty.equals("false"))) { useNaming = false; } if (ok && isUseNaming()) { if (getNamingContextListener() == null) { NamingContextListener ncl = new NamingContextListener(); ncl.setName(getNamingContextName()); ncl.setExceptionOnFailedWrite(getJndiExceptionOnFailedWrite()); addLifecycleListener(ncl); setNamingContextListener(ncl); } } // Standard container startup if (log.isDebugEnabled()) log.debug("Processing standard container startup"); // Binding thread ClassLoader oldCCL = bindThread(); try { if (ok) { // Start our subordinate components, if any if ((loader != null) && (loader instanceof Lifecycle)) ((Lifecycle) loader).start(); // since the loader just started, the webapp classloader is now // created. setClassLoaderProperty("antiJARLocking", getAntiJARLocking()); setClassLoaderProperty("clearReferencesStatic", getClearReferencesStatic()); setClassLoaderProperty("clearReferencesStopThreads", getClearReferencesStopThreads()); setClassLoaderProperty("clearReferencesStopTimerThreads", getClearReferencesStopTimerThreads()); setClassLoaderProperty("clearReferencesHttpClientKeepAliveThread", getClearReferencesHttpClientKeepAliveThread()); // By calling unbindThread and bindThread in a row, we setup the // current Thread CCL to be the webapp classloader unbindThread(oldCCL); oldCCL = bindThread(); // Initialize logger again. Other components might have used it // too early, so it should be reset. logger = null; getLogger(); if ((cluster != null) && (cluster instanceof Lifecycle)) ((Lifecycle) cluster).start(); Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) ((Lifecycle) realm).start(); if ((resources != null) && (resources instanceof Lifecycle)) ((Lifecycle) resources).start(); // Notify our interested LifecycleListeners fireLifecycleEvent(Lifecycle.CONFIGURE_START_EVENT, null); // Start our child containers, if not already started for (Container child : findChildren()) { if (!child.getState().isAvailable()) { child.start(); } } // Start the Valves in our pipeline (including the basic), // if any if (pipeline instanceof Lifecycle) { ((Lifecycle) pipeline).start(); } // Acquire clustered manager Manager contextManager = null; if (manager == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("standardContext.cluster.noManager", Boolean.valueOf((getCluster() != null)), Boolean.valueOf(distributable))); } if ( (getCluster() != null) && distributable) { try { contextManager = getCluster().createManager(getName()); } catch (Exception ex) { log.error("standardContext.clusterFail", ex); ok = false; } } else { contextManager = new StandardManager(); } } // Configure default manager if none was specified if (contextManager != null) { if (log.isDebugEnabled()) { log.debug(sm.getString("standardContext.manager", contextManager.getClass().getName())); } setManager(contextManager); } if (manager!=null && (getCluster() != null) && distributable) { //let the cluster know that there is a context that is distributable //and that it has its own manager getCluster().registerManager(manager); } } } finally { // Unbinding thread unbindThread(oldCCL); } if (!getConfigured()) { log.error( "Error getConfigured"); ok = false; } // We put the resources into the servlet context if (ok) getServletContext().setAttribute (Globals.RESOURCES_ATTR, getResources()); // Initialize associated mapper mapper.setContext(getPath(), welcomeFiles, resources); // Binding thread oldCCL = bindThread(); if (ok ) { if (getInstanceManager() == null) { javax.naming.Context context = null; if (isUseNaming() && getNamingContextListener() != null) { context = getNamingContextListener().getEnvContext(); } Map<String, Map<String, String>> injectionMap = buildInjectionMap( getIgnoreAnnotations() ? new NamingResources(): getNamingResources()); setInstanceManager(new DefaultInstanceManager(context, injectionMap, this, this.getClass().getClassLoader())); getServletContext().setAttribute( InstanceManager.class.getName(), getInstanceManager()); } } try { // Create context attributes that will be required if (ok) { getServletContext().setAttribute( JarScanner.class.getName(), getJarScanner()); } // Set up the context init params mergeParameters(); // Call ServletContainerInitializers for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializers.entrySet()) { try { entry.getKey().onStartup(entry.getValue(), getServletContext()); } catch (ServletException e) { // TODO: Log error ok = false; break; } } // Configure and call application event listeners if (ok) { if (!listenerStart()) { log.error( "Error listenerStart"); ok = false; } } try { // Start manager if ((manager != null) && (manager instanceof Lifecycle)) { ((Lifecycle) getManager()).start(); } // Start ContainerBackgroundProcessor thread super.threadStart(); } catch(Exception e) { log.error("Error manager.start()", e); ok = false; } // Configure and call application filters if (ok) { if (!filterStart()) { log.error("Error filterStart"); ok = false; } } // Load and initialize all "load on startup" servlets if (ok) { loadOnStartup(findChildren()); } } finally { // Unbinding thread unbindThread(oldCCL); } // Set available status depending upon startup success if (ok) { if (log.isDebugEnabled()) log.debug("Starting completed"); } else { log.error(sm.getString("standardContext.startFailed", getName())); } startTime=System.currentTimeMillis(); // Send j2ee.state.running notification if (ok && (this.getObjectName() != null)) { Notification notification = new Notification("j2ee.state.running", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } // Close all JARs right away to avoid always opening a peak number // of files on startup if (getLoader() instanceof WebappLoader) { ((WebappLoader) getLoader()).closeJARs(true); } // Reinitializing if something went wrong if (!ok) { setState(LifecycleState.FAILED); } else { setState(LifecycleState.STARTING); } }
// in java/org/apache/catalina/core/StandardContext.java
Override protected synchronized void stopInternal() throws LifecycleException { // Send j2ee.state.stopping notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.stopping", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } setState(LifecycleState.STOPPING); // Binding thread ClassLoader oldCCL = bindThread(); try { // Stop our child containers, if any final Container[] children = findChildren(); ClassLoader old = bindThread(); try { for (int i = 0; i < children.length; i++) { children[i].stop(); } // Stop our filters filterStop(); // Stop ContainerBackgroundProcessor thread threadStop(); if (manager != null && manager instanceof Lifecycle && ((Lifecycle) manager).getState().isAvailable()) { ((Lifecycle) manager).stop(); } // Stop our application listeners listenerStop(); } finally{ unbindThread(old); } // Finalize our character set mapper setCharsetMapper(null); // Normal container shutdown processing if (log.isDebugEnabled()) log.debug("Processing standard container shutdown"); // JNDI resources are unbound in CONFIGURE_STOP_EVENT so stop // naming resoucres before they are unbound since NamingResoucres // does a JNDI lookup to retrieve the resource. This needs to be // after the application has finished with the resource if (namingResources != null) { namingResources.stop(); } fireLifecycleEvent(Lifecycle.CONFIGURE_STOP_EVENT, null); // Stop the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle && ((Lifecycle) pipeline).getState().isAvailable()) { ((Lifecycle) pipeline).stop(); } // Clear all application-originated servlet context attributes if (context != null) context.clearAttributes(); // Stop resources resourcesStop(); Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) { ((Lifecycle) realm).stop(); } if ((cluster != null) && (cluster instanceof Lifecycle)) { ((Lifecycle) cluster).stop(); } if ((loader != null) && (loader instanceof Lifecycle)) { ((Lifecycle) loader).stop(); } } finally { // Unbinding thread unbindThread(oldCCL); } // Send j2ee.state.stopped notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.stopped", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } // Reset application context context = null; // This object will no longer be visible or used. try { resetContext(); } catch( Exception ex ) { log.error( "Error reseting context " + this + " " + ex, ex ); } //reset the instance manager instanceManager = null; if (log.isDebugEnabled()) log.debug("Stopping complete"); }
// in java/org/apache/catalina/core/StandardContext.java
Override protected void destroyInternal() throws LifecycleException { // If in state NEW when destroy is called, the object name will never // have been set so the notification can't be created if (getObjectName() != null) { // Send j2ee.object.deleted notification Notification notification = new Notification("j2ee.object.deleted", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } if (namingResources != null) { namingResources.destroy(); } synchronized (instanceListenersLock) { instanceListeners = new String[0]; } super.destroyInternal(); }
// in java/org/apache/catalina/core/StandardContext.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); if (processTlds) { this.addLifecycleListener(new TldConfig()); } // Register the naming resources if (namingResources != null) { namingResources.init(); } // Send j2ee.object.created notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.object.created", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } }
// in java/org/apache/catalina/core/StandardPipeline.java
Override protected synchronized void startInternal() throws LifecycleException { // Start the Valves in our pipeline (including the basic), if any Valve current = first; if (current == null) { current = basic; } while (current != null) { if (current instanceof Lifecycle) ((Lifecycle) current).start(); current = current.getNext(); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/core/StandardPipeline.java
Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); // Stop the Valves in our pipeline (including the basic), if any Valve current = first; if (current == null) { current = basic; } while (current != null) { if (current instanceof Lifecycle) ((Lifecycle) current).stop(); current = current.getNext(); } }
// in java/org/apache/catalina/core/StandardWrapper.java
Override protected synchronized void startInternal() throws LifecycleException { // Send j2ee.state.starting notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.starting", this.getObjectName(), sequenceNumber++); broadcaster.sendNotification(notification); } // Start up this component super.startInternal(); setAvailable(0L); // Send j2ee.state.running notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.running", this.getObjectName(), sequenceNumber++); broadcaster.sendNotification(notification); } }
// in java/org/apache/catalina/core/StandardWrapper.java
Override protected synchronized void stopInternal() throws LifecycleException { setAvailable(Long.MAX_VALUE); // Send j2ee.state.stopping notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.stopping", this.getObjectName(), sequenceNumber++); broadcaster.sendNotification(notification); } // Shut down our servlet instance (if it has been initialized) try { unload(); } catch (ServletException e) { getServletContext().log(sm.getString ("standardWrapper.unloadException", getName()), e); } // Shut down this component super.stopInternal(); // Send j2ee.state.stoppped notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.stopped", this.getObjectName(), sequenceNumber++); broadcaster.sendNotification(notification); } // Send j2ee.object.deleted notification Notification notification = new Notification("j2ee.object.deleted", this.getObjectName(), sequenceNumber++); broadcaster.sendNotification(notification); }
// in java/org/apache/catalina/core/StandardEngine.java
Override protected void initInternal() throws LifecycleException { // Ensure that a Realm is present before any attempt is made to start // one. This will create the default NullRealm if necessary. getRealm(); super.initInternal(); }
// in java/org/apache/catalina/core/StandardEngine.java
Override protected synchronized void startInternal() throws LifecycleException { // Log our server identification information if(log.isInfoEnabled()) log.info( "Starting Servlet Engine: " + ServerInfo.getServerInfo()); // Standard container startup super.startInternal(); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
Override protected void initInternal() throws LifecycleException { // If oname is not null then registration has already happened via // preRegister(). if (oname == null) { mserver = Registry.getRegistry(null, null).getMBeanServer(); oname = register(this, getObjectNameKeyProperties()); } }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
Override protected void destroyInternal() throws LifecycleException { unregister(oname); }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void init() throws LifecycleException { if (!state.equals(LifecycleState.NEW)) { invalidTransition(Lifecycle.BEFORE_INIT_EVENT); } setStateInternal(LifecycleState.INITIALIZING, null, false); try { initInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); } setStateInternal(LifecycleState.INITIALIZED, null, false); }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void start() throws LifecycleException { if (LifecycleState.STARTING_PREP.equals(state) || LifecycleState.STARTING.equals(state) || LifecycleState.STARTED.equals(state)) { if (log.isDebugEnabled()) { Exception e = new LifecycleException(); log.debug(sm.getString("lifecycleBase.alreadyStarted", toString()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("lifecycleBase.alreadyStarted", toString())); } return; } if (state.equals(LifecycleState.NEW)) { init(); } else if (state.equals(LifecycleState.FAILED)){ stop(); } else if (!state.equals(LifecycleState.INITIALIZED) && !state.equals(LifecycleState.STOPPED)) { invalidTransition(Lifecycle.BEFORE_START_EVENT); } setStateInternal(LifecycleState.STARTING_PREP, null, false); try { startInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.startFail",toString()), t); } if (state.equals(LifecycleState.FAILED) || state.equals(LifecycleState.MUST_STOP)) { stop(); } else { // Shouldn't be necessary but acts as a check that sub-classes are // doing what they are supposed to. if (!state.equals(LifecycleState.STARTING)) { invalidTransition(Lifecycle.AFTER_START_EVENT); } setStateInternal(LifecycleState.STARTED, null, false); } }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void stop() throws LifecycleException { if (LifecycleState.STOPPING_PREP.equals(state) || LifecycleState.STOPPING.equals(state) || LifecycleState.STOPPED.equals(state)) { if (log.isDebugEnabled()) { Exception e = new LifecycleException(); log.debug(sm.getString("lifecycleBase.alreadyStopped", toString()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("lifecycleBase.alreadyStopped", toString())); } return; } if (state.equals(LifecycleState.NEW)) { state = LifecycleState.STOPPED; return; } if (!state.equals(LifecycleState.STARTED) && !state.equals(LifecycleState.FAILED) && !state.equals(LifecycleState.MUST_STOP)) { invalidTransition(Lifecycle.BEFORE_STOP_EVENT); } if (state.equals(LifecycleState.FAILED)) { // Don't transition to STOPPING_PREP as that would briefly mark the // component as available but do ensure the BEFORE_STOP_EVENT is // fired fireLifecycleEvent(BEFORE_STOP_EVENT, null); } else { setStateInternal(LifecycleState.STOPPING_PREP, null, false); } try { stopInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.stopFail",toString()), t); } if (state.equals(LifecycleState.MUST_DESTROY)) { // Complete stop process first setStateInternal(LifecycleState.STOPPED, null, false); destroy(); } else { // Shouldn't be necessary but acts as a check that sub-classes are // doing what they are supposed to. if (!state.equals(LifecycleState.STOPPING)) { invalidTransition(Lifecycle.AFTER_STOP_EVENT); } setStateInternal(LifecycleState.STOPPED, null, false); } }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void destroy() throws LifecycleException { if (LifecycleState.FAILED.equals(state)) { try { // Triggers clean-up stop(); } catch (LifecycleException e) { // Just log. Still want to destroy. log.warn(sm.getString("lifecycleBase.destroyStopFail"), e); } } if (LifecycleState.DESTROYING.equals(state) || LifecycleState.DESTROYED.equals(state)) { if (log.isDebugEnabled()) { Exception e = new LifecycleException(); log.debug(sm.getString("lifecycleBase.alreadyDestroyed", toString()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("lifecycleBase.alreadyDestroyed", toString())); } return; } if (!state.equals(LifecycleState.STOPPED) && !state.equals(LifecycleState.FAILED) && !state.equals(LifecycleState.NEW) && !state.equals(LifecycleState.INITIALIZED)) { invalidTransition(Lifecycle.BEFORE_DESTROY_EVENT); } setStateInternal(LifecycleState.DESTROYING, null, false); try { destroyInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); } setStateInternal(LifecycleState.DESTROYED, null, false); }
// in java/org/apache/catalina/util/LifecycleBase.java
protected synchronized void setState(LifecycleState state) throws LifecycleException { setStateInternal(state, null, true); }
// in java/org/apache/catalina/util/LifecycleBase.java
protected synchronized void setState(LifecycleState state, Object data) throws LifecycleException { setStateInternal(state, data, true); }
// in java/org/apache/catalina/util/LifecycleBase.java
private synchronized void setStateInternal(LifecycleState state, Object data, boolean check) throws LifecycleException { if (log.isDebugEnabled()) { log.debug(sm.getString("lifecycleBase.setState", this, state)); } if (check) { // Must have been triggered by one of the abstract methods (assume // code in this class is correct) // null is never a valid state if (state == null) { invalidTransition("null"); // Unreachable code - here to stop eclipse complaining about // a possible NPE further down the method return; } // Any method can transition to failed // startInternal() permits STARTING_PREP to STARTING // stopInternal() permits STOPPING_PREP to STOPPING and FAILED to // STOPPING if (!(state == LifecycleState.FAILED || (this.state == LifecycleState.STARTING_PREP && state == LifecycleState.STARTING) || (this.state == LifecycleState.STOPPING_PREP && state == LifecycleState.STOPPING) || (this.state == LifecycleState.FAILED && state == LifecycleState.STOPPING))) { // No other transition permitted invalidTransition(state.name()); } } this.state = state; String lifecycleEvent = state.getLifecycleEvent(); if (lifecycleEvent != null) { fireLifecycleEvent(lifecycleEvent, data); } }
// in java/org/apache/catalina/util/LifecycleBase.java
private void invalidTransition(String type) throws LifecycleException { String msg = sm.getString("lifecycleBase.invalidTransition", type, toString(), state); throw new LifecycleException(msg); }
(Domain) ParseException 26
              
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
final public void Value() throws ParseException { /*@bgen(jjtree) Value */ AstValue jjtn000 = new AstValue(JJTVALUE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case HTTP_TOKEN: t = jj_consume_token(HTTP_TOKEN); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image.trim()); break; case QUOTED_STRING: t = jj_consume_token(QUOTED_STRING); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image.trim()); break; default: jj_la1[1] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public AstCompositeExpression CompositeExpression() throws ParseException { /*@bgen(jjtree) CompositeExpression */ AstCompositeExpression jjtn000 = new AstCompositeExpression(JJTCOMPOSITEEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { label_1: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LITERAL_EXPRESSION: case START_DYNAMIC_EXPRESSION: case START_DEFERRED_EXPRESSION: ; break; default: jj_la1[0] = jj_gen; break label_1; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case START_DEFERRED_EXPRESSION: DeferredExpression(); break; case START_DYNAMIC_EXPRESSION: DynamicExpression(); break; case LITERAL_EXPRESSION: LiteralExpression(); break; default: jj_la1[1] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } jj_consume_token(0); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; {if (true) return jjtn000;} } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } throw new Error("Missing return statement in function"); }
// in java/org/apache/el/parser/ELParser.java
final public void Or() throws ParseException { And(); label_3: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OR0: case OR1: ; break; default: jj_la1[2] = jj_gen; break label_3; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OR0: jj_consume_token(OR0); break; case OR1: jj_consume_token(OR1); break; default: jj_la1[3] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstOr jjtn001 = new AstOr(JJTOR); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { And(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } } }
// in java/org/apache/el/parser/ELParser.java
final public void And() throws ParseException { Equality(); label_4: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case AND0: case AND1: ; break; default: jj_la1[4] = jj_gen; break label_4; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case AND0: jj_consume_token(AND0); break; case AND1: jj_consume_token(AND1); break; default: jj_la1[5] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstAnd jjtn001 = new AstAnd(JJTAND); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Equality(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } } }
// in java/org/apache/el/parser/ELParser.java
final public void Equality() throws ParseException { Compare(); label_5: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQ0: case EQ1: case NE0: case NE1: ; break; default: jj_la1[6] = jj_gen; break label_5; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQ0: case EQ1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQ0: jj_consume_token(EQ0); break; case EQ1: jj_consume_token(EQ1); break; default: jj_la1[7] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstEqual jjtn001 = new AstEqual(JJTEQUAL); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Compare(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case NE0: case NE1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NE0: jj_consume_token(NE0); break; case NE1: jj_consume_token(NE1); break; default: jj_la1[8] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstNotEqual jjtn002 = new AstNotEqual(JJTNOTEQUAL); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Compare(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; default: jj_la1[9] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Compare() throws ParseException { Math(); label_6: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case GT0: case GT1: case LT0: case LT1: case GE0: case GE1: case LE0: case LE1: ; break; default: jj_la1[10] = jj_gen; break label_6; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LT0: case LT1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LT0: jj_consume_token(LT0); break; case LT1: jj_consume_token(LT1); break; default: jj_la1[11] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstLessThan jjtn001 = new AstLessThan(JJTLESSTHAN); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Math(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case GT0: case GT1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case GT0: jj_consume_token(GT0); break; case GT1: jj_consume_token(GT1); break; default: jj_la1[12] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstGreaterThan jjtn002 = new AstGreaterThan(JJTGREATERTHAN); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Math(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; case LE0: case LE1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LE0: jj_consume_token(LE0); break; case LE1: jj_consume_token(LE1); break; default: jj_la1[13] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstLessThanEqual jjtn003 = new AstLessThanEqual(JJTLESSTHANEQUAL); boolean jjtc003 = true; jjtree.openNodeScope(jjtn003); try { Math(); } catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} } finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, 2); } } break; case GE0: case GE1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case GE0: jj_consume_token(GE0); break; case GE1: jj_consume_token(GE1); break; default: jj_la1[14] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstGreaterThanEqual jjtn004 = new AstGreaterThanEqual(JJTGREATERTHANEQUAL); boolean jjtc004 = true; jjtree.openNodeScope(jjtn004); try { Math(); } catch (Throwable jjte004) { if (jjtc004) { jjtree.clearNodeScope(jjtn004); jjtc004 = false; } else { jjtree.popNode(); } if (jjte004 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte004;} } if (jjte004 instanceof ParseException) { {if (true) throw (ParseException)jjte004;} } {if (true) throw (Error)jjte004;} } finally { if (jjtc004) { jjtree.closeNodeScope(jjtn004, 2); } } break; default: jj_la1[15] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Math() throws ParseException { Multiplication(); label_7: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PLUS: case MINUS: ; break; default: jj_la1[16] = jj_gen; break label_7; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PLUS: jj_consume_token(PLUS); AstPlus jjtn001 = new AstPlus(JJTPLUS); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Multiplication(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case MINUS: jj_consume_token(MINUS); AstMinus jjtn002 = new AstMinus(JJTMINUS); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Multiplication(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; default: jj_la1[17] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Multiplication() throws ParseException { Unary(); label_8: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MULT: case DIV0: case DIV1: case MOD0: case MOD1: ; break; default: jj_la1[18] = jj_gen; break label_8; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MULT: jj_consume_token(MULT); AstMult jjtn001 = new AstMult(JJTMULT); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Unary(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case DIV0: case DIV1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DIV0: jj_consume_token(DIV0); break; case DIV1: jj_consume_token(DIV1); break; default: jj_la1[19] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstDiv jjtn002 = new AstDiv(JJTDIV); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Unary(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; case MOD0: case MOD1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MOD0: jj_consume_token(MOD0); break; case MOD1: jj_consume_token(MOD1); break; default: jj_la1[20] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstMod jjtn003 = new AstMod(JJTMOD); boolean jjtc003 = true; jjtree.openNodeScope(jjtn003); try { Unary(); } catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} } finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, 2); } } break; default: jj_la1[21] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Unary() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MINUS: jj_consume_token(MINUS); AstNegative jjtn001 = new AstNegative(JJTNEGATIVE); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Unary(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } } break; case NOT0: case NOT1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NOT0: jj_consume_token(NOT0); break; case NOT1: jj_consume_token(NOT1); break; default: jj_la1[22] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstNot jjtn002 = new AstNot(JJTNOT); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Unary(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, true); } } break; case EMPTY: jj_consume_token(EMPTY); AstEmpty jjtn003 = new AstEmpty(JJTEMPTY); boolean jjtc003 = true; jjtree.openNodeScope(jjtn003); try { Unary(); } catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} } finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, true); } } break; case INTEGER_LITERAL: case FLOATING_POINT_LITERAL: case STRING_LITERAL: case TRUE: case FALSE: case NULL: case LPAREN: case IDENTIFIER: Value(); break; default: jj_la1[23] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/el/parser/ELParser.java
final public void ValuePrefix() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case INTEGER_LITERAL: case FLOATING_POINT_LITERAL: case STRING_LITERAL: case TRUE: case FALSE: case NULL: Literal(); break; case LPAREN: case IDENTIFIER: NonLiteral(); break; default: jj_la1[25] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/el/parser/ELParser.java
final public void ValueSuffix() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DOT: DotSuffix(); break; case LBRACK: BracketSuffix(); break; default: jj_la1[26] = jj_gen; jj_consume_token(-1); throw new ParseException(); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LPAREN: MethodParameters(); break; default: jj_la1[27] = jj_gen; ; } }
// in java/org/apache/el/parser/ELParser.java
final public void NonLiteral() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LPAREN: jj_consume_token(LPAREN); Expression(); jj_consume_token(RPAREN); break; default: jj_la1[30] = jj_gen; if (jj_2_2(2147483647)) { Function(); } else { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: Identifier(); break; default: jj_la1[31] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } } }
// in java/org/apache/el/parser/ELParser.java
final public void Literal() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TRUE: case FALSE: Boolean(); break; case FLOATING_POINT_LITERAL: FloatingPoint(); break; case INTEGER_LITERAL: Integer(); break; case STRING_LITERAL: String(); break; case NULL: Null(); break; default: jj_la1[34] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/el/parser/ELParser.java
final public void Boolean() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TRUE: AstTrue jjtn001 = new AstTrue(JJTTRUE); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { jj_consume_token(TRUE); } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } } break; case FALSE: AstFalse jjtn002 = new AstFalse(JJTFALSE); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { jj_consume_token(FALSE); } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, true); } } break; default: jj_la1[35] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/catalina/ssi/ExpressionParseTree.java
private void parseExpression(String expr) throws ParseException { StringNode currStringNode = null; // We cheat a little and start an artificial // group right away. It makes finishing easier. pushOpp(null); ExpressionTokenizer et = new ExpressionTokenizer(expr); while (et.hasMoreTokens()) { int token = et.nextToken(); if (token != ExpressionTokenizer.TOKEN_STRING) currStringNode = null; switch (token) { case ExpressionTokenizer.TOKEN_STRING : if (currStringNode == null) { currStringNode = new StringNode(et.getTokenValue()); nodeStack.add(0, currStringNode); } else { // Add to the existing currStringNode.value.append(" "); currStringNode.value.append(et.getTokenValue()); } break; case ExpressionTokenizer.TOKEN_AND : pushOpp(new AndNode()); break; case ExpressionTokenizer.TOKEN_OR : pushOpp(new OrNode()); break; case ExpressionTokenizer.TOKEN_NOT : pushOpp(new NotNode()); break; case ExpressionTokenizer.TOKEN_EQ : pushOpp(new EqualNode()); break; case ExpressionTokenizer.TOKEN_NOT_EQ : pushOpp(new NotNode()); // Sneak the regular node in. The NOT will // be resolved when the next opp comes along. oppStack.add(0, new EqualNode()); break; case ExpressionTokenizer.TOKEN_RBRACE : // Closeout the current group resolveGroup(); break; case ExpressionTokenizer.TOKEN_LBRACE : // Push a group marker pushOpp(null); break; case ExpressionTokenizer.TOKEN_GE : pushOpp(new NotNode()); // Similar strategy to NOT_EQ above, except this // is NOT less than oppStack.add(0, new LessThanNode()); break; case ExpressionTokenizer.TOKEN_LE : pushOpp(new NotNode()); // Similar strategy to NOT_EQ above, except this // is NOT greater than oppStack.add(0, new GreaterThanNode()); break; case ExpressionTokenizer.TOKEN_GT : pushOpp(new GreaterThanNode()); break; case ExpressionTokenizer.TOKEN_LT : pushOpp(new LessThanNode()); break; case ExpressionTokenizer.TOKEN_END : break; } } // Finish off the rest of the opps resolveGroup(); if (nodeStack.size() == 0) { throw new ParseException("No nodes created.", et.getIndex()); } if (nodeStack.size() > 1) { throw new ParseException("Extra nodes created.", et.getIndex()); } if (oppStack.size() != 0) { throw new ParseException("Unused opp nodes exist.", et.getIndex()); } root = nodeStack.get(0); }
0 37
              
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
final public void Type() throws ParseException { /*@bgen(jjtree) Type */ AstType jjtn000 = new AstType(JJTTYPE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(HTTP_TOKEN); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image.trim()); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
final public void SubType() throws ParseException { /*@bgen(jjtree) SubType */ AstSubType jjtn000 = new AstSubType(JJTSUBTYPE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(HTTP_TOKEN); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image.trim()); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
final public void Parameter() throws ParseException { /*@bgen(jjtree) Parameter */ AstParameter jjtn000 = new AstParameter(JJTPARAMETER); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { Attribute(); jj_consume_token(EQUALS); Value(); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
final public void Attribute() throws ParseException { /*@bgen(jjtree) Attribute */ AstAttribute jjtn000 = new AstAttribute(JJTATTRIBUTE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(HTTP_TOKEN); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image.trim()); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
final public void Value() throws ParseException { /*@bgen(jjtree) Value */ AstValue jjtn000 = new AstValue(JJTVALUE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case HTTP_TOKEN: t = jj_consume_token(HTTP_TOKEN); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image.trim()); break; case QUOTED_STRING: t = jj_consume_token(QUOTED_STRING); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image.trim()); break; default: jj_la1[1] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
private Token jj_consume_token(int kind) throws ParseException { Token oldToken; if ((oldToken = token).next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; if (token.kind == kind) { jj_gen++; return token; } token = oldToken; jj_kind = kind; throw generateParseException(); }
// in java/org/apache/el/parser/ELParser.java
final public AstCompositeExpression CompositeExpression() throws ParseException { /*@bgen(jjtree) CompositeExpression */ AstCompositeExpression jjtn000 = new AstCompositeExpression(JJTCOMPOSITEEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { label_1: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LITERAL_EXPRESSION: case START_DYNAMIC_EXPRESSION: case START_DEFERRED_EXPRESSION: ; break; default: jj_la1[0] = jj_gen; break label_1; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case START_DEFERRED_EXPRESSION: DeferredExpression(); break; case START_DYNAMIC_EXPRESSION: DynamicExpression(); break; case LITERAL_EXPRESSION: LiteralExpression(); break; default: jj_la1[1] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } jj_consume_token(0); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; {if (true) return jjtn000;} } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } throw new Error("Missing return statement in function"); }
// in java/org/apache/el/parser/ELParser.java
final public void LiteralExpression() throws ParseException { /*@bgen(jjtree) LiteralExpression */ AstLiteralExpression jjtn000 = new AstLiteralExpression(JJTLITERALEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(LITERAL_EXPRESSION); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.setImage(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void DeferredExpression() throws ParseException { /*@bgen(jjtree) DeferredExpression */ AstDeferredExpression jjtn000 = new AstDeferredExpression(JJTDEFERREDEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(START_DEFERRED_EXPRESSION); Expression(); jj_consume_token(END_EXPRESSION); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void DynamicExpression() throws ParseException { /*@bgen(jjtree) DynamicExpression */ AstDynamicExpression jjtn000 = new AstDynamicExpression(JJTDYNAMICEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(START_DYNAMIC_EXPRESSION); Expression(); jj_consume_token(END_EXPRESSION); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Expression() throws ParseException { Choice(); }
// in java/org/apache/el/parser/ELParser.java
final public void Choice() throws ParseException { Or(); label_2: while (true) { if (jj_2_1(3)) { ; } else { break label_2; } jj_consume_token(QUESTIONMARK); Choice(); jj_consume_token(COLON); AstChoice jjtn001 = new AstChoice(JJTCHOICE); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Choice(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 3); } } } }
// in java/org/apache/el/parser/ELParser.java
final public void Or() throws ParseException { And(); label_3: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OR0: case OR1: ; break; default: jj_la1[2] = jj_gen; break label_3; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OR0: jj_consume_token(OR0); break; case OR1: jj_consume_token(OR1); break; default: jj_la1[3] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstOr jjtn001 = new AstOr(JJTOR); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { And(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } } }
// in java/org/apache/el/parser/ELParser.java
final public void And() throws ParseException { Equality(); label_4: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case AND0: case AND1: ; break; default: jj_la1[4] = jj_gen; break label_4; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case AND0: jj_consume_token(AND0); break; case AND1: jj_consume_token(AND1); break; default: jj_la1[5] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstAnd jjtn001 = new AstAnd(JJTAND); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Equality(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } } }
// in java/org/apache/el/parser/ELParser.java
final public void Equality() throws ParseException { Compare(); label_5: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQ0: case EQ1: case NE0: case NE1: ; break; default: jj_la1[6] = jj_gen; break label_5; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQ0: case EQ1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQ0: jj_consume_token(EQ0); break; case EQ1: jj_consume_token(EQ1); break; default: jj_la1[7] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstEqual jjtn001 = new AstEqual(JJTEQUAL); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Compare(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case NE0: case NE1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NE0: jj_consume_token(NE0); break; case NE1: jj_consume_token(NE1); break; default: jj_la1[8] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstNotEqual jjtn002 = new AstNotEqual(JJTNOTEQUAL); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Compare(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; default: jj_la1[9] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Compare() throws ParseException { Math(); label_6: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case GT0: case GT1: case LT0: case LT1: case GE0: case GE1: case LE0: case LE1: ; break; default: jj_la1[10] = jj_gen; break label_6; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LT0: case LT1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LT0: jj_consume_token(LT0); break; case LT1: jj_consume_token(LT1); break; default: jj_la1[11] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstLessThan jjtn001 = new AstLessThan(JJTLESSTHAN); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Math(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case GT0: case GT1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case GT0: jj_consume_token(GT0); break; case GT1: jj_consume_token(GT1); break; default: jj_la1[12] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstGreaterThan jjtn002 = new AstGreaterThan(JJTGREATERTHAN); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Math(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; case LE0: case LE1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LE0: jj_consume_token(LE0); break; case LE1: jj_consume_token(LE1); break; default: jj_la1[13] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstLessThanEqual jjtn003 = new AstLessThanEqual(JJTLESSTHANEQUAL); boolean jjtc003 = true; jjtree.openNodeScope(jjtn003); try { Math(); } catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} } finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, 2); } } break; case GE0: case GE1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case GE0: jj_consume_token(GE0); break; case GE1: jj_consume_token(GE1); break; default: jj_la1[14] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstGreaterThanEqual jjtn004 = new AstGreaterThanEqual(JJTGREATERTHANEQUAL); boolean jjtc004 = true; jjtree.openNodeScope(jjtn004); try { Math(); } catch (Throwable jjte004) { if (jjtc004) { jjtree.clearNodeScope(jjtn004); jjtc004 = false; } else { jjtree.popNode(); } if (jjte004 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte004;} } if (jjte004 instanceof ParseException) { {if (true) throw (ParseException)jjte004;} } {if (true) throw (Error)jjte004;} } finally { if (jjtc004) { jjtree.closeNodeScope(jjtn004, 2); } } break; default: jj_la1[15] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Math() throws ParseException { Multiplication(); label_7: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PLUS: case MINUS: ; break; default: jj_la1[16] = jj_gen; break label_7; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PLUS: jj_consume_token(PLUS); AstPlus jjtn001 = new AstPlus(JJTPLUS); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Multiplication(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case MINUS: jj_consume_token(MINUS); AstMinus jjtn002 = new AstMinus(JJTMINUS); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Multiplication(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; default: jj_la1[17] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Multiplication() throws ParseException { Unary(); label_8: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MULT: case DIV0: case DIV1: case MOD0: case MOD1: ; break; default: jj_la1[18] = jj_gen; break label_8; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MULT: jj_consume_token(MULT); AstMult jjtn001 = new AstMult(JJTMULT); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Unary(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case DIV0: case DIV1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DIV0: jj_consume_token(DIV0); break; case DIV1: jj_consume_token(DIV1); break; default: jj_la1[19] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstDiv jjtn002 = new AstDiv(JJTDIV); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Unary(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; case MOD0: case MOD1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MOD0: jj_consume_token(MOD0); break; case MOD1: jj_consume_token(MOD1); break; default: jj_la1[20] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstMod jjtn003 = new AstMod(JJTMOD); boolean jjtc003 = true; jjtree.openNodeScope(jjtn003); try { Unary(); } catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} } finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, 2); } } break; default: jj_la1[21] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Unary() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MINUS: jj_consume_token(MINUS); AstNegative jjtn001 = new AstNegative(JJTNEGATIVE); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Unary(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } } break; case NOT0: case NOT1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NOT0: jj_consume_token(NOT0); break; case NOT1: jj_consume_token(NOT1); break; default: jj_la1[22] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstNot jjtn002 = new AstNot(JJTNOT); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Unary(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, true); } } break; case EMPTY: jj_consume_token(EMPTY); AstEmpty jjtn003 = new AstEmpty(JJTEMPTY); boolean jjtc003 = true; jjtree.openNodeScope(jjtn003); try { Unary(); } catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} } finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, true); } } break; case INTEGER_LITERAL: case FLOATING_POINT_LITERAL: case STRING_LITERAL: case TRUE: case FALSE: case NULL: case LPAREN: case IDENTIFIER: Value(); break; default: jj_la1[23] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/el/parser/ELParser.java
final public void Value() throws ParseException { AstValue jjtn001 = new AstValue(JJTVALUE); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { ValuePrefix(); label_9: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DOT: case LBRACK: ; break; default: jj_la1[24] = jj_gen; break label_9; } ValueSuffix(); } } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, jjtree.nodeArity() > 1); } } }
// in java/org/apache/el/parser/ELParser.java
final public void ValuePrefix() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case INTEGER_LITERAL: case FLOATING_POINT_LITERAL: case STRING_LITERAL: case TRUE: case FALSE: case NULL: Literal(); break; case LPAREN: case IDENTIFIER: NonLiteral(); break; default: jj_la1[25] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/el/parser/ELParser.java
final public void ValueSuffix() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DOT: DotSuffix(); break; case LBRACK: BracketSuffix(); break; default: jj_la1[26] = jj_gen; jj_consume_token(-1); throw new ParseException(); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LPAREN: MethodParameters(); break; default: jj_la1[27] = jj_gen; ; } }
// in java/org/apache/el/parser/ELParser.java
final public void DotSuffix() throws ParseException { /*@bgen(jjtree) DotSuffix */ AstDotSuffix jjtn000 = new AstDotSuffix(JJTDOTSUFFIX); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { jj_consume_token(DOT); t = jj_consume_token(IDENTIFIER); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.setImage(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void BracketSuffix() throws ParseException { /*@bgen(jjtree) BracketSuffix */ AstBracketSuffix jjtn000 = new AstBracketSuffix(JJTBRACKETSUFFIX); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(LBRACK); Expression(); jj_consume_token(RBRACK); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void MethodParameters() throws ParseException { /*@bgen(jjtree) MethodParameters */ AstMethodParameters jjtn000 = new AstMethodParameters(JJTMETHODPARAMETERS); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(LPAREN); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case INTEGER_LITERAL: case FLOATING_POINT_LITERAL: case STRING_LITERAL: case TRUE: case FALSE: case NULL: case LPAREN: case NOT0: case NOT1: case EMPTY: case MINUS: case IDENTIFIER: Expression(); label_10: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: ; break; default: jj_la1[28] = jj_gen; break label_10; } jj_consume_token(COMMA); Expression(); } break; default: jj_la1[29] = jj_gen; ; } jj_consume_token(RPAREN); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void NonLiteral() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LPAREN: jj_consume_token(LPAREN); Expression(); jj_consume_token(RPAREN); break; default: jj_la1[30] = jj_gen; if (jj_2_2(2147483647)) { Function(); } else { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: Identifier(); break; default: jj_la1[31] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } } }
// in java/org/apache/el/parser/ELParser.java
final public void Identifier() throws ParseException { /*@bgen(jjtree) Identifier */ AstIdentifier jjtn000 = new AstIdentifier(JJTIDENTIFIER); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(IDENTIFIER); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.setImage(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Function() throws ParseException { /*@bgen(jjtree) Function */ AstFunction jjtn000 = new AstFunction(JJTFUNCTION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t0 = null; Token t1 = null; try { if (jj_2_3(2)) { t0 = jj_consume_token(IDENTIFIER); jj_consume_token(COLON); } else { ; } t1 = jj_consume_token(IDENTIFIER); if (t0 != null) { jjtn000.setPrefix(t0.image); jjtn000.setLocalName(t1.image); } else { jjtn000.setLocalName(t1.image); } jj_consume_token(LPAREN); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case INTEGER_LITERAL: case FLOATING_POINT_LITERAL: case STRING_LITERAL: case TRUE: case FALSE: case NULL: case LPAREN: case NOT0: case NOT1: case EMPTY: case MINUS: case IDENTIFIER: Expression(); label_11: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: ; break; default: jj_la1[32] = jj_gen; break label_11; } jj_consume_token(COMMA); Expression(); } break; default: jj_la1[33] = jj_gen; ; } jj_consume_token(RPAREN); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Literal() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TRUE: case FALSE: Boolean(); break; case FLOATING_POINT_LITERAL: FloatingPoint(); break; case INTEGER_LITERAL: Integer(); break; case STRING_LITERAL: String(); break; case NULL: Null(); break; default: jj_la1[34] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/el/parser/ELParser.java
final public void Boolean() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TRUE: AstTrue jjtn001 = new AstTrue(JJTTRUE); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { jj_consume_token(TRUE); } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } } break; case FALSE: AstFalse jjtn002 = new AstFalse(JJTFALSE); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { jj_consume_token(FALSE); } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, true); } } break; default: jj_la1[35] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/el/parser/ELParser.java
final public void FloatingPoint() throws ParseException { /*@bgen(jjtree) FloatingPoint */ AstFloatingPoint jjtn000 = new AstFloatingPoint(JJTFLOATINGPOINT); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(FLOATING_POINT_LITERAL); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.setImage(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Integer() throws ParseException { /*@bgen(jjtree) Integer */ AstInteger jjtn000 = new AstInteger(JJTINTEGER); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(INTEGER_LITERAL); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.setImage(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void String() throws ParseException { /*@bgen(jjtree) String */ AstString jjtn000 = new AstString(JJTSTRING); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(STRING_LITERAL); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.setImage(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Null() throws ParseException { /*@bgen(jjtree) Null */ AstNull jjtn000 = new AstNull(JJTNULL); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(NULL); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
private Token jj_consume_token(int kind) throws ParseException { Token oldToken; if ((oldToken = token).next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; if (token.kind == kind) { jj_gen++; if (++jj_gc > 100) { jj_gc = 0; for (int i = 0; i < jj_2_rtns.length; i++) { JJCalls c = jj_2_rtns[i]; while (c != null) { if (c.gen < jj_gen) c.first = null; c = c.next; } } } return token; } token = oldToken; jj_kind = kind; throw generateParseException(); }
// in java/org/apache/catalina/ssi/ExpressionParseTree.java
private void parseExpression(String expr) throws ParseException { StringNode currStringNode = null; // We cheat a little and start an artificial // group right away. It makes finishing easier. pushOpp(null); ExpressionTokenizer et = new ExpressionTokenizer(expr); while (et.hasMoreTokens()) { int token = et.nextToken(); if (token != ExpressionTokenizer.TOKEN_STRING) currStringNode = null; switch (token) { case ExpressionTokenizer.TOKEN_STRING : if (currStringNode == null) { currStringNode = new StringNode(et.getTokenValue()); nodeStack.add(0, currStringNode); } else { // Add to the existing currStringNode.value.append(" "); currStringNode.value.append(et.getTokenValue()); } break; case ExpressionTokenizer.TOKEN_AND : pushOpp(new AndNode()); break; case ExpressionTokenizer.TOKEN_OR : pushOpp(new OrNode()); break; case ExpressionTokenizer.TOKEN_NOT : pushOpp(new NotNode()); break; case ExpressionTokenizer.TOKEN_EQ : pushOpp(new EqualNode()); break; case ExpressionTokenizer.TOKEN_NOT_EQ : pushOpp(new NotNode()); // Sneak the regular node in. The NOT will // be resolved when the next opp comes along. oppStack.add(0, new EqualNode()); break; case ExpressionTokenizer.TOKEN_RBRACE : // Closeout the current group resolveGroup(); break; case ExpressionTokenizer.TOKEN_LBRACE : // Push a group marker pushOpp(null); break; case ExpressionTokenizer.TOKEN_GE : pushOpp(new NotNode()); // Similar strategy to NOT_EQ above, except this // is NOT less than oppStack.add(0, new LessThanNode()); break; case ExpressionTokenizer.TOKEN_LE : pushOpp(new NotNode()); // Similar strategy to NOT_EQ above, except this // is NOT greater than oppStack.add(0, new GreaterThanNode()); break; case ExpressionTokenizer.TOKEN_GT : pushOpp(new GreaterThanNode()); break; case ExpressionTokenizer.TOKEN_LT : pushOpp(new LessThanNode()); break; case ExpressionTokenizer.TOKEN_END : break; } } // Finish off the rest of the opps resolveGroup(); if (nodeStack.size() == 0) { throw new ParseException("No nodes created.", et.getIndex()); } if (nodeStack.size() > 1) { throw new ParseException("Extra nodes created.", et.getIndex()); } if (oppStack.size() != 0) { throw new ParseException("Unused opp nodes exist.", et.getIndex()); } root = nodeStack.get(0); }
(Lib) RuntimeOperationsException 23
              
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getInvoke(String aname, Object[] params, String[] signature, BaseModelMBean bean, Object resource) throws MBeanException, ReflectionException { Method method = null; if (params == null) params = new Object[0]; if (signature == null) signature = new String[0]; if (params.length != signature.length) throw new RuntimeOperationsException( new IllegalArgumentException( "Inconsistent arguments and signature"), "Inconsistent arguments and signature"); // Acquire the ModelMBeanOperationInfo information for // the requested operation OperationInfo opInfo = operations.get(aname); if (opInfo == null) throw new MBeanException(new ServiceNotFoundException( "Cannot find operation " + aname), "Cannot find operation " + aname); // Prepare the signature required by Java reflection APIs // FIXME - should we use the signature from opInfo? Class<?> types[] = new Class[signature.length]; for (int i = 0; i < signature.length; i++) { types[i] = BaseModelMBean.getAttributeClass(signature[i]); } // Locate the method to be invoked, either in this MBean itself // or in the corresponding managed resource // FIXME - Accessible methods in superinterfaces? Object object = null; Exception exception = null; try { object = bean; method = object.getClass().getMethod(aname, types); } catch (NoSuchMethodException e) { exception = e; } try { if ((method == null) && (resource != null)) { object = resource; method = object.getClass().getMethod(aname, types); } } catch (NoSuchMethodException e) { exception = e; } if (method == null) { throw new ReflectionException(exception, "Cannot find method " + aname + " with this signature"); } return method; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).getAttribute(name); } Method m=managedBean.getGetter(name, this, resource); Object result = null; try { Class<?> declaring = m.getDeclaringClass(); // workaround for catalina weird mbeans - the declaring class is BaseModelMBean. // but this is the catalina class. if( declaring.isAssignableFrom(this.getClass()) ) { result = m.invoke(this, NO_ARGS_PARAM ); } else { result = m.invoke(resource, NO_ARGS_PARAM ); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public AttributeList getAttributes(String names[]) { // Validate the input parameters if (names == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute names list is null"), "Attribute names list is null"); // Prepare our response, eating all exceptions AttributeList response = new AttributeList(); for (int i = 0; i < names.length; i++) { try { response.add(new Attribute(names[i],getAttribute(names[i]))); } catch (Exception e) { // Not having a particular attribute in the response // is the indication of a getter problem } } return (response); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object invoke(String name, Object params[], String signature[]) throws MBeanException, ReflectionException { if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).invoke(name, params, signature); } // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Method name is null"), "Method name is null"); if( log.isDebugEnabled()) log.debug("Invoke " + name); Method method= managedBean.getInvoke(name, params, signature, this, resource); // Invoke the selected method on the appropriate object Object result = null; try { if( method.getDeclaringClass().isAssignableFrom( this.getClass()) ) { result = method.invoke(this, params ); } else { result = method.invoke(resource, params); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if( log.isDebugEnabled() ) log.debug("Setting attribute " + this + " " + attribute ); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { try { ((DynamicMBean)resource).setAttribute(attribute); } catch (InvalidAttributeValueException e) { throw new MBeanException(e); } return; } // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); Object oldValue=null; //if( getAttMap.get(name) != null ) // oldValue=getAttribute( name ); Method m=managedBean.getSetter(name,this,resource); try { if( m.getDeclaringClass().isAssignableFrom( this.getClass()) ) { m.invoke(this, new Object[] { value }); } else { m.invoke(resource, new Object[] { value }); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } try { sendAttributeChangeNotification(new Attribute( name, oldValue), attribute); } catch(Exception ex) { log.error("Error sending notification " + name, ex); } //attributes.put( name, value ); // if( source != null ) { // // this mbean is associated with a source - maybe we want to persist // source.updateField(oname, name, value); // } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
public Object getManagedResource() throws InstanceNotFoundException, InvalidTargetObjectTypeException, MBeanException, RuntimeOperationsException { if (resource == null) throw new RuntimeOperationsException (new IllegalArgumentException("Managed resource is null"), "Managed resource is null"); return resource; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
public void setManagedResource(Object resource, String type) throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { if (resource == null) throw new RuntimeOperationsException (new IllegalArgumentException("Managed resource is null"), "Managed resource is null"); // if (!"objectreference".equalsIgnoreCase(type)) // throw new InvalidTargetObjectTypeException(type); this.resource = resource; this.resourceType = resource.getClass().getName(); // // Make the resource aware of the model mbean. // try { // Method m=resource.getClass().getMethod("setModelMBean", // new Class[] {ModelMBean.class}); // if( m!= null ) { // m.invoke(resource, new Object[] {this}); // } // } catch( NoSuchMethodException t ) { // // ignore // } catch( Throwable t ) { // log.error( "Can't set model mbean ", t ); // } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendAttributeChangeNotification (AttributeChangeNotification notification) throws MBeanException, RuntimeOperationsException { if (notification == null) throw new RuntimeOperationsException (new IllegalArgumentException("Notification is null"), "Notification is null"); if (attributeBroadcaster == null) return; // This means there are no registered listeners if( log.isDebugEnabled() ) log.debug( "AttributeChangeNotification " + notification ); attributeBroadcaster.sendNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendNotification(Notification notification) throws MBeanException, RuntimeOperationsException { if (notification == null) throw new RuntimeOperationsException (new IllegalArgumentException("Notification is null"), "Notification is null"); if (generalBroadcaster == null) return; // This means there are no registered listeners generalBroadcaster.sendNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendNotification(String message) throws MBeanException, RuntimeOperationsException { if (message == null) throw new RuntimeOperationsException (new IllegalArgumentException("Message is null"), "Message is null"); Notification notification = new Notification ("jmx.modelmbean.generic", this, 1, message); sendNotification(notification); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); Object result = null; try { Connector connector = (Connector) getManagedResource(); result = IntrospectionUtils.getProperty(connector, name); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return result; }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); try { Connector connector = (Connector) getManagedResource(); IntrospectionUtils.setProperty(connector, name, String.valueOf(value)); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("auth".equals(name)) { return (cr.getAuth()); } else if ("description".equals(name)) { return (cr.getDescription()); } else if ("name".equals(name)) { return (cr.getName()); } else if ("scope".equals(name)) { return (cr.getScope()); } else if ("type".equals(name)) { return (cr.getType()); } else { value = (String) cr.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("auth".equals(name)) { cr.setAuth((String)value); } else if ("description".equals(name)) { cr.setDescription((String)value); } else if ("name".equals(name)) { cr.setName((String)value); } else if ("scope".equals(name)) { cr.setScope((String)value); } else if ("type".equals(name)) { cr.setType((String)value); } else { cr.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = cr.getNamingResources(); nr.removeResource(cr.getName()); nr.addResource(cr); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink cl = null; try { cl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("global".equals(name)) { return (cl.getGlobal()); } else if ("description".equals(name)) { return (cl.getDescription()); } else if ("name".equals(name)) { return (cl.getName()); } else if ("type".equals(name)) { return (cl.getType()); } else { value = (String) cl.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink crl = null; try { crl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("global".equals(name)) { crl.setGlobal((String)value); } else if ("description".equals(name)) { crl.setDescription((String)value); } else if ("name".equals(name)) { crl.setName((String)value); } else if ("type".equals(name)) { crl.setType((String)value); } else { crl.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = crl.getNamingResources(); nr.removeResourceLink(crl.getName()); nr.addResourceLink(crl); }
3
              
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
22
              
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public DynamicMBean createMBean() throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { return (createMBean(null)); }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public DynamicMBean createMBean(Object instance) throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { BaseModelMBean mbean = null; // Load the ModelMBean implementation class if(getClassName().equals(BASE_MBEAN)) { // Skip introspection mbean = new BaseModelMBean(); } else { Class<?> clazz = null; Exception ex = null; try { clazz = Class.forName(getClassName()); } catch (Exception e) { } if( clazz==null ) { try { ClassLoader cl= Thread.currentThread().getContextClassLoader(); if ( cl != null) clazz= cl.loadClass(getClassName()); } catch (Exception e) { ex=e; } } if( clazz==null) { throw new MBeanException (ex, "Cannot load ModelMBean class " + getClassName()); } try { // Stupid - this will set the default minfo first.... mbean = (BaseModelMBean) clazz.newInstance(); } catch (RuntimeOperationsException e) { throw e; } catch (Exception e) { throw new MBeanException (e, "Cannot instantiate ModelMBean of class " + getClassName()); } } mbean.setManagedBean(this); // Set the managed resource (if any) try { if (instance != null) mbean.setManagedResource(instance, "ObjectReference"); } catch (InstanceNotFoundException e) { throw e; } return (mbean); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
public Object getManagedResource() throws InstanceNotFoundException, InvalidTargetObjectTypeException, MBeanException, RuntimeOperationsException { if (resource == null) throw new RuntimeOperationsException (new IllegalArgumentException("Managed resource is null"), "Managed resource is null"); return resource; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
public void setManagedResource(Object resource, String type) throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { if (resource == null) throw new RuntimeOperationsException (new IllegalArgumentException("Managed resource is null"), "Managed resource is null"); // if (!"objectreference".equalsIgnoreCase(type)) // throw new InvalidTargetObjectTypeException(type); this.resource = resource; this.resourceType = resource.getClass().getName(); // // Make the resource aware of the model mbean. // try { // Method m=resource.getClass().getMethod("setModelMBean", // new Class[] {ModelMBean.class}); // if( m!= null ) { // m.invoke(resource, new Object[] {this}); // } // } catch( NoSuchMethodException t ) { // // ignore // } catch( Throwable t ) { // log.error( "Can't set model mbean ", t ); // } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendAttributeChangeNotification (AttributeChangeNotification notification) throws MBeanException, RuntimeOperationsException { if (notification == null) throw new RuntimeOperationsException (new IllegalArgumentException("Notification is null"), "Notification is null"); if (attributeBroadcaster == null) return; // This means there are no registered listeners if( log.isDebugEnabled() ) log.debug( "AttributeChangeNotification " + notification ); attributeBroadcaster.sendNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendAttributeChangeNotification (Attribute oldValue, Attribute newValue) throws MBeanException, RuntimeOperationsException { // Calculate the class name for the change notification String type = null; if (newValue.getValue() != null) type = newValue.getValue().getClass().getName(); else if (oldValue.getValue() != null) type = oldValue.getValue().getClass().getName(); else return; // Old and new are both null == no change AttributeChangeNotification notification = new AttributeChangeNotification (this, 1, System.currentTimeMillis(), "Attribute value has changed", oldValue.getName(), type, oldValue.getValue(), newValue.getValue()); sendAttributeChangeNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendNotification(Notification notification) throws MBeanException, RuntimeOperationsException { if (notification == null) throw new RuntimeOperationsException (new IllegalArgumentException("Notification is null"), "Notification is null"); if (generalBroadcaster == null) return; // This means there are no registered listeners generalBroadcaster.sendNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendNotification(String message) throws MBeanException, RuntimeOperationsException { if (message == null) throw new RuntimeOperationsException (new IllegalArgumentException("Message is null"), "Message is null"); Notification notification = new Notification ("jmx.modelmbean.generic", this, 1, message); sendNotification(notification); }
(Lib) OperationNotSupportedException 20
              
// in java/org/apache/naming/NamingContext.java
Override public String getNameInNamespace() throws NamingException { throw new OperationNotSupportedException (sm.getString("namingContext.noAbsoluteName")); //FIXME ? }
// in java/org/apache/naming/NamingContext.java
protected boolean checkWritable() throws NamingException { if (isWritable()) { return true; } else { if (exceptionOnFailedWrite) { throw new javax.naming.OperationNotSupportedException( sm.getString("namingContext.readOnly")); } } return false; }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void unbind(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void rename(String oldName, String newName) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void destroySubcontext(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void bind(String name, Object obj, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void rebind(String name, Object obj, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public DirContext getSchema(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public DirContext getSchemaClassDefinition(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public DirContext getSchema(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public DirContext getSchemaClassDefinition(String name) throws NamingException { throw new OperationNotSupportedException(); }
0 0
(Domain) PropertyNotFoundException 18
              
// in java/org/apache/el/parser/AstIdentifier.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { return expr.getType(ctx.getELContext()); } } ctx.setPropertyResolved(false); Class<?> result = ctx.getELResolver().getType(ctx, null, this.image); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } return result; }
// in java/org/apache/el/parser/AstIdentifier.java
Override public Object getValue(EvaluationContext ctx) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { return expr.getValue(ctx.getELContext()); } } ctx.setPropertyResolved(false); Object result = ctx.getELResolver().getValue(ctx, null, this.image); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } return result; }
// in java/org/apache/el/parser/AstIdentifier.java
Override public boolean isReadOnly(EvaluationContext ctx) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { return expr.isReadOnly(ctx.getELContext()); } } ctx.setPropertyResolved(false); boolean result = ctx.getELResolver().isReadOnly(ctx, null, this.image); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } return result; }
// in java/org/apache/el/parser/AstIdentifier.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { expr.setValue(ctx.getELContext(), value); return; } } ctx.setPropertyResolved(false); ctx.getELResolver().setValue(ctx, null, this.image, value); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } }
// in java/org/apache/el/parser/AstValue.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { Target t = getTarget(ctx); ctx.setPropertyResolved(false); Class<?> result = ctx.getELResolver().getType(ctx, t.base, t.property); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", t.base, t.property)); } return result; }
// in java/org/apache/el/parser/AstValue.java
private final Target getTarget(EvaluationContext ctx) throws ELException { // evaluate expr-a to value-a Object base = this.children[0].getValue(ctx); // if our base is null (we know there are more properties to evaluate) if (base == null) { throw new PropertyNotFoundException(MessageFactory.get( "error.unreachable.base", this.children[0].getImage())); } // set up our start/end Object property = null; int propCount = this.jjtGetNumChildren(); if (propCount > 2 && this.jjtGetChild(propCount - 1) instanceof AstMethodParameters) { // Method call with paramaters. propCount-=2; } else { propCount--; } int i = 1; // evaluate any properties before our target ELResolver resolver = ctx.getELResolver(); if (propCount > 1) { while (base != null && i < propCount) { property = this.children[i].getValue(ctx); ctx.setPropertyResolved(false); base = resolver.getValue(ctx, base, property); i++; } // if we are in this block, we have more properties to resolve, // but our base was null if (base == null || property == null) { throw new PropertyNotFoundException(MessageFactory.get( "error.unreachable.property", property)); } } property = this.children[i].getValue(ctx); if (property == null) { throw new PropertyNotFoundException(MessageFactory.get( "error.unreachable.property", this.children[i])); } Target t = new Target(); t.base = base; t.property = property; return t; }
// in java/org/apache/el/parser/AstValue.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object base = this.children[0].getValue(ctx); int propCount = this.jjtGetNumChildren(); int i = 1; Object suffix = null; ELResolver resolver = ctx.getELResolver(); while (base != null && i < propCount) { suffix = this.children[i].getValue(ctx); if (i + 1 < propCount && (this.children[i+1] instanceof AstMethodParameters)) { AstMethodParameters mps = (AstMethodParameters) this.children[i+1]; // This is a method base = resolver.invoke(ctx, base, suffix, null, mps.getParameters(ctx)); i+=2; } else { // This is a property if (suffix == null) { return null; } ctx.setPropertyResolved(false); base = resolver.getValue(ctx, base, suffix); i++; } } if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", base, suffix)); } return base; }
// in java/org/apache/el/parser/AstValue.java
Override public boolean isReadOnly(EvaluationContext ctx) throws ELException { Target t = getTarget(ctx); ctx.setPropertyResolved(false); boolean result = ctx.getELResolver().isReadOnly(ctx, t.base, t.property); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", t.base, t.property)); } return result; }
// in java/org/apache/el/parser/AstValue.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { Target t = getTarget(ctx); ctx.setPropertyResolved(false); ELResolver resolver = ctx.getELResolver(); // coerce to the expected type Class<?> targetClass = resolver.getType(ctx, t.base, t.property); if (COERCE_TO_ZERO == true || !isAssignable(value, targetClass)) { resolver.setValue(ctx, t.base, t.property, ELSupport.coerceToType(value, targetClass)); } else { resolver.setValue(ctx, t.base, t.property, value); } if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", t.base, t.property)); } }
// in java/javax/el/ArrayELResolver.java
private static final void checkBounds(Object base, int idx) { if (idx < 0 || idx >= Array.getLength(base)) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } }
// in java/javax/el/BeanELResolver.java
private BeanProperty get(ELContext ctx, String name) { BeanProperty property = this.properties.get(name); if (property == null) { throw new PropertyNotFoundException(message(ctx, "propertyNotFound", new Object[] { type.getName(), name })); } return property; }
// in java/javax/el/BeanELResolver.java
private Method write(ELContext ctx) { if (this.write == null) { this.write = getMethod(this.owner, descriptor.getWriteMethod()); if (this.write == null) { throw new PropertyNotFoundException(message(ctx, "propertyNotWritable", new Object[] { type.getName(), descriptor.getName() })); } } return this.write; }
// in java/javax/el/BeanELResolver.java
private Method read(ELContext ctx) { if (this.read == null) { this.read = getMethod(this.owner, descriptor.getReadMethod()); if (this.read == null) { throw new PropertyNotFoundException(message(ctx, "propertyNotReadable", new Object[] { type.getName(), descriptor.getName() })); } } return this.read; }
// in java/javax/el/ListELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return Object.class; } return null; }
// in java/javax/el/ListELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); @SuppressWarnings("unchecked") // Must be OK to cast to Object List<Object> list = (List<Object>) base; if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); try { list.set(idx, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); } } }
// in java/javax/el/ListELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return this.readOnly || UNMODIFIABLE.equals(list.getClass()); } return this.readOnly; }
1
              
// in java/javax/el/ListELResolver.java
catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); }
48
              
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { return this.variableResolver.resolveVariable(property .toString()); } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getValue(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { Object obj = this.variableResolver.resolveVariable(property .toString()); return (obj != null) ? obj.getClass() : null; } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getType(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); throw new PropertyNotWritableException( "Legacy VariableResolver wrapped, not writable"); } if (!context.isPropertyResolved()) { elResolver.setValue(context, base, property, value); } }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return true; } return elResolver.isReadOnly(context, base, property); }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public MethodInfo getMethodInfo(ELContext context) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.getMethodInfo(context); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public Object invoke(ELContext context, Object[] params) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.invoke(context, params); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Class<?> getType(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getType(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public boolean isReadOnly(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.isReadOnly(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void setValue(ELContext context, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { try { this.target.setValue(context, value); } catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Object getValue(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getValue(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/el/MethodExpressionImpl.java
Override public MethodInfo getMethodInfo(ELContext context) throws PropertyNotFoundException, MethodNotFoundException, ELException { Node n = this.getNode(); EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return n.getMethodInfo(ctx, this.paramTypes); }
// in java/org/apache/el/MethodExpressionImpl.java
Override public Object invoke(ELContext context, Object[] params) throws PropertyNotFoundException, MethodNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return this.getNode().invoke(ctx, this.paramTypes, params); }
// in java/org/apache/el/ValueExpressionImpl.java
Override public Class<?> getType(ELContext context) throws PropertyNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return this.getNode().getType(ctx); }
// in java/org/apache/el/ValueExpressionImpl.java
Override public Object getValue(ELContext context) throws PropertyNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); Object value = this.getNode().getValue(ctx); if (this.expectedType != null) { return ELSupport.coerceToType(value, this.expectedType); } return value; }
// in java/org/apache/el/ValueExpressionImpl.java
Override public boolean isReadOnly(ELContext context) throws PropertyNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return this.getNode().isReadOnly(ctx); }
// in java/org/apache/el/ValueExpressionImpl.java
Override public void setValue(ELContext context, Object value) throws PropertyNotFoundException, PropertyNotWritableException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); this.getNode().setValue(ctx, value); }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { PageContext page = (PageContext) context .getContext(JspContext.class); context.setPropertyResolved(true); switch (idx) { case APPLICATIONSCOPE: return ScopeManager.get(page).getApplicationScope(); case COOKIE: return ScopeManager.get(page).getCookie(); case HEADER: return ScopeManager.get(page).getHeader(); case HEADERVALUES: return ScopeManager.get(page).getHeaderValues(); case INITPARAM: return ScopeManager.get(page).getInitParam(); case PAGECONTEXT: return ScopeManager.get(page).getPageContext(); case PAGESCOPE: return ScopeManager.get(page).getPageScope(); case PARAM: return ScopeManager.get(page).getParam(); case PARAM_VALUES: return ScopeManager.get(page).getParamValues(); case REQUEST_SCOPE: return ScopeManager.get(page).getRequestScope(); case SESSION_SCOPE: return ScopeManager.get(page).getSessionScope(); } } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
public Class getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); throw new PropertyNotWritableException(); } } }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); return true; } } return false; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); return page.findAttribute(key); } } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Class<Object> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); int scope = page.getAttributesScope(key); if (scope != 0) { page.setAttribute(key, value, scope); } else { page.setAttribute(key, value); } } } }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); } return false; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); if (property != null) { try { return ((ResourceBundle) base).getObject(property .toString()); } catch (MissingResourceException mre) { return "???" + property.toString() + "???"; } } } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } }
// in java/javax/el/ResourceBundleELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return true; }
// in java/javax/el/CompositeELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; Object result = null; for (int i = 0; i < sz; i++) { result = this.resolvers[i].getValue(context, base, property); if (context.isPropertyResolved()) { return result; } } return null; }
// in java/javax/el/CompositeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { context.setPropertyResolved(false); int sz = this.size; for (int i = 0; i < sz; i++) { this.resolvers[i].setValue(context, base, property, value); if (context.isPropertyResolved()) { return; } } }
// in java/javax/el/CompositeELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; boolean readOnly = false; for (int i = 0; i < sz; i++) { readOnly = this.resolvers[i].isReadOnly(context, base, property); if (context.isPropertyResolved()) { return readOnly; } } return false; }
// in java/javax/el/CompositeELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; Class<?> type; for (int i = 0; i < sz; i++) { type = this.resolvers[i].getType(context, base, property); if (context.isPropertyResolved()) { if (SCOPED_ATTRIBUTE_EL_RESOLVER != null && SCOPED_ATTRIBUTE_EL_RESOLVER.isAssignableFrom( resolvers[i].getClass())) { // Special case since // javax.servlet.jsp.el.ScopedAttributeELResolver will // always return Object.class for type Object value = resolvers[i].getValue(context, base, property); if (value != null) { return value.getClass(); } } return type; } } return null; }
// in java/javax/el/ArrayELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); if (idx < 0 || idx >= Array.getLength(base)) { return null; } return Array.get(base, idx); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); return base.getClass().getComponentType(); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); checkBounds(base, idx); if (value != null && !base.getClass().getComponentType().isAssignableFrom( value.getClass())) { throw new ClassCastException(message(context, "objectNotAssignable", new Object[] {value.getClass().getName(), base.getClass().getComponentType().getName()})); } Array.set(base, idx, value); } }
// in java/javax/el/ArrayELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); } return this.readOnly; }
// in java/javax/el/MapELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return ((Map<?,?>) base).get(property); } return null; }
// in java/javax/el/MapELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/el/MapELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } try { @SuppressWarnings("unchecked") // Must be OK Map<Object, Object> map = ((Map<Object, Object>) base); map.put(property, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } } }
// in java/javax/el/MapELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); return this.readOnly || UNMODIFIABLE.equals(base.getClass()); } return this.readOnly; }
// in java/javax/el/BeanELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); Method m = this.property(context, base, property).read(context); try { return m.invoke(base, (Object[]) null); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); return this.property(context, base, property).getPropertyType(); }
// in java/javax/el/BeanELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return; } context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } Method m = this.property(context, base, property).write(context); try { m.invoke(base, value); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return false; } context.setPropertyResolved(true); return this.readOnly || this.property(context, base, property).isReadOnly(); }
// in java/javax/el/ListELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { return null; } return list.get(idx); } return null; }
// in java/javax/el/ListELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return Object.class; } return null; }
// in java/javax/el/ListELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); @SuppressWarnings("unchecked") // Must be OK to cast to Object List<Object> list = (List<Object>) base; if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); try { list.set(idx, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); } } }
// in java/javax/el/ListELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return this.readOnly || UNMODIFIABLE.equals(list.getClass()); } return this.readOnly; }
(Lib) ClassNotFoundException 17
              
// in java/org/apache/jasper/servlet/JasperLoader.java
Override public synchronized Class<?> loadClass(final String name, boolean resolve) throws ClassNotFoundException { Class<?> clazz = null; // (0) Check our previously loaded class cache clazz = findLoadedClass(name); if (clazz != null) { if (resolve) resolveClass(clazz); return (clazz); } // (.5) Permission to access this class when using a SecurityManager if (securityManager != null) { int dot = name.lastIndexOf('.'); if (dot >= 0) { try { // Do not call the security manager since by default, we grant that package. if (!"org.apache.jasper.runtime".equalsIgnoreCase(name.substring(0,dot))){ securityManager.checkPackageAccess(name.substring(0,dot)); } } catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; se.printStackTrace(); throw new ClassNotFoundException(error); } } } if( !name.startsWith(Constants.JSP_PACKAGE_NAME + '.') ) { // Class is not in org.apache.jsp, therefore, have our // parent load it clazz = parent.loadClass(name); if( resolve ) resolveClass(clazz); return clazz; } return findClass(name); }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
public static SSLImplementation getInstance() throws ClassNotFoundException { for (int i = 0; i < implementations.length; i++) { try { SSLImplementation impl = getInstance(implementations[i]); return impl; } catch (Exception e) { if (logger.isTraceEnabled()) logger.trace("Error creating " + implementations[i], e); } } // If we can't instantiate any of these throw new ClassNotFoundException("Can't find any SSL implementation"); }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
public static SSLImplementation getInstance(String className) throws ClassNotFoundException { if (className == null) return getInstance(); try { // Workaround for the J2SE 1.4.x classloading problem (under // Solaris). // Class.forName(..) fails without creating class using new. // This is an ugly workaround. if (JSSEImplementationClass.equals(className)) { return new org.apache.tomcat.util.net.jsse.JSSEImplementation(); } Class<?> clazz = Class.forName(className); return (SSLImplementation) clazz.newInstance(); } catch (Exception e) { if (logger.isDebugEnabled()) logger .debug("Error loading SSL Implementation " + className, e); throw new ClassNotFoundException( "Error loading SSL Implementation " + className + " :" + e.toString()); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public Class<?> findClass(String name) throws ClassNotFoundException { if (log.isDebugEnabled()) log.debug(" findClass(" + name + ")"); // Cannot load anything from local repositories if class loader is stopped if (!started) { throw new ClassNotFoundException(name); } // (1) Permission to define this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { if (log.isTraceEnabled()) log.trace(" securityManager.checkPackageDefinition"); securityManager.checkPackageDefinition(name.substring(0,i)); } catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); } } } // Ask our superclass to locate this class, if possible // (throws ClassNotFoundException if it is not found) Class<?> clazz = null; try { if (log.isTraceEnabled()) log.trace(" findClassInternal(" + name + ")"); if (hasExternalRepositories && searchExternalFirst) { try { clazz = super.findClass(name); } catch(ClassNotFoundException cnfe) { // Ignore - will search internal repositories next } catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if ((clazz == null)) { try { clazz = findClassInternal(name); } catch(ClassNotFoundException cnfe) { if (!hasExternalRepositories || searchExternalFirst) { throw cnfe; } } catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if ((clazz == null) && hasExternalRepositories && !searchExternalFirst) { try { clazz = super.findClass(name); } catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if (clazz == null) { if (log.isDebugEnabled()) log.debug(" --> Returning ClassNotFoundException"); throw new ClassNotFoundException(name); } } catch (ClassNotFoundException e) { if (log.isTraceEnabled()) log.trace(" --> Passing on ClassNotFoundException"); throw e; } // Return the class we have located if (log.isTraceEnabled()) log.debug(" Returning class " + clazz); if (log.isTraceEnabled()) { ClassLoader cl; if (Globals.IS_SECURITY_ENABLED){ cl = AccessController.doPrivileged( new PrivilegedGetClassLoader(clazz)); } else { cl = clazz.getClassLoader(); } log.debug(" Loaded by " + cl.toString()); } return (clazz); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (log.isDebugEnabled()) log.debug("loadClass(" + name + ", " + resolve + ")"); Class<?> clazz = null; // Log access to stopped classloader if (!started) { try { throw new IllegalStateException(); } catch (IllegalStateException e) { log.info(sm.getString("webappClassLoader.stopped", name), e); } } // (0) Check our previously loaded local class cache clazz = findLoadedClass0(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.1) Check our previously loaded class cache clazz = findLoadedClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.2) Try loading the class with the system class loader, to prevent // the webapp from overriding J2SE classes try { clazz = system.loadClass(name); if (clazz != null) { if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (0.5) Permission to access this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { securityManager.checkPackageAccess(name.substring(0,i)); } catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); } } } boolean delegateLoad = delegate || filter(name); // (1) Delegate to our parent if requested if (delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader1 " + parent); ClassLoader loader = parent; if (loader == null) loader = system; try { clazz = Class.forName(name, false, loader); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } // (2) Search local repositories if (log.isDebugEnabled()) log.debug(" Searching local repositories"); try { clazz = findClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from local repository"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (3) Delegate to parent unconditionally if (!delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader at end: " + parent); ClassLoader loader = parent; if (loader == null) loader = system; try { clazz = Class.forName(name, false, loader); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } throw new ClassNotFoundException(name); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
protected Class<?> findClassInternal(String name) throws ClassNotFoundException { if (!validate(name)) throw new ClassNotFoundException(name); String tempPath = name.replace('.', '/'); String classPath = tempPath + ".class"; ResourceEntry entry = null; if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, classPath); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, classPath); } if (entry == null) throw new ClassNotFoundException(name); Class<?> clazz = entry.loadedClass; if (clazz != null) return clazz; synchronized (this) { clazz = entry.loadedClass; if (clazz != null) return clazz; if (entry.binaryContent == null) throw new ClassNotFoundException(name); // Looking up the package String packageName = null; int pos = name.lastIndexOf('.'); if (pos != -1) packageName = name.substring(0, pos); Package pkg = null; if (packageName != null) { pkg = getPackage(packageName); // Define the package (if null) if (pkg == null) { try { if (entry.manifest == null) { definePackage(packageName, null, null, null, null, null, null, null); } else { definePackage(packageName, entry.manifest, entry.codeBase); } } catch (IllegalArgumentException e) { // Ignore: normal error due to dual definition of package } pkg = getPackage(packageName); } } if (securityManager != null) { // Checking sealing if (pkg != null) { boolean sealCheck = true; if (pkg.isSealed()) { sealCheck = pkg.isSealed(entry.codeBase); } else { sealCheck = (entry.manifest == null) || !isPackageSealed(packageName, entry.manifest); } if (!sealCheck) throw new SecurityException ("Sealing violation loading " + name + " : Package " + packageName + " is sealed."); } } try { clazz = defineClass(name, entry.binaryContent, 0, entry.binaryContent.length, new CodeSource(entry.codeBase, entry.certificates)); } catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); } entry.loadedClass = clazz; entry.binaryContent = null; entry.source = null; entry.codeBase = null; entry.manifest = null; entry.certificates = null; } return clazz; }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
Override protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { ClassLoader latestLoader = (classLoaders!=null && classLoaders.length==0)?null:classLoaders[0]; ClassLoader nonPublicLoader = null; boolean hasNonPublicInterface = false; // define proxy in class loader of non-public interface(s), if any Class<?>[] classObjs = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { Class<?> cl = this.resolveClass(interfaces[i]); if (latestLoader==null) latestLoader = cl.getClassLoader(); if ((cl.getModifiers() & Modifier.PUBLIC) == 0) { if (hasNonPublicInterface) { if (nonPublicLoader != cl.getClassLoader()) { throw new IllegalAccessError( "conflicting non-public interface class loaders"); } } else { nonPublicLoader = cl.getClassLoader(); hasNonPublicInterface = true; } } classObjs[i] = cl; } try { return Proxy.getProxyClass(hasNonPublicInterface ? nonPublicLoader : latestLoader, classObjs); } catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); } }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
public Class<?> findExternalClass(String name) throws ClassNotFoundException { ClassNotFoundException cnfe = null; for (int i=0; i<classLoaders.length; i++ ) { try { Class<?> clazz = Class.forName(name, false, classLoaders[i]); return clazz; } catch ( ClassNotFoundException x ) { cnfe = x; } } if ( cnfe != null ) throw cnfe; else throw new ClassNotFoundException(name); }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
Override protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { Class<?>[] cinterfaces = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) cinterfaces[i] = classLoader.loadClass(interfaces[i]); try { return Proxy.getProxyClass(classLoader, cinterfaces); } catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); } }
9
              
// in java/org/apache/jasper/servlet/JasperLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; se.printStackTrace(); throw new ClassNotFoundException(error); }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
catch (Exception e) { if (logger.isDebugEnabled()) logger .debug("Error loading SSL Implementation " + className, e); throw new ClassNotFoundException( "Error loading SSL Implementation " + className + " :" + e.toString()); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); }
63
              
// in java/org/apache/jasper/compiler/JspUtil.java
public static Class<?> toClass(String type, ClassLoader loader) throws ClassNotFoundException { Class<?> c = null; int i0 = type.indexOf('['); int dims = 0; if (i0 > 0) { // This is an array. Count the dimensions for (int i = 0; i < type.length(); i++) { if (type.charAt(i) == '[') { dims++; } } type = type.substring(0, i0); } if ("boolean".equals(type)) { c = boolean.class; } else if ("char".equals(type)) { c = char.class; } else if ("byte".equals(type)) { c = byte.class; } else if ("short".equals(type)) { c = short.class; } else if ("int".equals(type)) { c = int.class; } else if ("long".equals(type)) { c = long.class; } else if ("float".equals(type)) { c = float.class; } else if ("double".equals(type)) { c = double.class; } else if ("void".equals(type)) { c = void.class; } else if (type.indexOf('[') < 0) { c = loader.loadClass(type); } if (dims == 0) { return c; } if (dims == 1) { return java.lang.reflect.Array.newInstance(c, 1).getClass(); } // Array of more than i dimension return java.lang.reflect.Array.newInstance(c, new int[dims]).getClass(); }
// in java/org/apache/jasper/servlet/JasperLoader.java
Override public Class<?> loadClass(String name) throws ClassNotFoundException { return (loadClass(name, false)); }
// in java/org/apache/jasper/servlet/JasperLoader.java
Override public synchronized Class<?> loadClass(final String name, boolean resolve) throws ClassNotFoundException { Class<?> clazz = null; // (0) Check our previously loaded class cache clazz = findLoadedClass(name); if (clazz != null) { if (resolve) resolveClass(clazz); return (clazz); } // (.5) Permission to access this class when using a SecurityManager if (securityManager != null) { int dot = name.lastIndexOf('.'); if (dot >= 0) { try { // Do not call the security manager since by default, we grant that package. if (!"org.apache.jasper.runtime".equalsIgnoreCase(name.substring(0,dot))){ securityManager.checkPackageAccess(name.substring(0,dot)); } } catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; se.printStackTrace(); throw new ClassNotFoundException(error); } } } if( !name.startsWith(Constants.JSP_PACKAGE_NAME + '.') ) { // Class is not in org.apache.jsp, therefore, have our // parent load it clazz = parent.loadClass(name); if( resolve ) resolveClass(clazz); return clazz; } return findClass(name); }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.mark = in.readUTF(); this.target = (MethodExpression) in.readObject(); }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.mark = in.readUTF(); this.target = (ValueExpression) in.readObject(); }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
public static SSLImplementation getInstance() throws ClassNotFoundException { for (int i = 0; i < implementations.length; i++) { try { SSLImplementation impl = getInstance(implementations[i]); return impl; } catch (Exception e) { if (logger.isTraceEnabled()) logger.trace("Error creating " + implementations[i], e); } } // If we can't instantiate any of these throw new ClassNotFoundException("Can't find any SSL implementation"); }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
public static SSLImplementation getInstance(String className) throws ClassNotFoundException { if (className == null) return getInstance(); try { // Workaround for the J2SE 1.4.x classloading problem (under // Solaris). // Class.forName(..) fails without creating class using new. // This is an ugly workaround. if (JSSEImplementationClass.equals(className)) { return new org.apache.tomcat.util.net.jsse.JSSEImplementation(); } Class<?> clazz = Class.forName(className); return (SSLImplementation) clazz.newInstance(); } catch (Exception e) { if (logger.isDebugEnabled()) logger .debug("Error loading SSL Implementation " + className, e); throw new ClassNotFoundException( "Error loading SSL Implementation " + className + " :" + e.toString()); } }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // read values in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; }
// in java/org/apache/el/lang/FunctionMapperImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.prefix = in.readUTF(); if ("".equals(this.prefix)) this.prefix = null; this.localName = in.readUTF(); this.owner = in.readUTF(); this.name = in.readUTF(); this.types = (String[]) in.readObject(); }
// in java/org/apache/el/MethodExpressionImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.expr = in.readUTF(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } this.paramTypes = ReflectionUtil.toTypeArray(((String[]) in .readObject())); this.fnMapper = (FunctionMapper) in.readObject(); this.varMapper = (VariableMapper) in.readObject(); }
// in java/org/apache/el/MethodExpressionLiteral.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.expr = in.readUTF(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } this.paramTypes = ReflectionUtil.toTypeArray(((String[]) in .readObject())); }
// in java/org/apache/el/ValueExpressionLiteral.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.value = in.readObject(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } }
// in java/org/apache/el/ValueExpressionImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.expr = in.readUTF(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } this.fnMapper = (FunctionMapper) in.readObject(); this.varMapper = (VariableMapper) in.readObject(); }
// in java/org/apache/el/util/ReflectionUtil.java
public static Class<?> forName(String name) throws ClassNotFoundException { if (null == name || "".equals(name)) { return null; } Class<?> c = forNamePrimitive(name); if (c == null) { if (name.endsWith("[]")) { String nc = name.substring(0, name.length() - 2); c = Class.forName(nc, true, Thread.currentThread().getContextClassLoader()); c = Array.newInstance(c, 0).getClass(); } else { c = Class.forName(name, true, Thread.currentThread().getContextClassLoader()); } } return c; }
// in java/org/apache/el/util/ReflectionUtil.java
public static Class<?>[] toTypeArray(String[] s) throws ClassNotFoundException { if (s == null) return null; Class<?>[] c = new Class[s.length]; for (int i = 0; i < s.length; i++) { c[i] = forName(s[i]); } return c; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public Class<?> findClass(String name) throws ClassNotFoundException { if (log.isDebugEnabled()) log.debug(" findClass(" + name + ")"); // Cannot load anything from local repositories if class loader is stopped if (!started) { throw new ClassNotFoundException(name); } // (1) Permission to define this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { if (log.isTraceEnabled()) log.trace(" securityManager.checkPackageDefinition"); securityManager.checkPackageDefinition(name.substring(0,i)); } catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); } } } // Ask our superclass to locate this class, if possible // (throws ClassNotFoundException if it is not found) Class<?> clazz = null; try { if (log.isTraceEnabled()) log.trace(" findClassInternal(" + name + ")"); if (hasExternalRepositories && searchExternalFirst) { try { clazz = super.findClass(name); } catch(ClassNotFoundException cnfe) { // Ignore - will search internal repositories next } catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if ((clazz == null)) { try { clazz = findClassInternal(name); } catch(ClassNotFoundException cnfe) { if (!hasExternalRepositories || searchExternalFirst) { throw cnfe; } } catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if ((clazz == null) && hasExternalRepositories && !searchExternalFirst) { try { clazz = super.findClass(name); } catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if (clazz == null) { if (log.isDebugEnabled()) log.debug(" --> Returning ClassNotFoundException"); throw new ClassNotFoundException(name); } } catch (ClassNotFoundException e) { if (log.isTraceEnabled()) log.trace(" --> Passing on ClassNotFoundException"); throw e; } // Return the class we have located if (log.isTraceEnabled()) log.debug(" Returning class " + clazz); if (log.isTraceEnabled()) { ClassLoader cl; if (Globals.IS_SECURITY_ENABLED){ cl = AccessController.doPrivileged( new PrivilegedGetClassLoader(clazz)); } else { cl = clazz.getClassLoader(); } log.debug(" Loaded by " + cl.toString()); } return (clazz); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public Class<?> loadClass(String name) throws ClassNotFoundException { return (loadClass(name, false)); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (log.isDebugEnabled()) log.debug("loadClass(" + name + ", " + resolve + ")"); Class<?> clazz = null; // Log access to stopped classloader if (!started) { try { throw new IllegalStateException(); } catch (IllegalStateException e) { log.info(sm.getString("webappClassLoader.stopped", name), e); } } // (0) Check our previously loaded local class cache clazz = findLoadedClass0(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.1) Check our previously loaded class cache clazz = findLoadedClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.2) Try loading the class with the system class loader, to prevent // the webapp from overriding J2SE classes try { clazz = system.loadClass(name); if (clazz != null) { if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (0.5) Permission to access this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { securityManager.checkPackageAccess(name.substring(0,i)); } catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); } } } boolean delegateLoad = delegate || filter(name); // (1) Delegate to our parent if requested if (delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader1 " + parent); ClassLoader loader = parent; if (loader == null) loader = system; try { clazz = Class.forName(name, false, loader); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } // (2) Search local repositories if (log.isDebugEnabled()) log.debug(" Searching local repositories"); try { clazz = findClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from local repository"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (3) Delegate to parent unconditionally if (!delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader at end: " + parent); ClassLoader loader = parent; if (loader == null) loader = system; try { clazz = Class.forName(name, false, loader); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } throw new ClassNotFoundException(name); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
protected Class<?> findClassInternal(String name) throws ClassNotFoundException { if (!validate(name)) throw new ClassNotFoundException(name); String tempPath = name.replace('.', '/'); String classPath = tempPath + ".class"; ResourceEntry entry = null; if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, classPath); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, classPath); } if (entry == null) throw new ClassNotFoundException(name); Class<?> clazz = entry.loadedClass; if (clazz != null) return clazz; synchronized (this) { clazz = entry.loadedClass; if (clazz != null) return clazz; if (entry.binaryContent == null) throw new ClassNotFoundException(name); // Looking up the package String packageName = null; int pos = name.lastIndexOf('.'); if (pos != -1) packageName = name.substring(0, pos); Package pkg = null; if (packageName != null) { pkg = getPackage(packageName); // Define the package (if null) if (pkg == null) { try { if (entry.manifest == null) { definePackage(packageName, null, null, null, null, null, null, null); } else { definePackage(packageName, entry.manifest, entry.codeBase); } } catch (IllegalArgumentException e) { // Ignore: normal error due to dual definition of package } pkg = getPackage(packageName); } } if (securityManager != null) { // Checking sealing if (pkg != null) { boolean sealCheck = true; if (pkg.isSealed()) { sealCheck = pkg.isSealed(entry.codeBase); } else { sealCheck = (entry.manifest == null) || !isPackageSealed(packageName, entry.manifest); } if (!sealCheck) throw new SecurityException ("Sealing violation loading " + name + " : Package " + packageName + " is sealed."); } } try { clazz = defineClass(name, entry.binaryContent, 0, entry.binaryContent.length, new CodeSource(entry.codeBase, entry.certificates)); } catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); } entry.loadedClass = clazz; entry.binaryContent = null; entry.source = null; entry.codeBase = null; entry.manifest = null; entry.certificates = null; } return clazz; }
// in java/org/apache/catalina/tribes/group/RpcMessage.java
Override public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException { reply = in.readBoolean(); int length = in.readInt(); uuid = new byte[length]; in.readFully(uuid); length = in.readInt(); rpcId = new byte[length]; in.readFully(rpcId); message = (Serializable)in.readObject(); }
// in java/org/apache/catalina/tribes/group/RpcMessage.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { reply = true; int length = in.readInt(); uuid = new byte[length]; in.readFully(uuid); length = in.readInt(); rpcId = new byte[length]; in.readFully(rpcId); }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data) throws IOException, ClassNotFoundException, ClassCastException { return deserialize(data,0,data.length); }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data, int offset, int length) throws IOException, ClassNotFoundException, ClassCastException { return deserialize(data,offset,length,null); }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data, int offset, int length, ClassLoader[] cls) throws IOException, ClassNotFoundException, ClassCastException { invokecount.addAndGet(1); Object message = null; if ( cls == null ) cls = new ClassLoader[0]; if (data != null && length > 0) { InputStream instream = new ByteArrayInputStream(data,offset,length); ObjectInputStream stream = null; stream = (cls.length>0)? new ReplicationStream(instream,cls):new ObjectInputStream(instream); message = stream.readObject(); instream.close(); stream.close(); } if ( message == null ) { return null; } else if (message instanceof Serializable) return (Serializable) message; else { throw new ClassCastException("Message has the wrong class. It should implement Serializable, instead it is:"+message.getClass().getName()); } }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
Override public Class<?> resolveClass(ObjectStreamClass classDesc) throws ClassNotFoundException, IOException { String name = classDesc.getName(); try { return resolveClass(name); } catch (ClassNotFoundException e) { return super.resolveClass(classDesc); } }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
public Class<?> resolveClass(String name) throws ClassNotFoundException { boolean tryRepFirst = name.startsWith("org.apache.catalina.tribes"); try { if (tryRepFirst) return findReplicationClass(name); else return findExternalClass(name); } catch (Exception x) { if (tryRepFirst) return findExternalClass(name); else return findReplicationClass(name); } }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
Override protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { ClassLoader latestLoader = (classLoaders!=null && classLoaders.length==0)?null:classLoaders[0]; ClassLoader nonPublicLoader = null; boolean hasNonPublicInterface = false; // define proxy in class loader of non-public interface(s), if any Class<?>[] classObjs = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { Class<?> cl = this.resolveClass(interfaces[i]); if (latestLoader==null) latestLoader = cl.getClassLoader(); if ((cl.getModifiers() & Modifier.PUBLIC) == 0) { if (hasNonPublicInterface) { if (nonPublicLoader != cl.getClassLoader()) { throw new IllegalAccessError( "conflicting non-public interface class loaders"); } } else { nonPublicLoader = cl.getClassLoader(); hasNonPublicInterface = true; } } classObjs[i] = cl; } try { return Proxy.getProxyClass(hasNonPublicInterface ? nonPublicLoader : latestLoader, classObjs); } catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); } }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
public Class<?> findReplicationClass(String name) throws ClassNotFoundException { Class<?> clazz = Class.forName(name, false, getClass().getClassLoader()); return clazz; }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
public Class<?> findExternalClass(String name) throws ClassNotFoundException { ClassNotFoundException cnfe = null; for (int i=0; i<classLoaders.length; i++ ) { try { Class<?> clazz = Class.forName(name, false, classLoaders[i]); return clazz; } catch ( ClassNotFoundException x ) { cnfe = x; } } if ( cnfe != null ) throw cnfe; else throw new ClassNotFoundException(name); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public void deserialize(ClassLoader[] cls) throws IOException, ClassNotFoundException { key(cls); value(cls); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public Serializable key(ClassLoader[] cls) throws IOException, ClassNotFoundException { if ( key!=null ) return key; if ( keydata == null || keydata.length == 0 ) return null; key = XByteBuffer.deserialize(keydata,0,keydata.length,cls); keydata = null; return key; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public Serializable value(ClassLoader[] cls) throws IOException, ClassNotFoundException { if ( value!=null ) return value; if ( valuedata == null || valuedata.length == 0 ) return null; value = XByteBuffer.deserialize(valuedata,0,valuedata.length,cls); valuedata = null; return value; }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { int length = in.readInt(); byte[] message = new byte[length]; in.readFully(message); getMember(message,this); }
// in java/org/apache/catalina/session/StandardManager.java
Override public void load() throws ClassNotFoundException, IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ AccessController.doPrivileged( new PrivilegedDoLoad() ); } catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof ClassNotFoundException){ throw (ClassNotFoundException)exception; } else if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in load() " + exception); } } else { doLoad(); } }
// in java/org/apache/catalina/session/StandardManager.java
protected void doLoad() throws ClassNotFoundException, IOException { if (log.isDebugEnabled()) log.debug("Start: Loading persisted sessions"); // Initialize our internal data structures sessions.clear(); // Open an input stream to the specified pathname, if any File file = file(); if (file == null) return; if (log.isDebugEnabled()) log.debug(sm.getString("standardManager.loading", pathname)); FileInputStream fis = null; BufferedInputStream bis = null; ObjectInputStream ois = null; Loader loader = null; ClassLoader classLoader = null; try { fis = new FileInputStream(file.getAbsolutePath()); bis = new BufferedInputStream(fis); if (container != null) loader = container.getLoader(); if (loader != null) classLoader = loader.getClassLoader(); if (classLoader != null) { if (log.isDebugEnabled()) log.debug("Creating custom object input stream for class loader "); ois = new CustomObjectInputStream(bis, classLoader); } else { if (log.isDebugEnabled()) log.debug("Creating standard object input stream"); ois = new ObjectInputStream(bis); } } catch (FileNotFoundException e) { if (log.isDebugEnabled()) log.debug("No persisted data file found"); return; } catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } throw e; } // Load the previously unloaded active sessions synchronized (sessions) { try { Integer count = (Integer) ois.readObject(); int n = count.intValue(); if (log.isDebugEnabled()) log.debug("Loading " + n + " persisted sessions"); for (int i = 0; i < n; i++) { StandardSession session = getNewSession(); session.readObjectData(ois); session.setManager(this); sessions.put(session.getIdInternal(), session); session.activate(); if (!session.isValidInternal()) { // If session is already invalid, // expire session to prevent memory leak. session.setValid(true); session.expire(); } sessionCounter++; } } catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; } catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; } finally { // Close the input stream try { ois.close(); } catch (IOException f) { // ignored } // Delete the persistent storage file if (file.exists() ) file.delete(); } } if (log.isDebugEnabled()) log.debug("Finish: Loading persisted sessions"); }
// in java/org/apache/catalina/session/JDBCStore.java
Override public Session load(String id) throws ClassNotFoundException, IOException { ResultSet rst = null; StandardSession _session = null; Loader loader = null; ClassLoader classLoader = null; ObjectInputStream ois = null; BufferedInputStream bis = null; Container container = manager.getContainer(); synchronized (this) { int numberOfTries = 2; while (numberOfTries > 0) { Connection _conn = getConnection(); if (_conn == null) { return (null); } try { if (preparedLoadSql == null) { String loadSql = "SELECT " + sessionIdCol + ", " + sessionDataCol + " FROM " + sessionTable + " WHERE " + sessionIdCol + " = ? AND " + sessionAppCol + " = ?"; preparedLoadSql = _conn.prepareStatement(loadSql); } preparedLoadSql.setString(1, id); preparedLoadSql.setString(2, getName()); rst = preparedLoadSql.executeQuery(); if (rst.next()) { bis = new BufferedInputStream(rst.getBinaryStream(2)); if (container != null) { loader = container.getLoader(); } if (loader != null) { classLoader = loader.getClassLoader(); } if (classLoader != null) { ois = new CustomObjectInputStream(bis, classLoader); } else { ois = new ObjectInputStream(bis); } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName() + ".loading", id, sessionTable)); } _session = (StandardSession) manager.createEmptySession(); _session.readObjectData(ois); _session.setManager(manager); } else if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(getStoreName() + ": No persisted data object found"); } // Break out after the finally block numberOfTries = 0; } catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); } finally { try { if (rst != null) { rst.close(); } } catch (SQLException e) { // Ignore } if (ois != null) { try { ois.close(); } catch (IOException e) { // Ignore } } release(_conn); } numberOfTries--; } } return (_session); }
// in java/org/apache/catalina/session/FileStore.java
Override public Session load(String id) throws ClassNotFoundException, IOException { // Open an input stream to the specified pathname, if any File file = file(id); if (file == null) { return (null); } if (! file.exists()) { return (null); } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName()+".loading", id, file.getAbsolutePath())); } FileInputStream fis = null; BufferedInputStream bis = null; ObjectInputStream ois = null; Loader loader = null; ClassLoader classLoader = null; try { fis = new FileInputStream(file.getAbsolutePath()); bis = new BufferedInputStream(fis); Container container = manager.getContainer(); if (container != null) loader = container.getLoader(); if (loader != null) classLoader = loader.getClassLoader(); if (classLoader != null) ois = new CustomObjectInputStream(bis, classLoader); else ois = new ObjectInputStream(bis); } catch (FileNotFoundException e) { if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug("No persisted data file found"); return (null); } catch (IOException e) { if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } throw e; } try { StandardSession session = (StandardSession) manager.createEmptySession(); session.readObjectData(ois); session.setManager(manager); return (session); } finally { // Close the input stream try { ois.close(); } catch (IOException f) { // Ignore } } }
// in java/org/apache/catalina/session/StandardSession.java
public void readObjectData(ObjectInputStream stream) throws ClassNotFoundException, IOException { readObject(stream); }
// in java/org/apache/catalina/session/StandardSession.java
protected void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException { // Deserialize the scalar instance variables (except Manager) authType = null; // Transient only creationTime = ((Long) stream.readObject()).longValue(); lastAccessedTime = ((Long) stream.readObject()).longValue(); maxInactiveInterval = ((Integer) stream.readObject()).intValue(); isNew = ((Boolean) stream.readObject()).booleanValue(); isValid = ((Boolean) stream.readObject()).booleanValue(); thisAccessedTime = ((Long) stream.readObject()).longValue(); principal = null; // Transient only // setId((String) stream.readObject()); id = (String) stream.readObject(); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug ("readObject() loading session " + id); // Deserialize the attribute count and attribute values if (attributes == null) attributes = new ConcurrentHashMap<String, Object>(); int n = ((Integer) stream.readObject()).intValue(); boolean isValidSave = isValid; isValid = true; for (int i = 0; i < n; i++) { String name = (String) stream.readObject(); Object value = stream.readObject(); if ((value instanceof String) && (value.equals(NOT_SERIALIZED))) continue; if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug(" loading attribute '" + name + "' with value '" + value + "'"); attributes.put(name, value); } isValid = isValidSave; if (listeners == null) { listeners = new ArrayList<SessionListener>(); } if (notes == null) { notes = new Hashtable<String, Object>(); } }
// in java/org/apache/catalina/ha/session/SerializablePrincipal.java
public static GenericPrincipal readPrincipal(ObjectInput in) throws IOException, ClassNotFoundException { String name = in.readUTF(); boolean hasPwd = in.readBoolean(); String pwd = null; if ( hasPwd ) pwd = in.readUTF(); int size = in.readInt(); String[] roles = new String[size]; for ( int i=0; i<size; i++ ) roles[i] = in.readUTF(); Principal userPrincipal = null; boolean hasUserPrincipal = in.readBoolean(); if (hasUserPrincipal) { try { userPrincipal = (Principal) in.readObject(); } catch (ClassNotFoundException e) { log.error(sm.getString( "serializablePrincipal.readPrincipal.cnfe"), e); throw e; } } return new GenericPrincipal(name,pwd,Arrays.asList(roles), userPrincipal); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void applyDiff(byte[] diff, int offset, int length) throws IOException, ClassNotFoundException { try { lock(); ReplicationStream stream = ( (ClusterManager) getManager()).getReplicationStream(diff, offset, length); ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); try { ClassLoader[] loaders = getClassLoaders(); if (loaders != null && loaders.length > 0) Thread.currentThread().setContextClassLoader(loaders[0]); getDeltaRequest().readExternal(stream); getDeltaRequest().execute(this, ((ClusterManager)getManager()).isNotifyListenersOnReplication()); } finally { Thread.currentThread().setContextClassLoader(contextLoader); } }finally { unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException { try { lock(); readObjectData(in); }finally{ unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void readObjectData(ObjectInputStream stream) throws ClassNotFoundException, IOException { readObject((ObjectInput)stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
public void readObjectData(ObjectInput stream) throws ClassNotFoundException, IOException { readObject(stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override protected void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException { readObject((ObjectInput)stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
private void readObject(ObjectInput stream) throws ClassNotFoundException, IOException { // Deserialize the scalar instance variables (except Manager) authType = null; // Transient only creationTime = ( (Long) stream.readObject()).longValue(); lastAccessedTime = ( (Long) stream.readObject()).longValue(); maxInactiveInterval = ( (Integer) stream.readObject()).intValue(); isNew = ( (Boolean) stream.readObject()).booleanValue(); isValid = ( (Boolean) stream.readObject()).booleanValue(); thisAccessedTime = ( (Long) stream.readObject()).longValue(); version = ( (Long) stream.readObject()).longValue(); boolean hasPrincipal = stream.readBoolean(); principal = null; if (hasPrincipal) { principal = SerializablePrincipal.readPrincipal(stream); } // setId((String) stream.readObject()); id = (String) stream.readObject(); if (log.isDebugEnabled()) log.debug(sm.getString("deltaSession.readSession", id)); // Deserialize the attribute count and attribute values if (attributes == null) attributes = new ConcurrentHashMap<String, Object>(); int n = ( (Integer) stream.readObject()).intValue(); boolean isValidSave = isValid; isValid = true; for (int i = 0; i < n; i++) { String name = (String) stream.readObject(); Object value = stream.readObject(); if ( (value instanceof String) && (value.equals(NOT_SERIALIZED))) continue; attributes.put(name, value); } isValid = isValidSave; if (listeners == null) { ArrayList<SessionListener> arrayList = new ArrayList<SessionListener>(); listeners = arrayList; } if (notes == null) { notes = new Hashtable<String,Object>(); } activate(); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
Override public void readExternal(java.io.ObjectInput in) throws IOException,ClassNotFoundException { //sessionId - String //recordAll - boolean //size - int //AttributeInfo - in an array reset(); sessionId = in.readUTF(); recordAllActions = in.readBoolean(); int cnt = in.readInt(); if (actions == null) actions = new LinkedList<AttributeInfo>(); else actions.clear(); for (int i = 0; i < cnt; i++) { AttributeInfo info = null; if (this.actionPool.size() > 0) { try { info = actionPool.removeFirst(); } catch ( Exception x ) { log.error("Unable to remove element",x); info = new AttributeInfo(); } } else { info = new AttributeInfo(); } info.readExternal(in); actions.addLast(info); }//for }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
Override public void readExternal(java.io.ObjectInput in ) throws IOException,ClassNotFoundException { //type - int //action - int //name - String //hasvalue - boolean //value - object type = in.readInt(); action = in.readInt(); name = in.readUTF(); boolean hasValue = in.readBoolean(); if ( hasValue ) value = in.readObject(); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected DeltaRequest deserializeDeltaRequest(DeltaSession session, byte[] data) throws ClassNotFoundException, IOException { try { session.lock(); ReplicationStream ois = getReplicationStream(data); session.getDeltaRequest().readExternal(ois); ois.close(); return session.getDeltaRequest(); }finally { session.unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void deserializeSessions(byte[] data) throws ClassNotFoundException,IOException { // Initialize our internal data structures //sessions.clear(); //should not do this // Open an input stream to the specified pathname, if any ClassLoader originalLoader = Thread.currentThread().getContextClassLoader(); ObjectInputStream ois = null; // Load the previously unloaded active sessions try { ois = getReplicationStream(data); Integer count = (Integer) ois.readObject(); int n = count.intValue(); for (int i = 0; i < n; i++) { DeltaSession session = (DeltaSession) createEmptySession(); session.readObjectData(ois); session.setManager(this); session.setValid(true); session.setPrimarySession(false); //in case the nodes in the cluster are out of //time synch, this will make sure that we have the //correct timestamp, isValid returns true, cause // accessCount=1 session.access(); //make sure that the session gets ready to expire if // needed session.setAccessCount(0); session.resetDeltaRequest(); // FIXME How inform other session id cache like SingleSignOn // increment sessionCounter to correct stats report if (findSession(session.getIdInternal()) == null ) { sessionCounter++; } else { sessionReplaceCounter++; // FIXME better is to grap this sessions again ! if (log.isWarnEnabled()) log.warn(sm.getString("deltaManager.loading.existing.session",session.getIdInternal())); } add(session); if (notifySessionListenersOnReplication) { session.tellNew(); } } } catch (ClassNotFoundException e) { log.error(sm.getString("deltaManager.loading.cnfe", e), e); throw e; } catch (IOException e) { log.error(sm.getString("deltaManager.loading.ioe", e), e); throw e; } finally { // Close the input stream try { if (ois != null) ois.close(); } catch (IOException f) { // ignored } ois = null; if (originalLoader != null) Thread.currentThread().setContextClassLoader(originalLoader); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleSESSION_DELTA(SessionMessage msg, Member sender) throws IOException, ClassNotFoundException { counterReceive_EVT_SESSION_DELTA++; byte[] delta = msg.getSession(); DeltaSession session = (DeltaSession) findSession(msg.getSessionID()); if (session != null) { if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.delta",getName(), msg.getSessionID())); try { session.lock(); DeltaRequest dreq = deserializeDeltaRequest(session, delta); dreq.execute(session, isNotifyListenersOnReplication()); session.setPrimarySession(false); }finally { session.unlock(); } } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleALL_SESSION_DATA(SessionMessage msg,Member sender) throws ClassNotFoundException, IOException { counterReceive_EVT_ALL_SESSION_DATA++; if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataBegin",getName())); byte[] data = msg.getSession(); deserializeSessions(data); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataAfter",getName())); //stateTransferred = true; }
// in java/org/apache/catalina/core/AprLifecycleListener.java
private static void terminateAPR() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { String methodName = "terminate"; Method method = Class.forName("org.apache.tomcat.jni.Library") .getMethod(methodName, (Class [])null); method.invoke(null, (Object []) null); aprAvailable = false; aprInitialized = false; sslInitialized = false; // Well we cleaned the pool in terminate. sslAvailable = false; // Well we cleaned the pool in terminate. fipsModeActive = false; }
// in java/org/apache/catalina/core/AprLifecycleListener.java
private static void initializeSSL() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { if ("off".equalsIgnoreCase(SSLEngine)) { return; } if (sslInitialized) { //only once per VM return; } sslInitialized = true; String methodName = "randSet"; Class<?> paramTypes[] = new Class[1]; paramTypes[0] = String.class; Object paramValues[] = new Object[1]; paramValues[0] = SSLRandomSeed; Class<?> clazz = Class.forName("org.apache.tomcat.jni.SSL"); Method method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); methodName = "initialize"; paramValues[0] = "on".equalsIgnoreCase(SSLEngine)?null:SSLEngine; method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); if("on".equalsIgnoreCase(FIPSMode)) { log.info(sm.getString("aprListener.initializingFIPS")); int result = SSL.fipsModeSet(1); // success is defined as return value = 1 if(1 == result) { fipsModeActive = true; log.info(sm.getString("aprListener.initializeFIPSSuccess")); } else { // This case should be handled by the native method, // but we'll make absolutely sure, here. String message = sm.getString("aprListener.initializeFIPSFailed"); log.error(message); throw new IllegalStateException(message); } } log.info(sm.getString("aprListener.initializedOpenSSL", SSL.versionString())); sslAvailable = true; }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
Filter getFilter() throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { // Return the existing filter instance, if any if (this.filter != null) return (this.filter); // Identify the class loader we will be using String filterClass = filterDef.getFilterClass(); this.filter = (Filter) getInstanceManager().newInstance(filterClass); initFilter(); return (this.filter); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
void setFilterDef(FilterDef filterDef) throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { this.filterDef = filterDef; if (filterDef == null) { // Release any previously allocated filter instance if (this.filter != null){ if (Globals.IS_SECURITY_ENABLED) { try{ SecurityUtil.doAsPrivilege("destroy", filter); } catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); } SecurityUtil.remove(filter); } else { filter.destroy(); } if (!context.getIgnoreAnnotations()) { try { ((StandardContext) context).getInstanceManager().destroyInstance(this.filter); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); } } } this.filter = null; } else { // Allocate a new filter instance if necessary if (filterDef.getFilter() == null) { getFilter(); } } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { Class<?> clazz = loadClassMaybePrivileged(className, classLoader); return newInstance(clazz.newInstance(), clazz); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(final String className, final ClassLoader classLoader) throws IllegalAccessException, NamingException, InvocationTargetException, InstantiationException, ClassNotFoundException { Class<?> clazz = classLoader.loadClass(className); return newInstance(clazz.newInstance(), clazz); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected Class<?> loadClassMaybePrivileged(final String className, final ClassLoader classLoader) throws ClassNotFoundException { Class<?> clazz; if (SecurityUtil.isPackageProtectionEnabled()) { try { clazz = AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() { @Override public Class<?> run() throws Exception { return loadClass(className, classLoader); } }); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected Class<?> loadClass(String className, ClassLoader classLoader) throws ClassNotFoundException { if (className.startsWith("org.apache.catalina")) { return containerClassLoader.loadClass(className); } try { Class<?> clazz = containerClassLoader.loadClass(className); if (ContainerServlet.class.isAssignableFrom(clazz)) { return clazz; } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } return classLoader.loadClass(className); }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
Override public Class<?> resolveClass(ObjectStreamClass classDesc) throws ClassNotFoundException, IOException { try { return Class.forName(classDesc.getName(), false, classLoader); } catch (ClassNotFoundException e) { try { // Try also the superclass because of primitive types return super.resolveClass(classDesc); } catch (ClassNotFoundException e2) { // Rethrow original exception, as it can have more information // about why the class was not found. BZ 48007 throw e; } } }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
Override protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { Class<?>[] cinterfaces = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) cinterfaces[i] = classLoader.loadClass(interfaces[i]); try { return Proxy.getProxyClass(classLoader, cinterfaces); } catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); } }
(Domain) ChannelException 16
              
// in java/org/apache/catalina/tribes/group/GroupChannel.java
Override public UniqueId send(Member[] destination, Serializable msg, int options, ErrorHandler handler) throws ChannelException { if ( msg == null ) throw new ChannelException("Cant send a NULL message"); XByteBuffer buffer = null; try { if ( destination == null || destination.length == 0) throw new ChannelException("No destination given"); ChannelData data = new ChannelData(true);//generates a unique Id data.setAddress(getLocalMember(false)); data.setTimestamp(System.currentTimeMillis()); byte[] b = null; if ( msg instanceof ByteMessage ){ b = ((ByteMessage)msg).getMessage(); options = options | SEND_OPTIONS_BYTE_MESSAGE; } else { b = XByteBuffer.serialize(msg); options = options & (~SEND_OPTIONS_BYTE_MESSAGE); } data.setOptions(options); //XByteBuffer buffer = new XByteBuffer(b.length+128,false); buffer = BufferPool.getBufferPool().getBuffer(b.length+128, false); buffer.append(b,0,b.length); data.setMessage(buffer); InterceptorPayload payload = null; if ( handler != null ) { payload = new InterceptorPayload(); payload.setErrorHandler(handler); } getFirstInterceptor().sendMessage(destination, data, payload); if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("GroupChannel - Sent msg:" + new UniqueId(data.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " to "+Arrays.toNameString(destination)); Logs.MESSAGES.trace("GroupChannel - Send Message:" + new UniqueId(data.getUniqueId()) + " is " +msg); } return new UniqueId(data.getUniqueId()); }catch ( Exception x ) { if ( x instanceof ChannelException ) throw (ChannelException)x; throw new ChannelException(x); } finally { if ( buffer != null ) BufferPool.getBufferPool().returnBuffer(buffer); } }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
protected synchronized void setupDefaultStack() throws ChannelException { if ( getFirstInterceptor() != null && ((getFirstInterceptor().getNext() instanceof ChannelCoordinator))) { ChannelInterceptor interceptor = null; Class<?> clazz = null; try { clazz = Class.forName("org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor", true,GroupChannel.class.getClassLoader()); clazz.newInstance(); } catch ( Throwable x ) { clazz = MessageDispatchInterceptor.class; }//catch try { interceptor = (ChannelInterceptor) clazz.newInstance(); } catch (Exception x) { throw new ChannelException("Unable to add MessageDispatchInterceptor to interceptor chain.",x); } this.addInterceptor(interceptor); } }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
protected void checkOptionFlags() throws ChannelException { StringBuilder conflicts = new StringBuilder(); ChannelInterceptor first = interceptors; while ( first != null ) { int flag = first.getOptionFlag(); if ( flag != 0 ) { ChannelInterceptor next = first.getNext(); while ( next != null ) { int nflag = next.getOptionFlag(); if (nflag!=0 && (((flag & nflag) == flag ) || ((flag & nflag) == nflag)) ) { conflicts.append("["); conflicts.append(first.getClass().getName()); conflicts.append(":"); conflicts.append(flag); conflicts.append(" == "); conflicts.append(next.getClass().getName()); conflicts.append(":"); conflicts.append(nflag); conflicts.append("] "); }//end if next = next.getNext(); }//while }//end if first = first.getNext(); }//while if ( conflicts.length() > 0 ) throw new ChannelException("Interceptor option flag conflict: "+conflicts.toString()); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
protected synchronized void internalStart(int svc) throws ChannelException { try { boolean valid = false; //make sure we don't pass down any flags that are unrelated to the bottom layer svc = svc & Channel.DEFAULT; if (startLevel == Channel.DEFAULT) return; //we have already started up all components if (svc == 0 ) return;//nothing to start if (svc == (svc & startLevel)) throw new ChannelException("Channel already started for level:"+svc); //must start the receiver first so that we can coordinate the port it //listens to with the local membership settings if ( Channel.SND_RX_SEQ==(svc & Channel.SND_RX_SEQ) ) { clusterReceiver.setMessageListener(this); clusterReceiver.start(); //synchronize, big time FIXME membershipService.setLocalMemberProperties(getClusterReceiver().getHost(), getClusterReceiver().getPort(), getClusterReceiver().getSecurePort(), getClusterReceiver().getUdpPort()); valid = true; } if ( Channel.SND_TX_SEQ==(svc & Channel.SND_TX_SEQ) ) { clusterSender.start(); valid = true; } if ( Channel.MBR_RX_SEQ==(svc & Channel.MBR_RX_SEQ) ) { membershipService.setMembershipListener(this); if (membershipService instanceof McastService) { ((McastService)membershipService).setMessageListener(this); } membershipService.start(MembershipService.MBR_RX); valid = true; } if ( Channel.MBR_TX_SEQ==(svc & Channel.MBR_TX_SEQ) ) { membershipService.start(MembershipService.MBR_TX); valid = true; } if ( !valid) { throw new IllegalArgumentException("Invalid start level, valid levels are:SND_RX_SEQ,SND_TX_SEQ,MBR_TX_SEQ,MBR_RX_SEQ"); } startLevel = (startLevel | svc); }catch ( ChannelException cx ) { throw cx; }catch ( Exception x ) { throw new ChannelException(x); } }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
protected synchronized void internalStop(int svc) throws ChannelException { try { //make sure we don't pass down any flags that are unrelated to the bottom layer svc = svc & Channel.DEFAULT; if (startLevel == 0) return; //we have already stopped up all components if (svc == 0 ) return;//nothing to stop boolean valid = false; if ( Channel.SND_RX_SEQ==(svc & Channel.SND_RX_SEQ) ) { clusterReceiver.stop(); clusterReceiver.setMessageListener(null); valid = true; } if ( Channel.SND_TX_SEQ==(svc & Channel.SND_TX_SEQ) ) { clusterSender.stop(); valid = true; } if ( Channel.MBR_RX_SEQ==(svc & Channel.MBR_RX_SEQ) ) { membershipService.stop(MembershipService.MBR_RX); membershipService.setMembershipListener(null); valid = true; } if ( Channel.MBR_TX_SEQ==(svc & Channel.MBR_TX_SEQ) ) { valid = true; membershipService.stop(MembershipService.MBR_TX); } if ( !valid) { throw new IllegalArgumentException("Invalid start level, valid levels are:SND_RX_SEQ,SND_TX_SEQ,MBR_TX_SEQ,MBR_RX_SEQ"); } startLevel = (startLevel & (~svc)); }catch ( Exception x ) { throw new ChannelException(x); } finally { } }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { try { byte[] data = compress(msg.getMessage().getBytes()); msg.getMessage().trim(msg.getMessage().getLength()); msg.getMessage().append(data,0,data.length); getNext().sendMessage(destination, msg, payload); } catch ( IOException x ) { log.error("Unable to compress byte contents"); throw new ChannelException(x); } }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { boolean async = (msg.getOptions() & Channel.SEND_OPTIONS_ASYNCHRONOUS) == Channel.SEND_OPTIONS_ASYNCHRONOUS; if ( async && run ) { if ( (getCurrentSize()+msg.getMessage().getLength()) > maxQueueSize ) { if ( alwaysSend ) { super.sendMessage(destination,msg,payload); return; } else { throw new ChannelException("Asynchronous queue is full, reached its limit of " + maxQueueSize +" bytes, current:" + getCurrentSize() + " bytes."); }//end if }//end if //add to queue if ( useDeepClone ) msg = (ChannelMessage)msg.deepclone(); if (!addToQueue(msg, destination, payload) ) { throw new ChannelException("Unable to add the message to the async queue, queue bug?"); } addAndGetCurrentSize(msg.getMessage().getLength()); } else { super.sendMessage(destination, msg, payload); } }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
Override public void sendMessage(Member[] destination, ChannelMessage message) throws ChannelException { if ( !connected ) throw new ChannelException("Sender not connected."); ParallelNioSender sender = (ParallelNioSender)getSender(); if (sender == null) { ChannelException cx = new ChannelException("Unable to retrieve a data sender, time out error."); for (int i = 0; i < destination.length; i++) cx.addFaultyMember(destination[i], new NullPointerException("Unable to retrieve a sender from the sender pool")); throw cx; } else { try { sender.sendMessage(destination, message); sender.keepalive(); } catch (ChannelException x) { sender.disconnect(); throw x; } finally { returnSender(sender); if (!connected) disconnect(); } } }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
Override public synchronized void sendMessage(Member[] destination, ChannelMessage msg) throws ChannelException { long start = System.currentTimeMillis(); this.setUdpBased((msg.getOptions()&Channel.SEND_OPTIONS_UDP) == Channel.SEND_OPTIONS_UDP); byte[] data = XByteBuffer.createDataPackage((ChannelData)msg); NioSender[] senders = setupForSend(destination); connect(senders); setData(senders,data); int remaining = senders.length; ChannelException cx = null; try { //loop until complete, an error happens, or we timeout long delta = System.currentTimeMillis() - start; boolean waitForAck = (Channel.SEND_OPTIONS_USE_ACK & msg.getOptions()) == Channel.SEND_OPTIONS_USE_ACK; while ( (remaining>0) && (delta<getTimeout()) ) { try { remaining -= doLoop(selectTimeout, getMaxRetryAttempts(),waitForAck,msg); } catch (Exception x ) { if (log.isTraceEnabled()) log.trace("Error sending message", x); int faulty = (cx == null)?0:cx.getFaultyMembers().length; if ( cx == null ) { if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException("Parallel NIO send failed.", x); } else { if (x instanceof ChannelException) cx.addFaultyMember( ( (ChannelException) x).getFaultyMembers()); } //count down the remaining on an error if (faulty<cx.getFaultyMembers().length) remaining -= (cx.getFaultyMembers().length-faulty); } //bail out if all remaining senders are failing if ( cx != null && cx.getFaultyMembers().length == remaining ) throw cx; delta = System.currentTimeMillis() - start; } if ( remaining > 0 ) { //timeout has occurred ChannelException cxtimeout = new ChannelException("Operation has timed out("+getTimeout()+" ms.)."); if ( cx==null ) cx = new ChannelException("Operation has timed out("+getTimeout()+" ms.)."); for (int i=0; i<senders.length; i++ ) { if (!senders[i].isComplete() ) cx.addFaultyMember(senders[i].getDestination(),cxtimeout); } throw cx; } else if ( cx != null ) { //there was an error throw cx; } } catch (Exception x ) { try { this.disconnect(); } catch (Exception e) {/*Ignore*/} if ( x instanceof ChannelException ) throw (ChannelException)x; else throw new ChannelException(x); } }
// in java/org/apache/catalina/tribes/membership/McastService.java
Override public void broadcast(ChannelMessage message) throws ChannelException { if (impl==null || (impl.startLevel & Channel.MBR_TX_SEQ)!=Channel.MBR_TX_SEQ ) throw new ChannelException("Multicast send is not started or enabled."); byte[] data = XByteBuffer.createDataPackage((ChannelData)message); if (data.length>McastServiceImpl.MAX_PACKET_SIZE) { throw new ChannelException("Packet length["+data.length+"] exceeds max packet size of "+McastServiceImpl.MAX_PACKET_SIZE+" bytes."); } DatagramPacket packet = new DatagramPacket(data,0,data.length); try { impl.send(false, packet); } catch (Exception x) { throw new ChannelException(x); } }
7
              
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { if ( x instanceof ChannelException ) throw (ChannelException)x; throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch (Exception x) { throw new ChannelException("Unable to add MessageDispatchInterceptor to interceptor chain.",x); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( Exception x ) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( Exception x ) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
catch ( IOException x ) { log.error("Unable to compress byte contents"); throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x ) { try { this.disconnect(); } catch (Exception e) {/*Ignore*/} if ( x instanceof ChannelException ) throw (ChannelException)x; else throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch (Exception x) { throw new ChannelException(x); }
58
              
// in java/org/apache/catalina/tribes/group/GroupChannel.java
Override public UniqueId send(Member[] destination, Serializable msg, int options) throws ChannelException { return send(destination,msg,options,null); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
Override public UniqueId send(Member[] destination, Serializable msg, int options, ErrorHandler handler) throws ChannelException { if ( msg == null ) throw new ChannelException("Cant send a NULL message"); XByteBuffer buffer = null; try { if ( destination == null || destination.length == 0) throw new ChannelException("No destination given"); ChannelData data = new ChannelData(true);//generates a unique Id data.setAddress(getLocalMember(false)); data.setTimestamp(System.currentTimeMillis()); byte[] b = null; if ( msg instanceof ByteMessage ){ b = ((ByteMessage)msg).getMessage(); options = options | SEND_OPTIONS_BYTE_MESSAGE; } else { b = XByteBuffer.serialize(msg); options = options & (~SEND_OPTIONS_BYTE_MESSAGE); } data.setOptions(options); //XByteBuffer buffer = new XByteBuffer(b.length+128,false); buffer = BufferPool.getBufferPool().getBuffer(b.length+128, false); buffer.append(b,0,b.length); data.setMessage(buffer); InterceptorPayload payload = null; if ( handler != null ) { payload = new InterceptorPayload(); payload.setErrorHandler(handler); } getFirstInterceptor().sendMessage(destination, data, payload); if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("GroupChannel - Sent msg:" + new UniqueId(data.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " to "+Arrays.toNameString(destination)); Logs.MESSAGES.trace("GroupChannel - Send Message:" + new UniqueId(data.getUniqueId()) + " is " +msg); } return new UniqueId(data.getUniqueId()); }catch ( Exception x ) { if ( x instanceof ChannelException ) throw (ChannelException)x; throw new ChannelException(x); } finally { if ( buffer != null ) BufferPool.getBufferPool().returnBuffer(buffer); } }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
protected synchronized void setupDefaultStack() throws ChannelException { if ( getFirstInterceptor() != null && ((getFirstInterceptor().getNext() instanceof ChannelCoordinator))) { ChannelInterceptor interceptor = null; Class<?> clazz = null; try { clazz = Class.forName("org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor", true,GroupChannel.class.getClassLoader()); clazz.newInstance(); } catch ( Throwable x ) { clazz = MessageDispatchInterceptor.class; }//catch try { interceptor = (ChannelInterceptor) clazz.newInstance(); } catch (Exception x) { throw new ChannelException("Unable to add MessageDispatchInterceptor to interceptor chain.",x); } this.addInterceptor(interceptor); } }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
protected void checkOptionFlags() throws ChannelException { StringBuilder conflicts = new StringBuilder(); ChannelInterceptor first = interceptors; while ( first != null ) { int flag = first.getOptionFlag(); if ( flag != 0 ) { ChannelInterceptor next = first.getNext(); while ( next != null ) { int nflag = next.getOptionFlag(); if (nflag!=0 && (((flag & nflag) == flag ) || ((flag & nflag) == nflag)) ) { conflicts.append("["); conflicts.append(first.getClass().getName()); conflicts.append(":"); conflicts.append(flag); conflicts.append(" == "); conflicts.append(next.getClass().getName()); conflicts.append(":"); conflicts.append(nflag); conflicts.append("] "); }//end if next = next.getNext(); }//while }//end if first = first.getNext(); }//while if ( conflicts.length() > 0 ) throw new ChannelException("Interceptor option flag conflict: "+conflicts.toString()); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
Override public synchronized void start(int svc) throws ChannelException { setupDefaultStack(); if (optionCheck) checkOptionFlags(); super.start(svc); if ( hbthread == null && heartbeat ) { hbthread = new HeartbeatThread(this,heartbeatSleeptime); hbthread.start(); } }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
Override public synchronized void stop(int svc) throws ChannelException { if (hbthread != null) { hbthread.stopHeartbeat(); hbthread = null; } super.stop(svc); }
// in java/org/apache/catalina/tribes/group/RpcChannel.java
public Response[] send(Member[] destination, Serializable message, int rpcOptions, int channelOptions, long timeout) throws ChannelException { if ( destination==null || destination.length == 0 ) return new Response[0]; //avoid dead lock int sendOptions = channelOptions & ~Channel.SEND_OPTIONS_SYNCHRONIZED_ACK; RpcCollectorKey key = new RpcCollectorKey(UUIDGenerator.randomUUID(false)); RpcCollector collector = new RpcCollector(key,rpcOptions,destination.length,timeout); try { synchronized (collector) { if ( rpcOptions != NO_REPLY ) responseMap.put(key, collector); RpcMessage rmsg = new RpcMessage(rpcId, key.id, message); channel.send(destination, rmsg, sendOptions); if ( rpcOptions != NO_REPLY ) collector.wait(timeout); } } catch ( InterruptedException ix ) { Thread.currentThread().interrupt(); }finally { responseMap.remove(key); } return collector.getResponses(); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { if ( destination == null ) destination = membershipService.getMembers(); if ((msg.getOptions()&Channel.SEND_OPTIONS_MULTICAST) == Channel.SEND_OPTIONS_MULTICAST) { membershipService.broadcast(msg); } else { clusterSender.sendMessage(msg,destination); } if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("ChannelCoordinator - Sent msg:" + new UniqueId(msg.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " to "+Arrays.toNameString(destination)); } }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
Override public void start(int svc) throws ChannelException { this.internalStart(svc); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
Override public void stop(int svc) throws ChannelException { this.internalStop(svc); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
protected synchronized void internalStart(int svc) throws ChannelException { try { boolean valid = false; //make sure we don't pass down any flags that are unrelated to the bottom layer svc = svc & Channel.DEFAULT; if (startLevel == Channel.DEFAULT) return; //we have already started up all components if (svc == 0 ) return;//nothing to start if (svc == (svc & startLevel)) throw new ChannelException("Channel already started for level:"+svc); //must start the receiver first so that we can coordinate the port it //listens to with the local membership settings if ( Channel.SND_RX_SEQ==(svc & Channel.SND_RX_SEQ) ) { clusterReceiver.setMessageListener(this); clusterReceiver.start(); //synchronize, big time FIXME membershipService.setLocalMemberProperties(getClusterReceiver().getHost(), getClusterReceiver().getPort(), getClusterReceiver().getSecurePort(), getClusterReceiver().getUdpPort()); valid = true; } if ( Channel.SND_TX_SEQ==(svc & Channel.SND_TX_SEQ) ) { clusterSender.start(); valid = true; } if ( Channel.MBR_RX_SEQ==(svc & Channel.MBR_RX_SEQ) ) { membershipService.setMembershipListener(this); if (membershipService instanceof McastService) { ((McastService)membershipService).setMessageListener(this); } membershipService.start(MembershipService.MBR_RX); valid = true; } if ( Channel.MBR_TX_SEQ==(svc & Channel.MBR_TX_SEQ) ) { membershipService.start(MembershipService.MBR_TX); valid = true; } if ( !valid) { throw new IllegalArgumentException("Invalid start level, valid levels are:SND_RX_SEQ,SND_TX_SEQ,MBR_TX_SEQ,MBR_RX_SEQ"); } startLevel = (startLevel | svc); }catch ( ChannelException cx ) { throw cx; }catch ( Exception x ) { throw new ChannelException(x); } }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
protected synchronized void internalStop(int svc) throws ChannelException { try { //make sure we don't pass down any flags that are unrelated to the bottom layer svc = svc & Channel.DEFAULT; if (startLevel == 0) return; //we have already stopped up all components if (svc == 0 ) return;//nothing to stop boolean valid = false; if ( Channel.SND_RX_SEQ==(svc & Channel.SND_RX_SEQ) ) { clusterReceiver.stop(); clusterReceiver.setMessageListener(null); valid = true; } if ( Channel.SND_TX_SEQ==(svc & Channel.SND_TX_SEQ) ) { clusterSender.stop(); valid = true; } if ( Channel.MBR_RX_SEQ==(svc & Channel.MBR_RX_SEQ) ) { membershipService.stop(MembershipService.MBR_RX); membershipService.setMembershipListener(null); valid = true; } if ( Channel.MBR_TX_SEQ==(svc & Channel.MBR_TX_SEQ) ) { valid = true; membershipService.stop(MembershipService.MBR_TX); } if ( !valid) { throw new IllegalArgumentException("Invalid start level, valid levels are:SND_RX_SEQ,SND_TX_SEQ,MBR_TX_SEQ,MBR_RX_SEQ"); } startLevel = (startLevel & (~svc)); }catch ( Exception x ) { throw new ChannelException(x); } finally { } }
// in java/org/apache/catalina/tribes/group/interceptors/TcpPingInterceptor.java
Override public synchronized void start(int svc) throws ChannelException { super.start(svc); running = true; if ( thread == null ) { thread = new PingThread(); thread.setDaemon(true); thread.setName("TcpPingInterceptor.PingThread-"+cnt.addAndGet(1)); thread.start(); } //acquire the interceptors to invoke on send ping events ChannelInterceptor next = getNext(); while ( next != null ) { if ( next instanceof TcpFailureDetector ) failureDetector = new WeakReference<TcpFailureDetector>((TcpFailureDetector)next); if ( next instanceof StaticMembershipInterceptor ) staticMembers = new WeakReference<StaticMembershipInterceptor>((StaticMembershipInterceptor)next); next = next.getNext(); } }
// in java/org/apache/catalina/tribes/group/interceptors/TcpPingInterceptor.java
Override public void stop(int svc) throws ChannelException { running = false; if ( thread != null ) thread.interrupt(); thread = null; super.stop(svc); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { try { super.sendMessage(destination, msg, payload); }catch ( ChannelException cx ) { FaultyMember[] mbrs = cx.getFaultyMembers(); for ( int i=0; i<mbrs.length; i++ ) { if ( mbrs[i].getCause()!=null && (!(mbrs[i].getCause() instanceof RemoteProcessException)) ) {//RemoteProcessException's are ok this.memberDisappeared(mbrs[i].getMember()); }//end if }//for throw cx; } }
// in java/org/apache/catalina/tribes/group/interceptors/StaticMembershipInterceptor.java
Override public void start(int svc) throws ChannelException { if ( (Channel.SND_RX_SEQ&svc)==Channel.SND_RX_SEQ ) super.start(Channel.SND_RX_SEQ); if ( (Channel.SND_TX_SEQ&svc)==Channel.SND_TX_SEQ ) super.start(Channel.SND_TX_SEQ); final Member[] mbrs = members.toArray(new Member[members.size()]); final ChannelInterceptorBase base = this; Thread t = new Thread() { @Override public void run() { for (int i=0; i<mbrs.length; i++ ) { base.memberAdded(mbrs[i]); } } }; t.start(); super.start(svc & (~Channel.SND_RX_SEQ) & (~Channel.SND_TX_SEQ)); }
// in java/org/apache/catalina/tribes/group/interceptors/OrderInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { if ( !okToProcess(msg.getOptions()) ) { super.sendMessage(destination, msg, payload); return; } ChannelException cx = null; for (int i=0; i<destination.length; i++ ) { try { int nr = 0; try { outLock.writeLock().lock(); nr = incCounter(destination[i]); } finally { outLock.writeLock().unlock(); } //reduce byte copy msg.getMessage().append(nr); try { getNext().sendMessage(new Member[] {destination[i]}, msg, payload); } finally { msg.getMessage().trim(4); } }catch ( ChannelException x ) { if ( cx == null ) cx = x; cx.addFaultyMember(x.getFaultyMembers()); } }//for if ( cx != null ) throw cx; }
// in java/org/apache/catalina/tribes/group/interceptors/TwoPhaseCommitInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { //todo, optimize, if destination.length==1, then we can do //msg.setOptions(msg.getOptions() & (~getOptionFlag()) //and just send one message if (okToProcess(msg.getOptions()) ) { super.sendMessage(destination, msg, null); ChannelMessage confirmation = null; if ( deepclone ) confirmation = (ChannelMessage)msg.deepclone(); else confirmation = (ChannelMessage)msg.clone(); confirmation.getMessage().reset(); UUIDGenerator.randomUUID(false,confirmation.getUniqueId(),0); confirmation.getMessage().append(START_DATA,0,START_DATA.length); confirmation.getMessage().append(msg.getUniqueId(),0,msg.getUniqueId().length); confirmation.getMessage().append(END_DATA,0,END_DATA.length); super.sendMessage(destination,confirmation,payload); } else { //turn off two phase commit //this wont work if the interceptor has 0 as a flag //since there is no flag to turn off //msg.setOptions(msg.getOptions() & (~getOptionFlag())); super.sendMessage(destination, msg, payload); } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
public void startElection(boolean force) throws ChannelException { synchronized (electionMutex) { MemberImpl local = (MemberImpl)getLocalMember(false); MemberImpl[] others = membership.getMembers(); fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_START_ELECT,this,"Election initated")); if ( others.length == 0 ) { this.viewId = new UniqueId(UUIDGenerator.randomUUID(false)); this.view = new Membership(local,AbsoluteOrder.comp, true); this.handleViewConf(this.createElectionMsg(local,others,local), view); return; //the only member, no need for an election } if ( suggestedviewId != null ) { if ( view != null && Arrays.diff(view,suggestedView,local).length == 0 && Arrays.diff(suggestedView,view,local).length == 0) { suggestedviewId = null; suggestedView = null; fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_ELECT_ABANDONED,this,"Election abandoned, running election matches view")); } else { fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_ELECT_ABANDONED,this,"Election abandoned, election running")); } return; //election already running, I'm not allowed to have two of them } if ( view != null && Arrays.diff(view,membership,local).length == 0 && Arrays.diff(membership,view,local).length == 0) { fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_ELECT_ABANDONED,this,"Election abandoned, view matches membership")); return; //already have this view installed } int prio = AbsoluteOrder.comp.compare(local,others[0]); MemberImpl leader = ( prio < 0 )?local:others[0];//am I the leader in my view? if ( local.equals(leader) || force ) { CoordinationMessage msg = createElectionMsg(local, others, leader); suggestedviewId = msg.getId(); suggestedView = new Membership(local,AbsoluteOrder.comp,true); Arrays.fill(suggestedView,msg.getMembers()); fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_PROCESS_ELECT,this,"Election, sending request")); sendElectionMsg(local,others[0],msg); } else { try { coordMsgReceived.set(false); fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_WAIT_FOR_MSG,this,"Election, waiting for request")); electionMutex.wait(waitForCoordMsgTimeout); }catch ( InterruptedException x ) { Thread.interrupted(); } if ( suggestedviewId == null && (!coordMsgReceived.get())) { //no message arrived, send the coord msg // fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_WAIT_FOR_MSG,this,"Election, waiting timed out.")); // startElection(true); fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_ELECT_ABANDONED,this,"Election abandoned, waiting timed out.")); } else { fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_ELECT_ABANDONED,this,"Election abandoned, received a message")); } }//end if } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
protected void sendElectionMsg(MemberImpl local, MemberImpl next, CoordinationMessage msg) throws ChannelException { fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_SEND_MSG,this,"Sending election message to("+next.getName()+")")); super.sendMessage(new Member[] {next}, createData(msg, local), null); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
protected void sendElectionMsgToNextInline(MemberImpl local, CoordinationMessage msg) throws ChannelException { int next = Arrays.nextIndex(local,msg.getMembers()); int current = next; msg.leader = msg.getMembers()[0]; boolean sent = false; while ( !sent && current >= 0 ) { try { sendElectionMsg(local, msg.getMembers()[current], msg); sent = true; }catch ( ChannelException x ) { log.warn("Unable to send election message to:"+msg.getMembers()[current]); current = Arrays.nextIndex(msg.getMembers()[current],msg.getMembers()); if ( current == next ) throw x; } } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
protected void processCoordMessage(CoordinationMessage msg) throws ChannelException { if ( !coordMsgReceived.get() ) { coordMsgReceived.set(true); synchronized (electionMutex) { electionMutex.notifyAll();} } msg.timestamp = System.currentTimeMillis(); Membership merged = mergeOnArrive(msg); if (isViewConf(msg)) handleViewConf(msg, merged); else handleToken(msg, merged); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
protected void handleToken(CoordinationMessage msg, Membership merged) throws ChannelException { MemberImpl local = (MemberImpl)getLocalMember(false); if ( local.equals(msg.getSource()) ) { //my message msg.src=local handleMyToken(local, msg, merged); } else { handleOtherToken(local, msg, merged); } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
protected void handleMyToken(MemberImpl local, CoordinationMessage msg, Membership merged) throws ChannelException { if ( local.equals(msg.getLeader()) ) { //no leadership change if ( Arrays.sameMembers(msg.getMembers(),merged.getMembers()) ) { msg.type = COORD_CONF; super.sendMessage(Arrays.remove(msg.getMembers(),local),createData(msg,local),null); handleViewConf(msg, merged); } else { //membership change suggestedView = new Membership(local,AbsoluteOrder.comp,true); suggestedviewId = msg.getId(); Arrays.fill(suggestedView,merged.getMembers()); msg.view = merged.getMembers(); sendElectionMsgToNextInline(local,msg); } } else { //leadership change suggestedView = null; suggestedviewId = null; msg.view = merged.getMembers(); sendElectionMsgToNextInline(local,msg); } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
protected void handleOtherToken(MemberImpl local, CoordinationMessage msg, Membership merged) throws ChannelException { if ( local.equals(msg.getLeader()) ) { //I am the new leader //startElection(false); } else { msg.view = merged.getMembers(); sendElectionMsgToNextInline(local,msg); } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
protected void handleViewConf(CoordinationMessage msg, Membership merged) throws ChannelException { if ( viewId != null && msg.getId().equals(viewId) ) return;//we already have this view view = new Membership((MemberImpl)getLocalMember(false),AbsoluteOrder.comp,true); Arrays.fill(view,msg.getMembers()); viewId = msg.getId(); if ( viewId.equals(suggestedviewId) ) { suggestedView = null; suggestedviewId = null; } if (suggestedView != null && AbsoluteOrder.comp.compare(suggestedView.getMembers()[0],merged.getMembers()[0])<0 ) { suggestedView = null; suggestedviewId = null; } fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_CONF_RX,this,"Accepted View")); if ( suggestedviewId == null && hasHigherPriority(merged.getMembers(),membership.getMembers()) ) { startElection(false); } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
Override public void start(int svc) throws ChannelException { if (membership == null) setupMembership(); if (started)return; fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_START, this, "Before start")); super.start(startsvc); started = true; if (view == null) view = new Membership( (MemberImpl)super.getLocalMember(true), AbsoluteOrder.comp, true); fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_START, this, "After start")); startElection(false); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
Override public void stop(int svc) throws ChannelException { try { halt(); synchronized (electionMutex) { if (!started)return; started = false; fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_STOP, this, "Before stop")); super.stop(startsvc); this.view = null; this.viewId = null; this.suggestedView = null; this.suggestedviewId = null; this.membership.reset(); fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_STOP, this, "After stop")); } }finally { release(); } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { waitForRelease(); super.sendMessage(destination, msg, payload); }
// in java/org/apache/catalina/tribes/group/interceptors/SimpleCoordinator.java
Override public void start(int svc) throws ChannelException { super.start(svc); installViewWhenStable(); }
// in java/org/apache/catalina/tribes/group/interceptors/SimpleCoordinator.java
Override public void stop(int svc) throws ChannelException { super.stop(svc); }
// in java/org/apache/catalina/tribes/group/interceptors/FragmentationInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { int size = msg.getMessage().getLength(); boolean frag = (size>maxSize) && okToProcess(msg.getOptions()); if ( frag ) { frag(destination, msg, payload); } else { msg.getMessage().append(frag); super.sendMessage(destination, msg, payload); } }
// in java/org/apache/catalina/tribes/group/interceptors/FragmentationInterceptor.java
public void frag(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { int size = msg.getMessage().getLength(); int count = ((size / maxSize )+(size%maxSize==0?0:1)); ChannelMessage[] messages = new ChannelMessage[count]; int remaining = size; for ( int i=0; i<count; i++ ) { ChannelMessage tmp = (ChannelMessage)msg.clone(); int offset = (i*maxSize); int length = Math.min(remaining,maxSize); tmp.getMessage().clear(); tmp.getMessage().append(msg.getMessage().getBytesDirect(),offset,length); //add the msg nr //tmp.getMessage().append(XByteBuffer.toBytes(i),0,4); tmp.getMessage().append(i); //add the total nr of messages //tmp.getMessage().append(XByteBuffer.toBytes(count),0,4); tmp.getMessage().append(count); //add true as the frag flag //byte[] flag = XByteBuffer.toBytes(true); //tmp.getMessage().append(flag,0,flag.length); tmp.getMessage().append(true); messages[i] = tmp; remaining -= length; } for ( int i=0; i<messages.length; i++ ) { super.sendMessage(destination,messages[i],payload); } }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { try { byte[] data = compress(msg.getMessage().getBytes()); msg.getMessage().trim(msg.getMessage().getLength()); msg.getMessage().append(data,0,data.length); getNext().sendMessage(destination, msg, payload); } catch ( IOException x ) { log.error("Unable to compress byte contents"); throw new ChannelException(x); } }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { boolean async = (msg.getOptions() & Channel.SEND_OPTIONS_ASYNCHRONOUS) == Channel.SEND_OPTIONS_ASYNCHRONOUS; if ( async && run ) { if ( (getCurrentSize()+msg.getMessage().getLength()) > maxQueueSize ) { if ( alwaysSend ) { super.sendMessage(destination,msg,payload); return; } else { throw new ChannelException("Asynchronous queue is full, reached its limit of " + maxQueueSize +" bytes, current:" + getCurrentSize() + " bytes."); }//end if }//end if //add to queue if ( useDeepClone ) msg = (ChannelMessage)msg.deepclone(); if (!addToQueue(msg, destination, payload) ) { throw new ChannelException("Unable to add the message to the async queue, queue bug?"); } addAndGetCurrentSize(msg.getMessage().getLength()); } else { super.sendMessage(destination, msg, payload); } }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
Override public void start(int svc) throws ChannelException { //start the thread if (!run ) { synchronized (this) { if ( !run && ((svc & Channel.SND_TX_SEQ)==Channel.SND_TX_SEQ) ) {//only start with the sender startQueue(); }//end if }//sync }//end if super.start(svc); }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
Override public void stop(int svc) throws ChannelException { //stop the thread if ( run ) { synchronized (this) { if ( run && ((svc & Channel.SND_TX_SEQ)==Channel.SND_TX_SEQ)) { stopQueue(); }//end if }//sync }//end if super.stop(svc); }
// in java/org/apache/catalina/tribes/group/interceptors/ThroughputInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { if ( access.addAndGet(1) == 1 ) txStart = System.currentTimeMillis(); long bytes = XByteBuffer.getDataPackageLength(((ChannelData)msg).getDataPackageLength()); try { super.sendMessage(destination, msg, payload); }catch ( ChannelException x ) { msgTxErr.addAndGet(1); if ( access.get() == 1 ) access.addAndGet(-1); throw x; } mbTx += (bytes*destination.length)/(1024d*1024d); mbAppTx += bytes/(1024d*1024d); if ( access.addAndGet(-1) == 0 ) { long stop = System.currentTimeMillis(); timeTx += (stop - txStart) / 1000d; if ((msgTxCnt.get() / interval) >= lastCnt) { lastCnt++; report(timeTx); } } msgTxCnt.addAndGet(1); }
// in java/org/apache/catalina/tribes/group/ChannelInterceptorBase.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { if (getNext() != null) getNext().sendMessage(destination, msg, payload); }
// in java/org/apache/catalina/tribes/group/ChannelInterceptorBase.java
Override public void start(int svc) throws ChannelException { if ( getNext()!=null ) getNext().start(svc); }
// in java/org/apache/catalina/tribes/group/ChannelInterceptorBase.java
Override public void stop(int svc) throws ChannelException { if (getNext() != null) getNext().stop(svc); }
// in java/org/apache/catalina/tribes/transport/bio/PooledMultiSender.java
Override public void sendMessage(Member[] destination, ChannelMessage msg) throws ChannelException { MultiPointSender sender = null; try { sender = (MultiPointSender)getSender(); if (sender == null) { ChannelException cx = new ChannelException("Unable to retrieve a data sender, time out error."); for (int i = 0; i < destination.length; i++) cx.addFaultyMember(destination[i], new NullPointerException("Unable to retrieve a sender from the sender pool")); throw cx; } else { sender.sendMessage(destination, msg); } sender.keepalive(); }finally { if ( sender != null ) returnSender(sender); } }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
Override public synchronized void sendMessage(Member[] destination, ChannelMessage msg) throws ChannelException { byte[] data = XByteBuffer.createDataPackage((ChannelData)msg); BioSender[] senders = setupForSend(destination); ChannelException cx = null; for ( int i=0; i<senders.length; i++ ) { try { senders[i].sendMessage(data,(msg.getOptions()&Channel.SEND_OPTIONS_USE_ACK)==Channel.SEND_OPTIONS_USE_ACK); } catch (Exception x) { if (cx == null) cx = new ChannelException(x); cx.addFaultyMember(destination[i],x); } } if (cx!=null ) throw cx; }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
protected BioSender[] setupForSend(Member[] destination) throws ChannelException { ChannelException cx = null; BioSender[] result = new BioSender[destination.length]; for ( int i=0; i<destination.length; i++ ) { try { BioSender sender = bioSenders.get(destination[i]); if (sender == null) { sender = new BioSender(); AbstractSender.transferProperties(this,sender); sender.setDestination(destination[i]); bioSenders.put(destination[i], sender); } result[i] = sender; if (!result[i].isConnected() ) result[i].connect(); result[i].keepalive(); }catch (Exception x ) { if ( cx== null ) cx = new ChannelException(x); cx.addFaultyMember(destination[i],x); } } if ( cx!=null ) throw cx; else return result; }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
private synchronized void close() throws ChannelException { ChannelException x = null; Object[] members = bioSenders.keySet().toArray(); for (int i=0; i<members.length; i++ ) { Member mbr = (Member)members[i]; try { BioSender sender = bioSenders.get(mbr); sender.disconnect(); }catch ( Exception e ) { if ( x == null ) x = new ChannelException(e); x.addFaultyMember(mbr,e); } bioSenders.remove(mbr); } if ( x != null ) throw x; }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
Override public void sendMessage(Member[] destination, ChannelMessage message) throws ChannelException { if ( !connected ) throw new ChannelException("Sender not connected."); ParallelNioSender sender = (ParallelNioSender)getSender(); if (sender == null) { ChannelException cx = new ChannelException("Unable to retrieve a data sender, time out error."); for (int i = 0; i < destination.length; i++) cx.addFaultyMember(destination[i], new NullPointerException("Unable to retrieve a sender from the sender pool")); throw cx; } else { try { sender.sendMessage(destination, message); sender.keepalive(); } catch (ChannelException x) { sender.disconnect(); throw x; } finally { returnSender(sender); if (!connected) disconnect(); } } }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
Override public synchronized void sendMessage(Member[] destination, ChannelMessage msg) throws ChannelException { long start = System.currentTimeMillis(); this.setUdpBased((msg.getOptions()&Channel.SEND_OPTIONS_UDP) == Channel.SEND_OPTIONS_UDP); byte[] data = XByteBuffer.createDataPackage((ChannelData)msg); NioSender[] senders = setupForSend(destination); connect(senders); setData(senders,data); int remaining = senders.length; ChannelException cx = null; try { //loop until complete, an error happens, or we timeout long delta = System.currentTimeMillis() - start; boolean waitForAck = (Channel.SEND_OPTIONS_USE_ACK & msg.getOptions()) == Channel.SEND_OPTIONS_USE_ACK; while ( (remaining>0) && (delta<getTimeout()) ) { try { remaining -= doLoop(selectTimeout, getMaxRetryAttempts(),waitForAck,msg); } catch (Exception x ) { if (log.isTraceEnabled()) log.trace("Error sending message", x); int faulty = (cx == null)?0:cx.getFaultyMembers().length; if ( cx == null ) { if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException("Parallel NIO send failed.", x); } else { if (x instanceof ChannelException) cx.addFaultyMember( ( (ChannelException) x).getFaultyMembers()); } //count down the remaining on an error if (faulty<cx.getFaultyMembers().length) remaining -= (cx.getFaultyMembers().length-faulty); } //bail out if all remaining senders are failing if ( cx != null && cx.getFaultyMembers().length == remaining ) throw cx; delta = System.currentTimeMillis() - start; } if ( remaining > 0 ) { //timeout has occurred ChannelException cxtimeout = new ChannelException("Operation has timed out("+getTimeout()+" ms.)."); if ( cx==null ) cx = new ChannelException("Operation has timed out("+getTimeout()+" ms.)."); for (int i=0; i<senders.length; i++ ) { if (!senders[i].isComplete() ) cx.addFaultyMember(senders[i].getDestination(),cxtimeout); } throw cx; } else if ( cx != null ) { //there was an error throw cx; } } catch (Exception x ) { try { this.disconnect(); } catch (Exception e) {/*Ignore*/} if ( x instanceof ChannelException ) throw (ChannelException)x; else throw new ChannelException(x); } }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
private int doLoop(long selectTimeOut, int maxAttempts, boolean waitForAck, ChannelMessage msg) throws IOException, ChannelException { int completed = 0; int selectedKeys = selector.select(selectTimeOut); if (selectedKeys == 0) { return 0; } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey sk = it.next(); it.remove(); int readyOps = sk.readyOps(); sk.interestOps(sk.interestOps() & ~readyOps); NioSender sender = (NioSender) sk.attachment(); try { if (sender.process(sk,waitForAck)) { completed++; sender.setComplete(true); if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("ParallelNioSender - Sent msg:" + new UniqueId(msg.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " to "+sender.getDestination().getName()); } SenderState.getSenderState(sender.getDestination()).setReady(); }//end if } catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if } } return completed; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
private void connect(NioSender[] senders) throws ChannelException { ChannelException x = null; for (int i=0; i<senders.length; i++ ) { try { senders[i].connect(); }catch ( IOException io ) { if ( x==null ) x = new ChannelException(io); x.addFaultyMember(senders[i].getDestination(),io); } } if ( x != null ) throw x; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
private void setData(NioSender[] senders, byte[] data) throws ChannelException { ChannelException x = null; for (int i=0; i<senders.length; i++ ) { try { senders[i].setMessage(data); }catch ( IOException io ) { if ( x==null ) x = new ChannelException(io); x.addFaultyMember(senders[i].getDestination(),io); } } if ( x != null ) throw x; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
private NioSender[] setupForSend(Member[] destination) throws ChannelException { ChannelException cx = null; NioSender[] result = new NioSender[destination.length]; for ( int i=0; i<destination.length; i++ ) { NioSender sender = nioSenders.get(destination[i]); try { if (sender == null) { sender = new NioSender(); AbstractSender.transferProperties(this, sender); nioSenders.put(destination[i], sender); } sender.reset(); sender.setDestination(destination[i]); sender.setSelector(selector); sender.setUdpBased(isUdpBased()); result[i] = sender; }catch ( UnknownHostException x ) { if (cx == null) cx = new ChannelException("Unable to setup NioSender.", x); cx.addFaultyMember(destination[i], x); } } if ( cx != null ) throw cx; else return result; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
private synchronized void close() throws ChannelException { ChannelException x = null; Object[] members = nioSenders.keySet().toArray(); for (int i=0; i<members.length; i++ ) { Member mbr = (Member)members[i]; try { NioSender sender = nioSenders.get(mbr); sender.disconnect(); }catch ( Exception e ) { if ( x == null ) x = new ChannelException(e); x.addFaultyMember(mbr,e); } nioSenders.remove(mbr); } if ( x != null ) throw x; }
// in java/org/apache/catalina/tribes/transport/ReplicationTransmitter.java
Override public void sendMessage(ChannelMessage message, Member[] destination) throws ChannelException { MultiPointSender sender = getTransport(); sender.sendMessage(destination,message); }
// in java/org/apache/catalina/tribes/tipis/LazyReplicatedMap.java
Override protected Member[] publishEntryInfo(Object key, Object value) throws ChannelException { if (! (key instanceof Serializable && value instanceof Serializable) ) return new Member[0]; Member[] members = getMapMembers(); int firstIdx = getNextBackupIndex(); int nextIdx = firstIdx; Member[] backup = new Member[0]; //there are no backups if ( members.length == 0 || firstIdx == -1 ) return backup; boolean success = false; do { //select a backup node Member next = members[nextIdx]; //increment for the next round of back up selection nextIdx = nextIdx + 1; if ( nextIdx >= members.length ) nextIdx = 0; if (next == null) { continue; } MapMessage msg = null; try { backup = wrap(next); //publish the backup data to one node msg = new MapMessage(getMapContextName(), MapMessage.MSG_BACKUP, false, (Serializable) key, (Serializable) value, null, channel.getLocalMember(false), backup); if ( log.isTraceEnabled() ) log.trace("Publishing backup data:"+msg+" to: "+next.getName()); UniqueId id = getChannel().send(backup, msg, getChannelSendOptions()); if ( log.isTraceEnabled() ) log.trace("Data published:"+msg+" msg Id:"+id); //we published out to a backup, mark the test success success = true; }catch ( ChannelException x ) { log.error("Unable to replicate backup key:"+key+" to backup:"+next+". Reason:"+x.getMessage(),x); } try { //publish the data out to all nodes Member[] proxies = excludeFromSet(backup, getMapMembers()); if (success && proxies.length > 0 ) { msg = new MapMessage(getMapContextName(), MapMessage.MSG_PROXY, false, (Serializable) key, null, null, channel.getLocalMember(false),backup); if ( log.isTraceEnabled() ) log.trace("Publishing proxy data:"+msg+" to: "+Arrays.toNameString(proxies)); getChannel().send(proxies, msg, getChannelSendOptions()); } }catch ( ChannelException x ) { //log the error, but proceed, this should only happen if a node went down, //and if the node went down, then it can't receive the message, the others //should still get it. log.error("Unable to replicate proxy key:"+key+" to backup:"+next+". Reason:"+x.getMessage(),x); } } while ( !success && (firstIdx!=nextIdx)); return backup; }
// in java/org/apache/catalina/tribes/tipis/ReplicatedMap.java
Override protected Member[] publishEntryInfo(Object key, Object value) throws ChannelException { if (! (key instanceof Serializable && value instanceof Serializable) ) return new Member[0]; //select a backup node Member[] backup = getMapMembers(); if (backup == null || backup.length == 0) return null; //publish the data out to all nodes MapMessage msg = new MapMessage(getMapContextName(), MapMessage.MSG_COPY, false, (Serializable) key, (Serializable) value, null,channel.getLocalMember(false), backup); getChannel().send(getMapMembers(), msg, getChannelSendOptions()); return backup; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
protected void ping(long timeout) throws ChannelException { //send out a map membership message, only wait for the first reply MapMessage msg = new MapMessage(this.mapContextName, MapMessage.MSG_INIT, false, null, null, null, channel.getLocalMember(false), null); if ( channel.getMembers().length > 0 ) { try { //send a ping, wait for all nodes to reply Response[] resp = rpcChannel.send(channel.getMembers(), msg, RpcChannel.ALL_REPLY, (channelSendOptions), (int) accessTimeout); for (int i = 0; i < resp.length; i++) { memberAlive(resp[i].getSource()); } } catch (ChannelException ce) { // Handle known failed members FaultyMember[] faultyMembers = ce.getFaultyMembers(); for (FaultyMember faultyMember : faultyMembers) { memberDisappeared(faultyMember.getMember()); } } } //update our map of members, expire some if we didn't receive a ping back synchronized (mapMembers) { Iterator<Map.Entry<Member, Long>> it = mapMembers.entrySet().iterator(); long now = System.currentTimeMillis(); while ( it.hasNext() ) { Map.Entry<Member,Long> entry = it.next(); long access = entry.getValue().longValue(); if ( (now - access) > timeout ) { it.remove(); memberDisappeared(entry.getKey()); } } }//synch }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
protected void broadcast(int msgtype, boolean rpc) throws ChannelException { Member[] members = channel.getMembers(); // No destination. if (members.length == 0 ) return; //send out a map membership message, only wait for the first reply MapMessage msg = new MapMessage(this.mapContextName, msgtype, false, null, null, null, channel.getLocalMember(false), null); if ( rpc) { Response[] resp = rpcChannel.send(members, msg, RpcChannel.FIRST_REPLY, (channelSendOptions), rpcTimeout); if (resp.length > 0) { for (int i = 0; i < resp.length; i++) { mapMemberAdded(resp[i].getSource()); messageReceived(resp[i].getMessage(), resp[i].getSource()); } } else { log.warn("broadcast received 0 replies, probably a timeout."); } } else { channel.send(channel.getMembers(),msg,channelSendOptions); } }
// in java/org/apache/catalina/tribes/membership/McastService.java
Override public void broadcast(ChannelMessage message) throws ChannelException { if (impl==null || (impl.startLevel & Channel.MBR_TX_SEQ)!=Channel.MBR_TX_SEQ ) throw new ChannelException("Multicast send is not started or enabled."); byte[] data = XByteBuffer.createDataPackage((ChannelData)message); if (data.length>McastServiceImpl.MAX_PACKET_SIZE) { throw new ChannelException("Packet length["+data.length+"] exceeds max packet size of "+McastServiceImpl.MAX_PACKET_SIZE+" bytes."); } DatagramPacket packet = new DatagramPacket(data,0,data.length); try { impl.send(false, packet); } catch (Exception x) { throw new ChannelException(x); } }
(Lib) SAXParseException 16
              
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void startElement( String uri, String localName, String qName, Attributes attrs) throws SAXException { AttributesImpl taglibAttrs = null; AttributesImpl nonTaglibAttrs = null; AttributesImpl nonTaglibXmlnsAttrs = null; processChars(); checkPrefixes(uri, qName, attrs); if (directivesOnly && !(JSP_URI.equals(uri) && localName.startsWith(DIRECTIVE_ACTION))) { return; } String currentPrefix = getPrefix(current.getQName()); // jsp:text must not have any subelements if (JSP_URI.equals(uri) && TEXT_ACTION.equals(current.getLocalName()) && "jsp".equals(currentPrefix)) { throw new SAXParseException( Localizer.getMessage("jsp.error.text.has_subelement"), locator); } startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); if (attrs != null) { /* * Notice that due to a bug in the underlying SAX parser, the * attributes must be enumerated in descending order. */ boolean isTaglib = false; for (int i = attrs.getLength() - 1; i >= 0; i--) { isTaglib = false; String attrQName = attrs.getQName(i); if (!attrQName.startsWith("xmlns")) { if (nonTaglibAttrs == null) { nonTaglibAttrs = new AttributesImpl(); } nonTaglibAttrs.addAttribute( attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getValue(i)); } else { if (attrQName.startsWith("xmlns:jsp")) { isTaglib = true; } else { String attrUri = attrs.getValue(i); // TaglibInfo for this uri already established in // startPrefixMapping isTaglib = pageInfo.hasTaglib(attrUri); } if (isTaglib) { if (taglibAttrs == null) { taglibAttrs = new AttributesImpl(); } taglibAttrs.addAttribute( attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getValue(i)); } else { if (nonTaglibXmlnsAttrs == null) { nonTaglibXmlnsAttrs = new AttributesImpl(); } nonTaglibXmlnsAttrs.addAttribute( attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getValue(i)); } } } } Node node = null; if (tagDependentPending && JSP_URI.equals(uri) && localName.equals(BODY_ACTION)) { tagDependentPending = false; tagDependentNesting++; current = parseStandardAction( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark); return; } if (tagDependentPending && JSP_URI.equals(uri) && localName.equals(ATTRIBUTE_ACTION)) { current = parseStandardAction( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark); return; } if (tagDependentPending) { tagDependentPending = false; tagDependentNesting++; } if (tagDependentNesting > 0) { node = new Node.UninterpretedTag( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark, current); } else if (JSP_URI.equals(uri)) { node = parseStandardAction( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark); } else { node = parseCustomAction( qName, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark, current); if (node == null) { node = new Node.UninterpretedTag( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark, current); } else { // custom action String bodyType = getBodyType((Node.CustomTag) node); if (scriptlessBodyNode == null && bodyType.equalsIgnoreCase(TagInfo.BODY_CONTENT_SCRIPTLESS)) { scriptlessBodyNode = node; } else if (TagInfo.BODY_CONTENT_TAG_DEPENDENT.equalsIgnoreCase(bodyType)) { tagDependentPending = true; } } } current = node; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void processChars() throws SAXException { if (charBuffer == null || directivesOnly) { return; } /* * JSP.6.1.1: All textual nodes that have only white space are to be * dropped from the document, except for nodes in a jsp:text element, * and any leading and trailing white-space-only textual nodes in a * jsp:attribute whose 'trim' attribute is set to FALSE, which are to * be kept verbatim. * JSP.6.2.3 defines white space characters. */ boolean isAllSpace = true; if (!(current instanceof Node.JspText) && !(current instanceof Node.NamedAttribute)) { for (int i = 0; i < charBuffer.length(); i++) { if (!(charBuffer.charAt(i) == ' ' || charBuffer.charAt(i) == '\n' || charBuffer.charAt(i) == '\r' || charBuffer.charAt(i) == '\t')) { isAllSpace = false; break; } } } if (!isAllSpace && tagDependentPending) { tagDependentPending = false; tagDependentNesting++; } if (tagDependentNesting > 0) { if (charBuffer.length() > 0) { new Node.TemplateText(charBuffer.toString(), startMark, current); } startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); charBuffer = null; return; } if ((current instanceof Node.JspText) || (current instanceof Node.NamedAttribute) || !isAllSpace) { int line = startMark.getLineNumber(); int column = startMark.getColumnNumber(); CharArrayWriter ttext = new CharArrayWriter(); int lastCh = 0, elType = 0; for (int i = 0; i < charBuffer.length(); i++) { int ch = charBuffer.charAt(i); if (ch == '\n') { column = 1; line++; } else { column++; } if ((lastCh == '$' || lastCh == '#') && ch == '{') { elType = lastCh; if (ttext.size() > 0) { new Node.TemplateText( ttext.toString(), startMark, current); ttext = new CharArrayWriter(); //We subtract two from the column number to //account for the '[$,#]{' that we've already parsed startMark = new Mark(ctxt, path, line, column - 2); } // following "${" || "#{" to first unquoted "}" i++; boolean singleQ = false; boolean doubleQ = false; lastCh = 0; for (;; i++) { if (i >= charBuffer.length()) { throw new SAXParseException( Localizer.getMessage( "jsp.error.unterminated", (char) elType + "{"), locator); } ch = charBuffer.charAt(i); if (ch == '\n') { column = 1; line++; } else { column++; } if (lastCh == '\\' && (singleQ || doubleQ)) { ttext.write(ch); lastCh = 0; continue; } if (ch == '}') { new Node.ELExpression((char) elType, ttext.toString(), startMark, current); ttext = new CharArrayWriter(); startMark = new Mark(ctxt, path, line, column); break; } if (ch == '"') doubleQ = !doubleQ; else if (ch == '\'') singleQ = !singleQ; ttext.write(ch); lastCh = ch; } } else if (lastCh == '\\' && (ch == '$' || ch == '#')) { if (pageInfo.isELIgnored()) { ttext.write('\\'); } ttext.write(ch); ch = 0; // Not start of EL anymore } else { if (lastCh == '$' || lastCh == '#' || lastCh == '\\') { ttext.write(lastCh); } if (ch != '$' && ch != '#' && ch != '\\') { ttext.write(ch); } } lastCh = ch; } if (lastCh == '$' || lastCh == '#' || lastCh == '\\') { ttext.write(lastCh); } if (ttext.size() > 0) { new Node.TemplateText(ttext.toString(), startMark, current); } } startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); charBuffer = null; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void endElement(String uri, String localName, String qName) throws SAXException { processChars(); if (directivesOnly && !(JSP_URI.equals(uri) && localName.startsWith(DIRECTIVE_ACTION))) { return; } if (current instanceof Node.NamedAttribute) { boolean isTrim = ((Node.NamedAttribute)current).isTrim(); Node.Nodes subElems = ((Node.NamedAttribute)current).getBody(); for (int i = 0; subElems != null && i < subElems.size(); i++) { Node subElem = subElems.getNode(i); if (!(subElem instanceof Node.TemplateText)) { continue; } // Ignore any whitespace (including spaces, carriage returns, // line feeds, and tabs, that appear at the beginning and at // the end of the body of the <jsp:attribute> action, if the // action's 'trim' attribute is set to TRUE (default). // In addition, any textual nodes in the <jsp:attribute> that // have only white space are dropped from the document, with // the exception of leading and trailing white-space-only // textual nodes in a <jsp:attribute> whose 'trim' attribute // is set to FALSE, which must be kept verbatim. if (i == 0) { if (isTrim) { ((Node.TemplateText)subElem).ltrim(); } } else if (i == subElems.size() - 1) { if (isTrim) { ((Node.TemplateText)subElem).rtrim(); } } else { if (((Node.TemplateText)subElem).isAllSpace()) { subElems.remove(subElem); } } } } else if (current instanceof Node.ScriptingElement) { checkScriptingBody((Node.ScriptingElement)current); } if ( isTagDependent(current)) { tagDependentNesting--; } if (scriptlessBodyNode != null && current.equals(scriptlessBodyNode)) { scriptlessBodyNode = null; } if (current instanceof Node.CustomTag) { String bodyType = getBodyType((Node.CustomTag) current); if (TagInfo.BODY_CONTENT_EMPTY.equalsIgnoreCase(bodyType)) { // Children - if any - must be JSP attributes Node.Nodes children = current.getBody(); if (children != null && children.size() > 0) { for (int i = 0; i < children.size(); i++) { Node child = children.getNode(i); if (!(child instanceof Node.NamedAttribute)) { throw new SAXParseException(Localizer.getMessage( "jasper.error.emptybodycontent.nonempty", current.qName), locator); } } } } } if (current.getParent() != null) { current = current.getParent(); } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void startPrefixMapping(String prefix, String uri) throws SAXException { TagLibraryInfo taglibInfo; if (directivesOnly && !(JSP_URI.equals(uri))) { return; } try { taglibInfo = getTaglibInfo(prefix, uri); } catch (JasperException je) { throw new SAXParseException( Localizer.getMessage("jsp.error.could.not.add.taglibraries"), locator, je); } if (taglibInfo != null) { if (pageInfo.getTaglib(uri) == null) { pageInfo.addTaglib(uri, taglibInfo); } pageInfo.pushPrefixMapping(prefix, uri); } else { pageInfo.pushPrefixMapping(prefix, null); } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private Node parseStandardAction( String qName, String localName, Attributes nonTaglibAttrs, Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs, Mark start) throws SAXException { Node node = null; if (localName.equals(ROOT_ACTION)) { if (!(current instanceof Node.Root)) { throw new SAXParseException( Localizer.getMessage("jsp.error.nested_jsproot"), locator); } node = new Node.JspRoot( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); if (isTop) { pageInfo.setHasJspRoot(true); } } else if (localName.equals(PAGE_DIRECTIVE_ACTION)) { if (isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.istagfile", localName), locator); } node = new Node.PageDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); String imports = nonTaglibAttrs.getValue("import"); // There can only be one 'import' attribute per page directive if (imports != null) { ((Node.PageDirective)node).addImport(imports); } } else if (localName.equals(INCLUDE_DIRECTIVE_ACTION)) { node = new Node.IncludeDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); processIncludeDirective(nonTaglibAttrs.getValue("file"), node); } else if (localName.equals(DECLARATION_ACTION)) { if (scriptlessBodyNode != null) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException( Localizer.getMessage( "jsp.error.no.scriptlets", localName), locator); } node = new Node.Declaration( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(SCRIPTLET_ACTION)) { if (scriptlessBodyNode != null) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException( Localizer.getMessage( "jsp.error.no.scriptlets", localName), locator); } node = new Node.Scriptlet( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(EXPRESSION_ACTION)) { if (scriptlessBodyNode != null) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException( Localizer.getMessage( "jsp.error.no.scriptlets", localName), locator); } node = new Node.Expression( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(USE_BEAN_ACTION)) { node = new Node.UseBean( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(SET_PROPERTY_ACTION)) { node = new Node.SetProperty( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(GET_PROPERTY_ACTION)) { node = new Node.GetProperty( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(INCLUDE_ACTION)) { node = new Node.IncludeAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(FORWARD_ACTION)) { node = new Node.ForwardAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(PARAM_ACTION)) { node = new Node.ParamAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(PARAMS_ACTION)) { node = new Node.ParamsAction( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(PLUGIN_ACTION)) { node = new Node.PlugIn( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(TEXT_ACTION)) { node = new Node.JspText( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(BODY_ACTION)) { node = new Node.JspBody( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(ATTRIBUTE_ACTION)) { node = new Node.NamedAttribute( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(OUTPUT_ACTION)) { node = new Node.JspOutput( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(TAG_DIRECTIVE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.TagDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); String imports = nonTaglibAttrs.getValue("import"); // There can only be one 'import' attribute per tag directive if (imports != null) { ((Node.TagDirective)node).addImport(imports); } } else if (localName.equals(ATTRIBUTE_DIRECTIVE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.AttributeDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(VARIABLE_DIRECTIVE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.VariableDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(INVOKE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.InvokeAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(DOBODY_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.DoBodyAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(ELEMENT_ACTION)) { node = new Node.JspElement( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(FALLBACK_ACTION)) { node = new Node.FallBackAction( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else { throw new SAXParseException( Localizer.getMessage( "jsp.error.xml.badStandardAction", localName), locator); } return node; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void processIncludeDirective(String fname, Node parent) throws SAXException { if (fname == null) { return; } try { parserController.parse(fname, parent, null); } catch (FileNotFoundException fnfe) { throw new SAXParseException( Localizer.getMessage("jsp.error.file.not.found", fname), locator, fnfe); } catch (Exception e) { throw new SAXException(e); } }
2
              
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (JasperException je) { throw new SAXParseException( Localizer.getMessage("jsp.error.could.not.add.taglibraries"), locator, je); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (FileNotFoundException fnfe) { throw new SAXParseException( Localizer.getMessage("jsp.error.file.not.found", fname), locator, fnfe); }
0
(Lib) UnsupportedOperationException 17
              
// in java/org/apache/el/lang/VariableMapperFactory.java
Override public ValueExpression setVariable(String variable, ValueExpression expression) { throw new UnsupportedOperationException("Cannot Set Variables on Factory"); }
// in java/org/apache/el/parser/SimpleNode.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/el/parser/SimpleNode.java
Override public Object getValue(EvaluationContext ctx) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/el/parser/SimpleNode.java
Override public Object invoke(EvaluationContext ctx, Class<?>[] paramTypes, Object[] paramValues) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/el/parser/SimpleNode.java
Override public MethodInfo getMethodInfo(EvaluationContext ctx, Class<?>[] paramTypes) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/catalina/ant/DeployTask.java
Override public void execute() throws BuildException { super.execute(); if (path == null) { throw new BuildException ("Must specify 'path' attribute"); } if ((war == null) && (localWar == null) && (config == null) && (tag == null)) { throw new BuildException ("Must specify either 'war', 'localWar', 'config', or 'tag' attribute"); } // Building an input stream on the WAR to upload, if any BufferedInputStream stream = null; String contentType = null; int contentLength = -1; if (war != null) { if (war.startsWith("file:")) { try { URL url = new URL(war); URLConnection conn = url.openConnection(); contentLength = conn.getContentLength(); stream = new BufferedInputStream (conn.getInputStream(), 1024); } catch (IOException e) { throw new BuildException(e); } } else { try { FileInputStream fsInput = new FileInputStream(war); long size = fsInput.getChannel().size(); if (size > Integer.MAX_VALUE) throw new UnsupportedOperationException( "DeployTask does not support WAR files " + "greater than 2 Gb"); contentLength = (int) size; stream = new BufferedInputStream(fsInput, 1024); } catch (IOException e) { throw new BuildException(e); } } contentType = "application/octet-stream"; } // Building URL StringBuilder sb = new StringBuilder("/deploy?path="); try { sb.append(URLEncoder.encode(this.path, getCharset())); if ((war == null) && (config != null)) { sb.append("&config="); sb.append(URLEncoder.encode(config, getCharset())); } if ((war == null) && (localWar != null)) { sb.append("&war="); sb.append(URLEncoder.encode(localWar, getCharset())); } if (update) { sb.append("&update=true"); } if (tag != null) { sb.append("&tag="); sb.append(URLEncoder.encode(tag, getCharset())); } } catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); } execute(sb.toString(), stream, contentType, contentLength); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
Override public Object clone() { throw new UnsupportedOperationException("This operation is not valid on a replicated map"); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
public void cleanDeployDir() { throw new java.lang.UnsupportedOperationException(sm.getString( "farmWarDeployer.notImplemented", "cleanDeployDir()")); }
// in java/org/apache/catalina/connector/CometEventImpl.java
Override public void setTimeout(int timeout) throws IOException, ServletException, UnsupportedOperationException { if (request.getAttribute(Globals.COMET_TIMEOUT_SUPPORTED_ATTR) == Boolean.TRUE) { request.setAttribute(Globals.COMET_TIMEOUT_ATTR, Integer.valueOf(timeout)); if (request.isComet()) { request.setCometTimeout(timeout); } } else { throw new UnsupportedOperationException(); } }
// in java/javax/servlet/jsp/tagext/TagAdapter.java
Override public void setPageContext(PageContext pc) { throw new UnsupportedOperationException( "Illegal to invoke setPageContext() on TagAdapter wrapper"); }
// in java/javax/servlet/jsp/tagext/TagAdapter.java
Override public void setParent(Tag parentTag) { throw new UnsupportedOperationException( "Illegal to invoke setParent() on TagAdapter wrapper"); }
// in java/javax/servlet/jsp/tagext/TagAdapter.java
Override public int doStartTag() throws JspException { throw new UnsupportedOperationException( "Illegal to invoke doStartTag() on TagAdapter wrapper"); }
// in java/javax/servlet/jsp/tagext/TagAdapter.java
Override public int doEndTag() throws JspException { throw new UnsupportedOperationException( "Illegal to invoke doEndTag() on TagAdapter wrapper"); }
// in java/javax/servlet/jsp/tagext/TagAdapter.java
Override public void release() { throw new UnsupportedOperationException( "Illegal to invoke release() on TagAdapter wrapper"); }
// in java/javax/el/CompositeELResolver.java
Override public void remove() { throw new UnsupportedOperationException(); }
0 1
              
// in java/org/apache/catalina/connector/CometEventImpl.java
Override public void setTimeout(int timeout) throws IOException, ServletException, UnsupportedOperationException { if (request.getAttribute(Globals.COMET_TIMEOUT_SUPPORTED_ATTR) == Boolean.TRUE) { request.setAttribute(Globals.COMET_TIMEOUT_ATTR, Integer.valueOf(timeout)); if (request.isComet()) { request.setCometTimeout(timeout); } } else { throw new UnsupportedOperationException(); } }
(Domain) ClassFormatException 14
              
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
public static final String codeToString( byte[] code, ConstantPool constant_pool, int index, int length, boolean verbose ) { StringBuilder buf = new StringBuilder(code.length * 20); // Should be sufficient ByteSequence stream = new ByteSequence(code); try { for (int i = 0; i < index; i++) { codeToString(stream, constant_pool, verbose); } for (int i = 0; stream.available() > 0; i++) { if ((length < 0) || (i < length)) { String indices = fillup(stream.getIndex() + ":", 6, true, ' '); buf.append(indices).append(codeToString(stream, constant_pool, verbose)) .append('\n'); } } } catch (IOException e) { System.out.println(buf.toString()); e.printStackTrace(); throw new ClassFormatException("Byte code error: " + e, e); } return buf.toString(); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
public static final String methodSignatureToString( String signature, String name, String access, boolean chopit, LocalVariableTable vars ) throws ClassFormatException { StringBuilder buf = new StringBuilder("("); String type; int index; int var_index = (access.indexOf("static") >= 0) ? 0 : 1; try { // Read all declarations between for `(' and `)' if (signature.charAt(0) != '(') { throw new ClassFormatException("Invalid method signature: " + signature); } index = 1; // current string position while (signature.charAt(index) != ')') { String param_type = signatureToString(signature.substring(index), chopit); buf.append(param_type); if (vars != null) { LocalVariable l = vars.getLocalVariable(var_index); if (l != null) { buf.append(" ").append(l.getName()); } } else { buf.append(" arg").append(var_index); } if ("double".equals(param_type) || "long".equals(param_type)) { var_index += 2; } else { var_index++; } buf.append(", "); //corrected concurrent private static field acess index += unwrap(consumed_chars); // update position } index++; // update position // Read return type after `)' type = signatureToString(signature.substring(index), chopit); } catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); } if (buf.length() > 1) { buf.setLength(buf.length() - 2); } buf.append(")"); return access + ((access.length() > 0) ? " " : "") + // May be an empty string type + " " + name + buf.toString(); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
public static final String signatureToString( String signature, boolean chopit ) { //corrected concurrent private static field acess wrap(consumed_chars, 1); // This is the default, read just one char like `B' try { switch (signature.charAt(0)) { case 'B': return "byte"; case 'C': return "char"; case 'D': return "double"; case 'F': return "float"; case 'I': return "int"; case 'J': return "long"; case 'L': { // Full class name int index = signature.indexOf(';'); // Look for closing `;' if (index < 0) { throw new ClassFormatException("Invalid signature: " + signature); } //corrected concurrent private static field acess wrap(consumed_chars, index + 1); // "Lblabla;" `L' and `;' are removed return compactClassName(signature.substring(1, index), chopit); } case 'S': return "short"; case 'Z': return "boolean"; case '[': { // Array declaration int n; StringBuilder brackets; String type; int consumed_chars; // Shadows global var brackets = new StringBuilder(); // Accumulate []'s // Count opening brackets and look for optional size argument for (n = 0; signature.charAt(n) == '['; n++) { brackets.append("[]"); } consumed_chars = n; // Remember value // The rest of the string denotes a `<field_type>' type = signatureToString(signature.substring(n), chopit); //corrected concurrent private static field acess //Utility.consumed_chars += consumed_chars; is replaced by: int _temp = unwrap(Utility.consumed_chars) + consumed_chars; wrap(Utility.consumed_chars, _temp); return type + brackets.toString(); } case 'V': return "void"; default: throw new ClassFormatException("Invalid signature: `" + signature + "'"); } } catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid signature: " + signature, e); } }
// in java/org/apache/tomcat/util/bcel/classfile/Constant.java
static final Constant readConstant( DataInputStream file ) throws IOException, ClassFormatException { byte b = file.readByte(); // Read tag byte switch (b) { case Constants.CONSTANT_Class: return new ConstantClass(file); case Constants.CONSTANT_Fieldref: return new ConstantFieldref(file); case Constants.CONSTANT_Methodref: return new ConstantMethodref(file); case Constants.CONSTANT_InterfaceMethodref: return new ConstantInterfaceMethodref(file); case Constants.CONSTANT_String: return new ConstantString(file); case Constants.CONSTANT_Integer: return new ConstantInteger(file); case Constants.CONSTANT_Float: return new ConstantFloat(file); case Constants.CONSTANT_Long: return new ConstantLong(file); case Constants.CONSTANT_Double: return new ConstantDouble(file); case Constants.CONSTANT_NameAndType: return new ConstantNameAndType(file); case Constants.CONSTANT_Utf8: return new ConstantUtf8(file); default: throw new ClassFormatException("Invalid byte tag in constant pool: " + b); } }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public Constant getConstant( int index ) { if (index >= constant_pool.length || index < 0) { throw new ClassFormatException("Invalid constant pool reference: " + index + ". Constant pool size is: " + constant_pool.length); } return constant_pool[index]; }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public Constant getConstant( int index, byte tag ) throws ClassFormatException { Constant c; c = getConstant(index); if (c == null) { throw new ClassFormatException("Constant pool at index " + index + " is null."); } if (c.getTag() != tag) { throw new ClassFormatException("Expected class `" + Constants.CONSTANT_NAMES[tag] + "' at index " + index + " and got " + c); } return c; }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapTableEntry.java
public final void dump( DataOutputStream file ) throws IOException { file.write(frame_type); if (frame_type >= Constants.SAME_FRAME && frame_type <= Constants.SAME_FRAME_MAX) { // nothing to be done } else if (frame_type >= Constants.SAME_LOCALS_1_STACK_ITEM_FRAME && frame_type <= Constants.SAME_LOCALS_1_STACK_ITEM_FRAME_MAX) { types_of_stack_items[0].dump(file); } else if (frame_type == Constants.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { file.writeShort(byte_code_offset_delta); types_of_stack_items[0].dump(file); } else if (frame_type >= Constants.CHOP_FRAME && frame_type <= Constants.CHOP_FRAME_MAX) { file.writeShort(byte_code_offset_delta); } else if (frame_type == Constants.SAME_FRAME_EXTENDED) { file.writeShort(byte_code_offset_delta); } else if (frame_type >= Constants.APPEND_FRAME && frame_type <= Constants.APPEND_FRAME_MAX) { file.writeShort(byte_code_offset_delta); for (int i = 0; i < number_of_locals; i++) { types_of_locals[i].dump(file); } } else if (frame_type == Constants.FULL_FRAME) { file.writeShort(byte_code_offset_delta); file.writeShort(number_of_locals); for (int i = 0; i < number_of_locals; i++) { types_of_locals[i].dump(file); } file.writeShort(number_of_stack_items); for (int i = 0; i < number_of_stack_items; i++) { types_of_stack_items[i].dump(file); } } else { /* Can't happen */ throw new ClassFormatException ("Invalid Stack map table tag: " + frame_type); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readClassInfo() throws IOException, ClassFormatException { access_flags = file.readUnsignedShort(); /* Interfaces are implicitely abstract, the flag should be set * according to the JVM specification. */ if ((access_flags & Constants.ACC_INTERFACE) != 0) { access_flags |= Constants.ACC_ABSTRACT; } if (((access_flags & Constants.ACC_ABSTRACT) != 0) && ((access_flags & Constants.ACC_FINAL) != 0)) { throw new ClassFormatException("Class " + file_name + " can't be both final and abstract"); } class_name_index = file.readUnsignedShort(); superclass_name_index = file.readUnsignedShort(); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readID() throws IOException, ClassFormatException { int magic = 0xCAFEBABE; if (file.readInt() != magic) { throw new ClassFormatException(file_name + " is not a Java .class file"); } }
3
              
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (IOException e) { System.out.println(buf.toString()); e.printStackTrace(); throw new ClassFormatException("Byte code error: " + e, e); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid signature: " + signature, e); }
21
              
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
public static final String methodSignatureToString( String signature, String name, String access, boolean chopit, LocalVariableTable vars ) throws ClassFormatException { StringBuilder buf = new StringBuilder("("); String type; int index; int var_index = (access.indexOf("static") >= 0) ? 0 : 1; try { // Read all declarations between for `(' and `)' if (signature.charAt(0) != '(') { throw new ClassFormatException("Invalid method signature: " + signature); } index = 1; // current string position while (signature.charAt(index) != ')') { String param_type = signatureToString(signature.substring(index), chopit); buf.append(param_type); if (vars != null) { LocalVariable l = vars.getLocalVariable(var_index); if (l != null) { buf.append(" ").append(l.getName()); } } else { buf.append(" arg").append(var_index); } if ("double".equals(param_type) || "long".equals(param_type)) { var_index += 2; } else { var_index++; } buf.append(", "); //corrected concurrent private static field acess index += unwrap(consumed_chars); // update position } index++; // update position // Read return type after `)' type = signatureToString(signature.substring(index), chopit); } catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); } if (buf.length() > 1) { buf.setLength(buf.length() - 2); } buf.append(")"); return access + ((access.length() > 0) ? " " : "") + // May be an empty string type + " " + name + buf.toString(); }
// in java/org/apache/tomcat/util/bcel/classfile/Constant.java
static final Constant readConstant( DataInputStream file ) throws IOException, ClassFormatException { byte b = file.readByte(); // Read tag byte switch (b) { case Constants.CONSTANT_Class: return new ConstantClass(file); case Constants.CONSTANT_Fieldref: return new ConstantFieldref(file); case Constants.CONSTANT_Methodref: return new ConstantMethodref(file); case Constants.CONSTANT_InterfaceMethodref: return new ConstantInterfaceMethodref(file); case Constants.CONSTANT_String: return new ConstantString(file); case Constants.CONSTANT_Integer: return new ConstantInteger(file); case Constants.CONSTANT_Float: return new ConstantFloat(file); case Constants.CONSTANT_Long: return new ConstantLong(file); case Constants.CONSTANT_Double: return new ConstantDouble(file); case Constants.CONSTANT_NameAndType: return new ConstantNameAndType(file); case Constants.CONSTANT_Utf8: return new ConstantUtf8(file); default: throw new ClassFormatException("Invalid byte tag in constant pool: " + b); } }
// in java/org/apache/tomcat/util/bcel/classfile/Attribute.java
public static final Attribute readAttribute(DataInputStream file, ConstantPool constant_pool) throws IOException, ClassFormatException { ConstantUtf8 c; String name; int name_index; int length; byte tag = Constants.ATTR_UNKNOWN; // Unknown attribute // Get class name from constant pool via `name_index' indirection name_index = file.readUnsignedShort(); c = (ConstantUtf8) constant_pool.getConstant(name_index, Constants.CONSTANT_Utf8); name = c.getBytes(); // Length of data in bytes length = file.readInt(); // Compare strings to find known attribute // System.out.println(name); for (byte i = 0; i < Constants.KNOWN_ATTRIBUTES; i++) { if (name.equals(Constants.ATTRIBUTE_NAMES[i])) { tag = i; // found! break; } } // Call proper constructor, depending on `tag' switch (tag) { case Constants.ATTR_UNKNOWN: AttributeReader r = readers.get(name); if (r != null) { return r.createAttribute(name_index, length, file, constant_pool); } return new Unknown(name_index, length, file, constant_pool); case Constants.ATTR_CONSTANT_VALUE: return new ConstantValue(name_index, length, file, constant_pool); case Constants.ATTR_SOURCE_FILE: return new SourceFile(name_index, length, file, constant_pool); case Constants.ATTR_CODE: return new Code(name_index, length, file, constant_pool); case Constants.ATTR_EXCEPTIONS: return new ExceptionTable(name_index, length, file, constant_pool); case Constants.ATTR_LINE_NUMBER_TABLE: return new LineNumberTable(name_index, length, file, constant_pool); case Constants.ATTR_LOCAL_VARIABLE_TABLE: return new LocalVariableTable(name_index, length, file, constant_pool); case Constants.ATTR_INNER_CLASSES: return new InnerClasses(name_index, length, file, constant_pool); case Constants.ATTR_SYNTHETIC: return new Synthetic(name_index, length, file, constant_pool); case Constants.ATTR_DEPRECATED: return new Deprecated(name_index, length, file, constant_pool); case Constants.ATTR_PMG: return new PMGClass(name_index, length, file, constant_pool); case Constants.ATTR_SIGNATURE: return new Signature(name_index, length, file, constant_pool); case Constants.ATTR_STACK_MAP: return new StackMap(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIME_VISIBLE_ANNOTATIONS: return new RuntimeVisibleAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIMEIN_VISIBLE_ANNOTATIONS: return new RuntimeInvisibleAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS: return new RuntimeVisibleParameterAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIMEIN_VISIBLE_PARAMETER_ANNOTATIONS: return new RuntimeInvisibleParameterAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_ANNOTATION_DEFAULT: return new AnnotationDefault(name_index, length, file, constant_pool); case Constants.ATTR_LOCAL_VARIABLE_TYPE_TABLE: return new LocalVariableTypeTable(name_index, length, file, constant_pool); case Constants.ATTR_ENCLOSING_METHOD: return new EnclosingMethod(name_index, length, file, constant_pool); case Constants.ATTR_STACK_MAP_TABLE: return new StackMapTable(name_index, length, file, constant_pool); default: // Never reached throw new IllegalStateException("Unrecognized attribute type tag parsed: " + tag); } }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public String constantToString( Constant c ) throws ClassFormatException { String str; int i; byte tag = c.getTag(); switch (tag) { case Constants.CONSTANT_Class: i = ((ConstantClass) c).getNameIndex(); c = getConstant(i, Constants.CONSTANT_Utf8); str = Utility.compactClassName(((ConstantUtf8) c).getBytes(), false); break; case Constants.CONSTANT_String: i = ((ConstantString) c).getStringIndex(); c = getConstant(i, Constants.CONSTANT_Utf8); str = "\"" + escape(((ConstantUtf8) c).getBytes()) + "\""; break; case Constants.CONSTANT_Utf8: str = ((ConstantUtf8) c).getBytes(); break; case Constants.CONSTANT_Double: str = String.valueOf(((ConstantDouble) c).getBytes()); break; case Constants.CONSTANT_Float: str = String.valueOf(((ConstantFloat) c).getBytes()); break; case Constants.CONSTANT_Long: str = String.valueOf(((ConstantLong) c).getBytes()); break; case Constants.CONSTANT_Integer: str = String.valueOf(((ConstantInteger) c).getBytes()); break; case Constants.CONSTANT_NameAndType: str = (constantToString(((ConstantNameAndType) c).getNameIndex(), Constants.CONSTANT_Utf8) + " " + constantToString(((ConstantNameAndType) c).getSignatureIndex(), Constants.CONSTANT_Utf8)); break; case Constants.CONSTANT_InterfaceMethodref: case Constants.CONSTANT_Methodref: case Constants.CONSTANT_Fieldref: str = (constantToString(((ConstantCP) c).getClassIndex(), Constants.CONSTANT_Class) + "." + constantToString(((ConstantCP) c).getNameAndTypeIndex(), Constants.CONSTANT_NameAndType)); break; default: // Never reached throw new RuntimeException("Unknown constant type " + tag); } return str; }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public String constantToString( int index, byte tag ) throws ClassFormatException { Constant c = getConstant(index, tag); return constantToString(c); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public Constant getConstant( int index, byte tag ) throws ClassFormatException { Constant c; c = getConstant(index); if (c == null) { throw new ClassFormatException("Constant pool at index " + index + " is null."); } if (c.getTag() != tag) { throw new ClassFormatException("Expected class `" + Constants.CONSTANT_NAMES[tag] + "' at index " + index + " and got " + c); } return c; }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public String getConstantString( int index, byte tag ) throws ClassFormatException { Constant c; int i; c = getConstant(index, tag); /* This switch() is not that elegant, since the two classes have the * same contents, they just differ in the name of the index * field variable. * But we want to stick to the JVM naming conventions closely though * we could have solved these more elegantly by using the same * variable name or by subclassing. */ switch (tag) { case Constants.CONSTANT_Class: i = ((ConstantClass) c).getNameIndex(); break; case Constants.CONSTANT_String: i = ((ConstantString) c).getStringIndex(); break; default: throw new RuntimeException("getConstantString called with illegal tag " + tag); } // Finally get the string from the constant pool c = getConstant(i, Constants.CONSTANT_Utf8); return ((ConstantUtf8) c).getBytes(); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
public JavaClass parse() throws IOException, ClassFormatException { /****************** Read headers ********************************/ // Check magic tag of class file readID(); // Get compiler version readVersion(); /****************** Read constant pool and related **************/ // Read constant pool entries readConstantPool(); // Get class information readClassInfo(); // Get interface information, i.e., implemented interfaces readInterfaces(); /****************** Read class fields and methods ***************/ // Read class fields, i.e., the variables of the class readFields(); // Read class methods, i.e., the functions in the class readMethods(); // Read class attributes readAttributes(); // Check for unknown variables //Unknown[] u = Unknown.getUnknownAttributes(); //for(int i=0; i < u.length; i++) // System.err.println("WARNING: " + u[i]); // Everything should have been read now // if(file.available() > 0) { // int bytes = file.available(); // byte[] buf = new byte[bytes]; // file.read(buf); // if(!(is_zip && (buf.length == 1))) { // System.err.println("WARNING: Trailing garbage at end of " + file_name); // System.err.println(bytes + " extra bytes: " + Utility.toHexString(buf)); // } // } // Return the information we have gathered in a new object return new JavaClass(class_name_index, superclass_name_index, file_name, major, minor, access_flags, constant_pool, interfaces, fields, methods, attributes); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readAttributes() throws IOException, ClassFormatException { int attributes_count; attributes_count = file.readUnsignedShort(); attributes = new Attribute[attributes_count]; for (int i = 0; i < attributes_count; i++) { attributes[i] = Attribute.readAttribute(file, constant_pool); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readClassInfo() throws IOException, ClassFormatException { access_flags = file.readUnsignedShort(); /* Interfaces are implicitely abstract, the flag should be set * according to the JVM specification. */ if ((access_flags & Constants.ACC_INTERFACE) != 0) { access_flags |= Constants.ACC_ABSTRACT; } if (((access_flags & Constants.ACC_ABSTRACT) != 0) && ((access_flags & Constants.ACC_FINAL) != 0)) { throw new ClassFormatException("Class " + file_name + " can't be both final and abstract"); } class_name_index = file.readUnsignedShort(); superclass_name_index = file.readUnsignedShort(); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readConstantPool() throws IOException, ClassFormatException { constant_pool = new ConstantPool(file); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readFields() throws IOException, ClassFormatException { int fields_count; fields_count = file.readUnsignedShort(); fields = new Field[fields_count]; for (int i = 0; i < fields_count; i++) { fields[i] = new Field(file, constant_pool); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readID() throws IOException, ClassFormatException { int magic = 0xCAFEBABE; if (file.readInt() != magic) { throw new ClassFormatException(file_name + " is not a Java .class file"); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readInterfaces() throws IOException, ClassFormatException { int interfaces_count; interfaces_count = file.readUnsignedShort(); interfaces = new int[interfaces_count]; for (int i = 0; i < interfaces_count; i++) { interfaces[i] = file.readUnsignedShort(); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readMethods() throws IOException, ClassFormatException { int methods_count; methods_count = file.readUnsignedShort(); methods = new Method[methods_count]; for (int i = 0; i < methods_count; i++) { methods[i] = new Method(file, constant_pool); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readVersion() throws IOException, ClassFormatException { minor = file.readUnsignedShort(); major = file.readUnsignedShort(); }
// in java/org/apache/catalina/startup/ContextConfig.java
protected void processAnnotationsStream(InputStream is, WebXml fragment) throws ClassFormatException, IOException { ClassParser parser = new ClassParser(is, null); JavaClass clazz = parser.parse(); checkHandlesTypes(clazz); String className = clazz.getClassName(); AnnotationEntry[] annotationsEntries = clazz.getAnnotationEntries(); for (AnnotationEntry ae : annotationsEntries) { String type = ae.getAnnotationType(); if ("Ljavax/servlet/annotation/WebServlet;".equals(type)) { processAnnotationWebServlet(className, ae, fragment); }else if ("Ljavax/servlet/annotation/WebFilter;".equals(type)) { processAnnotationWebFilter(className, ae, fragment); }else if ("Ljavax/servlet/annotation/WebListener;".equals(type)) { fragment.addListener(className); } else { // Unknown annotation - ignore } } }
(Lib) Exception 13
              
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.UseBean n) throws JasperException { String name = n.getTextAttribute("id"); String scope = n.getTextAttribute("scope"); String klass = n.getTextAttribute("class"); String type = n.getTextAttribute("type"); Node.JspAttribute beanName = n.getBeanName(); // If "class" is specified, try an instantiation at compile time boolean generateNew = false; String canonicalName = null; // Canonical name for klass if (klass != null) { try { Class<?> bean = ctxt.getClassLoader().loadClass(klass); if (klass.indexOf('$') >= 0) { // Obtain the canonical type name canonicalName = bean.getCanonicalName(); } else { canonicalName = klass; } int modifiers = bean.getModifiers(); if (!Modifier.isPublic(modifiers) || Modifier.isInterface(modifiers) || Modifier.isAbstract(modifiers)) { throw new Exception("Invalid bean class modifier"); } // Check that there is a 0 arg constructor bean.getConstructor(new Class[] {}); // At compile time, we have determined that the bean class // exists, with a public zero constructor, new() can be // used for bean instantiation. generateNew = true; } catch (Exception e) { // Cannot instantiate the specified class, either a // compilation error or a runtime error will be raised, // depending on a compiler flag. if (ctxt.getOptions() .getErrorOnUseBeanInvalidClassAttribute()) { err.jspError(n, "jsp.error.invalid.bean", klass); } if (canonicalName == null) { // Doing our best here to get a canonical name // from the binary name, should work 99.99% of time. canonicalName = klass.replace('$', '.'); } } if (type == null) { // if type is unspecified, use "class" as type of bean type = canonicalName; } } // JSP.5.1, Sematics, para 1 - lock not required for request or // page scope String scopename = "javax.servlet.jsp.PageContext.PAGE_SCOPE"; // Default to page String lock = null; if ("request".equals(scope)) { scopename = "javax.servlet.jsp.PageContext.REQUEST_SCOPE"; } else if ("session".equals(scope)) { scopename = "javax.servlet.jsp.PageContext.SESSION_SCOPE"; lock = "session"; } else if ("application".equals(scope)) { scopename = "javax.servlet.jsp.PageContext.APPLICATION_SCOPE"; lock = "application"; } n.setBeginJavaLine(out.getJavaLine()); // Declare bean out.printin(type); out.print(' '); out.print(name); out.println(" = null;"); // Lock (if required) while getting or creating bean if (lock != null) { out.printin("synchronized ("); out.print(lock); out.println(") {"); out.pushIndent(); } // Locate bean from context out.printin(name); out.print(" = ("); out.print(type); out.print(") _jspx_page_context.getAttribute("); out.print(quote(name)); out.print(", "); out.print(scopename); out.println(");"); // Create bean /* * Check if bean is already there */ out.printin("if ("); out.print(name); out.println(" == null){"); out.pushIndent(); if (klass == null && beanName == null) { /* * If both class name and beanName is not specified, the bean * must be found locally, otherwise it's an error */ out.printin("throw new java.lang.InstantiationException(\"bean "); out.print(name); out.println(" not found within scope\");"); } else { /* * Instantiate the bean if it is not in the specified scope. */ if (!generateNew) { String binaryName; if (beanName != null) { if (beanName.isNamedAttribute()) { // If the value for beanName was specified via // jsp:attribute, first generate code to evaluate // that body. binaryName = generateNamedAttributeValue(beanName .getNamedAttributeNode()); } else { binaryName = attributeValue(beanName, false, String.class); } } else { // Implies klass is not null binaryName = quote(klass); } out.printil("try {"); out.pushIndent(); out.printin(name); out.print(" = ("); out.print(type); out.print(") java.beans.Beans.instantiate("); out.print("this.getClass().getClassLoader(), "); out.print(binaryName); out.println(");"); out.popIndent(); /* * Note: Beans.instantiate throws ClassNotFoundException if * the bean class is abstract. */ out.printil("} catch (java.lang.ClassNotFoundException exc) {"); out.pushIndent(); out.printil("throw new InstantiationException(exc.getMessage());"); out.popIndent(); out.printil("} catch (java.lang.Exception exc) {"); out.pushIndent(); out.printin("throw new javax.servlet.ServletException("); out.print("\"Cannot create bean of class \" + "); out.print(binaryName); out.println(", exc);"); out.popIndent(); out.printil("}"); // close of try } else { // Implies klass is not null // Generate codes to instantiate the bean class out.printin(name); out.print(" = new "); out.print(canonicalName); out.println("();"); } /* * Set attribute for bean in the specified scope */ out.printin("_jspx_page_context.setAttribute("); out.print(quote(name)); out.print(", "); out.print(name); out.print(", "); out.print(scopename); out.println(");"); // Only visit the body when bean is instantiated visitBody(n); } out.popIndent(); out.printil("}"); // End of lock block if (lock != null) { out.popIndent(); out.printil("}"); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
Override public void bind() throws Exception { // Create the root APR memory pool try { rootPool = Pool.create(0); } catch (UnsatisfiedLinkError e) { throw new Exception(sm.getString("endpoint.init.notavail")); } // Create the pool for the server socket serverSockPool = Pool.create(rootPool); // Create the APR address that will be bound String addressStr = null; if (getAddress() != null) { addressStr = getAddress().getHostAddress(); } int family = Socket.APR_INET; if (Library.APR_HAVE_IPV6) { if (addressStr == null) { if (!OS.IS_BSD && !OS.IS_WIN32 && !OS.IS_WIN64) family = Socket.APR_UNSPEC; } else if (addressStr.indexOf(':') >= 0) { family = Socket.APR_UNSPEC; } } long inetAddress = Address.info(addressStr, family, getPort(), 0, rootPool); // Create the APR server socket serverSock = Socket.create(Address.getInfo(inetAddress).family, Socket.SOCK_STREAM, Socket.APR_PROTO_TCP, rootPool); if (OS.IS_UNIX) { Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Deal with the firewalls that tend to drop the inactive sockets Socket.optSet(serverSock, Socket.APR_SO_KEEPALIVE, 1); // Bind the server socket int ret = Socket.bind(serverSock, inetAddress); if (ret != 0) { throw new Exception(sm.getString("endpoint.init.bind", "" + ret, Error.strerror(ret))); } // Start listening on the server socket ret = Socket.listen(serverSock, getBacklog()); if (ret != 0) { throw new Exception(sm.getString("endpoint.init.listen", "" + ret, Error.strerror(ret))); } if (OS.IS_WIN32 || OS.IS_WIN64) { // On Windows set the reuseaddr flag after the bind/listen Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Sendfile usage on systems which don't support it cause major problems if (useSendfile && !Library.APR_HAS_SENDFILE) { useSendfile = false; } // Initialize thread count defaults for acceptor, poller and sendfile if (acceptorThreadCount == 0) { // FIXME: Doesn't seem to work that well with multiple accept threads acceptorThreadCount = 1; } if (pollerThreadCount == 0) { if ((OS.IS_WIN32 || OS.IS_WIN64) && (getMaxConnections() > 1024)) { // The maximum per poller to get reasonable performance is 1024 pollerThreadCount = getMaxConnections() / 1024; // Adjust poller size so that it won't reach the limit setMaxConnections( getMaxConnections() - (getMaxConnections() % 1024)); } else { // No explicit poller size limitation pollerThreadCount = 1; } } if (sendfileThreadCount == 0) { if ((OS.IS_WIN32 || OS.IS_WIN64) && (sendfileSize > 1024)) { // The maximum per poller to get reasonable performance is 1024 sendfileThreadCount = sendfileSize / 1024; // Adjust poller size so that it won't reach the limit sendfileSize = sendfileSize - (sendfileSize % 1024); } else { // No explicit poller size limitation // FIXME: Default to one per CPU ? sendfileThreadCount = 1; } } // Delay accepting of new connections until data is available // Only Linux kernels 2.4 + have that implemented // on other platforms this call is noop and will return APR_ENOTIMPL. if (deferAccept) { if (Socket.optSet(serverSock, Socket.APR_TCP_DEFER_ACCEPT, 1) == Status.APR_ENOTIMPL) { deferAccept = false; } } // Initialize SSL if needed if (isSSLEnabled()) { if (SSLCertificateFile == null) { // This is required throw new Exception(sm.getString("endpoint.apr.noSslCertFile")); } // SSL protocol int value; // This branch can be removed, once the required version is at least 1.1.21. int tcnFullVersion = Library.TCN_MAJOR_VERSION * 1000 + Library.TCN_MINOR_VERSION * 100 + Library.TCN_PATCH_VERSION; if (tcnFullVersion <= 1120) { value = SSL.SSL_PROTOCOL_ALL; if ("SSLv2".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_SSLV2; } else if ("SSLv3".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_SSLV3; } else if ("TLSv1".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_TLSV1; } else if ("SSLv2+SSLv3".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_SSLV2 | SSL.SSL_PROTOCOL_SSLV3; } else if ("all".equalsIgnoreCase(SSLProtocol) || SSLProtocol == null || SSLProtocol.length() == 0) { // NOOP, use the default defined above } else { // Protocol not recognized, fail to start as it is safer than // continuing with the default which might enable more than the // is required throw new Exception(sm.getString( "endpoint.apr.invalidSslProtocol", SSLProtocol)); } } else { value = SSL.SSL_PROTOCOL_NONE; if (SSLProtocol == null || SSLProtocol.length() == 0) { value = SSL.SSL_PROTOCOL_ALL; } else { for (String protocol : SSLProtocol.split("\\+")) { protocol = protocol.trim(); if ("SSLv2".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_SSLV2; } else if ("SSLv3".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_SSLV3; } else if ("TLSv1".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_TLSV1; } else if ("all".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_ALL; } else { // Protocol not recognized, fail to start as it is safer than // continuing with the default which might enable more than the // is required throw new Exception(sm.getString( "endpoint.apr.invalidSslProtocol", SSLProtocol)); } } } } // Create SSL Context sslContext = SSLContext.make(rootPool, value, SSL.SSL_MODE_SERVER); if (SSLInsecureRenegotiation) { boolean legacyRenegSupported = false; try { legacyRenegSupported = SSL.hasOp(SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); if (legacyRenegSupported) SSLContext.setOptions(sslContext, SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); } catch (UnsatisfiedLinkError e) { // Ignore } if (!legacyRenegSupported) { // OpenSSL does not support unsafe legacy renegotiation. log.warn(sm.getString("endpoint.warn.noInsecureReneg", SSL.versionString())); } } // List the ciphers that the client is permitted to negotiate SSLContext.setCipherSuite(sslContext, SSLCipherSuite); // Load Server key and certificate SSLContext.setCertificate(sslContext, SSLCertificateFile, SSLCertificateKeyFile, SSLPassword, SSL.SSL_AIDX_RSA); // Set certificate chain file SSLContext.setCertificateChainFile(sslContext, SSLCertificateChainFile, false); // Support Client Certificates SSLContext.setCACertificate(sslContext, SSLCACertificateFile, SSLCACertificatePath); // Set revocation SSLContext.setCARevocation(sslContext, SSLCARevocationFile, SSLCARevocationPath); // Client certificate verification value = SSL.SSL_CVERIFY_NONE; if ("optional".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_OPTIONAL; } else if ("require".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_REQUIRE; } else if ("optionalNoCA".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_OPTIONAL_NO_CA; } SSLContext.setVerify(sslContext, value, SSLVerifyDepth); // For now, sendfile is not supported with SSL useSendfile = false; } }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsSerSource.java
public void execute() throws Exception { if( registry==null ) registry=Registry.getRegistry(null, null); long t1=System.currentTimeMillis(); try { InputStream stream=null; if( source instanceof URL ) { stream=((URL)source).openStream(); } if( source instanceof InputStream ) { stream=(InputStream)source; } if( stream==null ) { throw new Exception( "Can't process "+ source); } ObjectInputStream ois=new ObjectInputStream(stream); Thread.currentThread().setContextClassLoader(ManagedBean.class.getClassLoader()); Object obj=ois.readObject(); //log.info("Reading " + obj); ManagedBean beans[]=(ManagedBean[])obj; // after all are read without error for( int i=0; i<beans.length; i++ ) { registry.addManagedBean(beans[i]); } } catch( Exception ex ) { log.error( "Error reading descriptors " + source + " " + ex.toString(), ex); throw ex; } long t2=System.currentTimeMillis(); log.info( "Reading descriptors ( ser ) " + (t2-t1)); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
private Service getService(ObjectName oname) throws Exception { if (container instanceof Service) { // Don't bother checking the domain - this is the only option return (Service) container; } StandardService service = null; String domain = oname.getDomain(); if (container instanceof Server) { Service[] services = ((Server)container).findServices(); for (int i = 0; i < services.length; i++) { service = (StandardService) services[i]; if (domain.equals(service.getObjectName().getDomain())) { break; } } } if (service == null || !service.getObjectName().getDomain().equals(domain)) { throw new Exception("Service with the domain is not found"); } return service; }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createStandardServiceEngine(String domain, String defaultHost, String baseDir) throws Exception{ if (!(container instanceof Server)) { throw new Exception("Container not Server"); } StandardEngine engine = new StandardEngine(); engine.setDomain(domain); engine.setName(domain); engine.setDefaultHost(defaultHost); Service service = new StandardService(); service.setContainer(engine); service.setName(domain); ((Server) container).addService(service); return engine.getObjectName().toString(); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeService(String name) throws Exception { if (!(container instanceof Server)) { throw new Exception(); } // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(name); Service service = getService(oname); ((Server) container).removeService(service); }
// in java/org/apache/catalina/ha/backend/TcpSender.java
Override public void init(HeartbeatListener config) throws Exception { this.config = config; StringTokenizer tok = new StringTokenizer(config.getProxyList(), ","); proxies = new Proxy[tok.countTokens()]; int i = 0; while (tok.hasMoreTokens()) { String token = tok.nextToken().trim(); int pos = token.indexOf(':'); if (pos <=0) throw new Exception("bad ProxyList"); proxies[i] = new Proxy(); proxies[i].port = Integer.parseInt(token.substring(pos + 1)); try { proxies[i].address = InetAddress.getByName(token.substring(0, pos)); } catch (Exception e) { throw new Exception("bad ProxyList"); } i++; } connections = new Socket[proxies.length]; connectionReaders = new BufferedReader[proxies.length]; connectionWriters = new BufferedWriter[proxies.length]; }
2
              
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (UnsatisfiedLinkError e) { throw new Exception(sm.getString("endpoint.init.notavail")); }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (Exception e) { throw new Exception("bad ProxyList"); }
297
              
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
public void mapFunction(String fnQName, final Class<?> c, final String methodName, final Class<?>[] args) { java.lang.reflect.Method method; if (SecurityUtil.isPackageProtectionEnabled()) { try { method = AccessController.doPrivileged( new PrivilegedExceptionAction<Method>() { @Override public Method run() throws Exception { return c.getDeclaredMethod(methodName, args); } }); } catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); } }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
Override public Method run() throws Exception { return c.getDeclaredMethod(methodName, args); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
public static ProtectedFunctionMapper getMapForFunction(String fnQName, final Class<?> c, final String methodName, final Class<?>[] args) { java.lang.reflect.Method method; ProtectedFunctionMapper funcMapper; if (SecurityUtil.isPackageProtectionEnabled()) { funcMapper = AccessController.doPrivileged( new PrivilegedAction<ProtectedFunctionMapper>() { @Override public ProtectedFunctionMapper run() { return new ProtectedFunctionMapper(); } }); try { method = AccessController.doPrivileged( new PrivilegedExceptionAction<Method>() { @Override public Method run() throws Exception { return c.getDeclaredMethod(methodName, args); } }); } catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); } }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
Override public Method run() throws Exception { return c.getDeclaredMethod(methodName, args); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void include(final String relativeUrlPath, final boolean flush) throws ServletException, IOException { if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doInclude(relativeUrlPath, flush); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public Void run() throws Exception { doInclude(relativeUrlPath, flush); return null; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void forward(final String relativeUrlPath) throws ServletException, IOException { if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doForward(relativeUrlPath); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public Void run() throws Exception { doForward(relativeUrlPath); return null; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void handlePageException(final Throwable t) throws IOException, ServletException { if (t == null) throw new NullPointerException("null Throwable"); if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doHandlePageException(t); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public Void run() throws Exception { doHandlePageException(t); return null; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
public static Object proprietaryEvaluate(final String expression, final Class<?> expectedType, final PageContext pageContext, final ProtectedFunctionMapper functionMap, final boolean escape) throws ELException { Object retValue; final ExpressionFactory exprFactory = jspf.getJspApplicationContext(pageContext.getServletContext()).getExpressionFactory(); if (SecurityUtil.isPackageProtectionEnabled()) { try { retValue = AccessController .doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { ELContextImpl ctx = (ELContextImpl) pageContext.getELContext(); ctx.setFunctionMapper(new FunctionMapperImpl(functionMap)); ValueExpression ve = exprFactory.createValueExpression(ctx, expression, expectedType); return ve.getValue(ctx); } }); } catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public Object run() throws Exception { ELContextImpl ctx = (ELContextImpl) pageContext.getELContext(); ctx.setFunctionMapper(new FunctionMapperImpl(functionMap)); ValueExpression ve = exprFactory.createValueExpression(ctx, expression, expectedType); return ve.getValue(ctx); }
// in java/org/apache/jasper/compiler/Compiler.java
protected String[] generateJava() throws Exception { String[] smapStr = null; long t1, t2, t3, t4; t1 = t2 = t3 = t4 = 0; if (log.isDebugEnabled()) { t1 = System.currentTimeMillis(); } // Setup page info area pageInfo = new PageInfo(new BeanRepository(ctxt.getClassLoader(), errDispatcher), ctxt.getJspFile()); JspConfig jspConfig = options.getJspConfig(); JspConfig.JspProperty jspProperty = jspConfig.findJspProperty(ctxt .getJspFile()); /* * If the current uri is matched by a pattern specified in a * jsp-property-group in web.xml, initialize pageInfo with those * properties. */ if (jspProperty.isELIgnored() != null) { pageInfo.setELIgnored(JspUtil.booleanValue(jspProperty .isELIgnored())); } if (jspProperty.isScriptingInvalid() != null) { pageInfo.setScriptingInvalid(JspUtil.booleanValue(jspProperty .isScriptingInvalid())); } if (jspProperty.getIncludePrelude() != null) { pageInfo.setIncludePrelude(jspProperty.getIncludePrelude()); } if (jspProperty.getIncludeCoda() != null) { pageInfo.setIncludeCoda(jspProperty.getIncludeCoda()); } if (jspProperty.isDeferedSyntaxAllowedAsLiteral() != null) { pageInfo.setDeferredSyntaxAllowedAsLiteral(JspUtil.booleanValue(jspProperty .isDeferedSyntaxAllowedAsLiteral())); } if (jspProperty.isTrimDirectiveWhitespaces() != null) { pageInfo.setTrimDirectiveWhitespaces(JspUtil.booleanValue(jspProperty .isTrimDirectiveWhitespaces())); } // Default ContentType processing is deferred until after the page has // been parsed if (jspProperty.getBuffer() != null) { pageInfo.setBufferValue(jspProperty.getBuffer(), null, errDispatcher); } if (jspProperty.isErrorOnUndeclaredNamespace() != null) { pageInfo.setErrorOnUndeclaredNamespace( JspUtil.booleanValue( jspProperty.isErrorOnUndeclaredNamespace())); } if (ctxt.isTagFile()) { try { double libraryVersion = Double.parseDouble(ctxt.getTagInfo() .getTagLibrary().getRequiredVersion()); if (libraryVersion < 2.0) { pageInfo.setIsELIgnored("true", null, errDispatcher, true); } if (libraryVersion < 2.1) { pageInfo.setDeferredSyntaxAllowedAsLiteral("true", null, errDispatcher, true); } } catch (NumberFormatException ex) { errDispatcher.jspError(ex); } } ctxt.checkOutputDir(); String javaFileName = ctxt.getServletJavaFileName(); ServletWriter writer = null; try { /* * The setting of isELIgnored changes the behaviour of the parser * in subtle ways. To add to the 'fun', isELIgnored can be set in * any file that forms part of the translation unit so setting it * in a file included towards the end of the translation unit can * change how the parser should have behaved when parsing content * up to the point where isELIgnored was set. Arghh! * Previous attempts to hack around this have only provided partial * solutions. We now use two passes to parse the translation unit. * The first just parses the directives and the second parses the * whole translation unit once we know how isELIgnored has been set. * TODO There are some possible optimisations of this process. */ // Parse the file ParserController parserCtl = new ParserController(ctxt, this); // Pass 1 - the directives Node.Nodes directives = parserCtl.parseDirectives(ctxt.getJspFile()); Validator.validateDirectives(this, directives); // Pass 2 - the whole translation unit pageNodes = parserCtl.parse(ctxt.getJspFile()); // Leave this until now since it can only be set once - bug 49726 if (pageInfo.getContentType() == null && jspProperty.getDefaultContentType() != null) { pageInfo.setContentType(jspProperty.getDefaultContentType()); } if (ctxt.isPrototypeMode()) { // generate prototype .java file for the tag file writer = setupContextWriter(javaFileName); Generator.generate(writer, this, pageNodes); writer.close(); writer = null; return null; } // Validate and process attributes - don't re-validate the // directives we validated in pass 1 Validator.validateExDirectives(this, pageNodes); if (log.isDebugEnabled()) { t2 = System.currentTimeMillis(); } // Collect page info Collector.collect(this, pageNodes); // Compile (if necessary) and load the tag files referenced in // this compilation unit. tfp = new TagFileProcessor(); tfp.loadTagFiles(this, pageNodes); if (log.isDebugEnabled()) { t3 = System.currentTimeMillis(); } // Determine which custom tag needs to declare which scripting vars ScriptingVariabler.set(pageNodes, errDispatcher); // Optimizations by Tag Plugins TagPluginManager tagPluginManager = options.getTagPluginManager(); tagPluginManager.apply(pageNodes, errDispatcher, pageInfo); // Optimization: concatenate contiguous template texts. TextOptimizer.concatenate(this, pageNodes); // Generate static function mapper codes. ELFunctionMapper.map(pageNodes); // generate servlet .java file writer = setupContextWriter(javaFileName); Generator.generate(writer, this, pageNodes); writer.close(); writer = null; // The writer is only used during the compile, dereference // it in the JspCompilationContext when done to allow it // to be GC'd and save memory. ctxt.setWriter(null); if (log.isDebugEnabled()) { t4 = System.currentTimeMillis(); log.debug("Generated " + javaFileName + " total=" + (t4 - t1) + " generate=" + (t4 - t3) + " validate=" + (t2 - t1)); } } catch (Exception e) { if (writer != null) { try { writer.close(); writer = null; } catch (Exception e1) { // do nothing } } // Remove the generated .java file File file = new File(javaFileName); if (file.exists()) { if (!file.delete()) { log.warn(Localizer.getMessage( "jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath())); } } throw e; } finally { if (writer != null) { try { writer.close(); } catch (Exception e2) { // do nothing } } } // JSR45 Support if (!options.isSmapSuppressed()) { smapStr = SmapUtil.generateSmap(ctxt, pageNodes); } // If any proto type .java and .class files was generated, // the prototype .java may have been replaced by the current // compilation (if the tag file is self referencing), but the // .class file need to be removed, to make sure that javac would // generate .class again from the new .java file just generated. tfp.removeProtoTypeFiles(ctxt.getClassFileName()); return smapStr; }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile() throws FileNotFoundException, JasperException, Exception { compile(true); }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile(boolean compileClass) throws FileNotFoundException, JasperException, Exception { compile(compileClass, false); }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile(boolean compileClass, boolean jspcMode) throws FileNotFoundException, JasperException, Exception { if (errDispatcher == null) { this.errDispatcher = new ErrorDispatcher(jspcMode); } try { String[] smap = generateJava(); File javaFile = new File(ctxt.getServletJavaFileName()); Long jspLastModified = ctxt.getLastModified(ctxt.getJspFile()); javaFile.setLastModified(jspLastModified.longValue()); if (compileClass) { generateClass(smap); // Fix for bugzilla 41606 // Set JspServletWrapper.servletClassLastModifiedTime after successful compile String targetFileName = ctxt.getClassFileName(); if (targetFileName != null) { File targetFile = new File(targetFileName); if (targetFile.exists()) { targetFile.setLastModified(jspLastModified.longValue()); if (jsw != null) { jsw.setServletClassLastModifiedTime( jspLastModified.longValue()); } } } } } finally { if (tfp != null && ctxt.isPrototypeMode()) { tfp.removeProtoTypeFiles(null); } // Make sure these object which are only used during the // generation and compilation of the JSP page get // dereferenced so that they can be GC'd and reduce the // memory footprint. tfp = null; errDispatcher = null; pageInfo = null; // Only get rid of the pageNodes if in production. // In development mode, they are used for detailed // error messages. // http://issues.apache.org/bugzilla/show_bug.cgi?id=37062 if (!this.options.getDevelopment()) { pageNodes = null; } if (ctxt.getWriter() != null) { ctxt.getWriter().close(); ctxt.setWriter(null); } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private void tldScanWebXml() throws Exception { WebXml webXml = null; try { webXml = new WebXml(ctxt); if (webXml.getInputSource() == null) { return; } // Parse the web application deployment descriptor TreeNode webtld = null; webtld = new ParserUtils().parseXMLDocument(webXml.getSystemId(), webXml.getInputSource()); // Allow taglib to be an element of the root or jsp-config (JSP2.0) TreeNode jspConfig = webtld.findChild("jsp-config"); if (jspConfig != null) { webtld = jspConfig; } Iterator<TreeNode> taglibs = webtld.findChildren("taglib"); while (taglibs.hasNext()) { // Parse the next <taglib> element TreeNode taglib = taglibs.next(); String tagUri = null; String tagLoc = null; TreeNode child = taglib.findChild("taglib-uri"); if (child != null) tagUri = child.getBody(); child = taglib.findChild("taglib-location"); if (child != null) tagLoc = child.getBody(); // Save this location if appropriate if (tagLoc == null) continue; if (uriType(tagLoc) == NOROOT_REL_URI) tagLoc = "/WEB-INF/" + tagLoc; TldLocation location; if (tagLoc.endsWith(JAR_EXT)) { location = new TldLocation("META-INF/taglib.tld", ctxt.getResource(tagLoc).toString()); } else { location = new TldLocation(tagLoc); } mappings.put(tagUri, location); } } finally { if (webXml != null) { webXml.close(); } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private void tldScanResourcePaths(String startPath) throws Exception { Set<String> dirList = ctxt.getResourcePaths(startPath); if (dirList != null) { Iterator<String> it = dirList.iterator(); while (it.hasNext()) { String path = it.next(); if (!path.endsWith(TLD_EXT) && (path.startsWith(WEB_INF_LIB) || path.startsWith("/WEB-INF/classes/"))) { continue; } if (path.endsWith(TLD_EXT)) { if (path.startsWith("/WEB-INF/tags/") && !path.endsWith("implicit.tld")) { continue; } InputStream stream = ctxt.getResourceAsStream(path); try { tldScanStream(path, null, stream); } finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } } else { tldScanResourcePaths(path); } } } }
// in java/org/apache/jasper/compiler/JDTCompiler.java
Override protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception { long t1 = 0; if (log.isDebugEnabled()) { t1 = System.currentTimeMillis(); } final String sourceFile = ctxt.getServletJavaFileName(); final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath(); String packageName = ctxt.getServletPackageName(); final String targetClassName = ((packageName.length() != 0) ? (packageName + ".") : "") + ctxt.getServletClassName(); final ClassLoader classLoader = ctxt.getJspLoader(); String[] fileNames = new String[] {sourceFile}; String[] classNames = new String[] {targetClassName}; final ArrayList<JavacErrorDetail> problemList = new ArrayList<JavacErrorDetail>(); class CompilationUnit implements ICompilationUnit { private final String className; private final String sourceFile; CompilationUnit(String sourceFile, String className) { this.className = className; this.sourceFile = sourceFile; } @Override public char[] getFileName() { return sourceFile.toCharArray(); } @Override public char[] getContents() { char[] result = null; FileInputStream is = null; InputStreamReader isr = null; Reader reader = null; try { is = new FileInputStream(sourceFile); isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding()); reader = new BufferedReader(isr); char[] chars = new char[8192]; StringBuilder buf = new StringBuilder(); int count; while ((count = reader.read(chars, 0, chars.length)) > 0) { buf.append(chars, 0, count); } result = new char[buf.length()]; buf.getChars(0, result.length, result, 0); } catch (IOException e) { log.error("Compilation error", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) {/*Ignore*/} } if (isr != null) { try { isr.close(); } catch (IOException ioe) {/*Ignore*/} } if (is != null) { try { is.close(); } catch (IOException exc) {/*Ignore*/} } } return result; } @Override public char[] getMainTypeName() { int dot = className.lastIndexOf('.'); if (dot > 0) { return className.substring(dot + 1).toCharArray(); } return className.toCharArray(); } @Override public char[][] getPackageName() { StringTokenizer izer = new StringTokenizer(className, "."); char[][] result = new char[izer.countTokens()-1][]; for (int i = 0; i < result.length; i++) { String tok = izer.nextToken(); result[i] = tok.toCharArray(); } return result; } @SuppressWarnings("unused") // New method added to interface in // later JDT versions public boolean ignoreOptionalProblems() { return false; } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private static SAXParser getSAXParser( boolean validating, JspDocumentParser jspDocParser) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); // Preserve xmlns attributes factory.setFeature( "http://xml.org/sax/features/namespace-prefixes", true); factory.setValidating(validating); //factory.setFeature( // "http://xml.org/sax/features/validation", // validating); // Configure the parser SAXParser saxParser = factory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setProperty(LEXICAL_HANDLER_PROPERTY, jspDocParser); xmlReader.setErrorHandler(jspDocParser); return saxParser; }
// in java/org/apache/jasper/compiler/AntCompiler.java
Override protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception { long t1 = 0; if (log.isDebugEnabled()) { t1 = System.currentTimeMillis(); } String javaEncoding = ctxt.getOptions().getJavaEncoding(); String javaFileName = ctxt.getServletJavaFileName(); String classpath = ctxt.getClassPath(); String sep = System.getProperty("path.separator"); StringBuilder errorReport = new StringBuilder(); StringBuilder info=new StringBuilder(); info.append("Compile: javaFileName=" + javaFileName + "\n" ); info.append(" classpath=" + classpath + "\n" ); // Start capturing the System.err output for this thread SystemLogHandler.setThread(); // Initializing javac task getProject(); Javac javac = (Javac) project.createTask("javac"); // Initializing classpath Path path = new Path(project); path.setPath(System.getProperty("java.class.path")); info.append(" cp=" + System.getProperty("java.class.path") + "\n"); StringTokenizer tokenizer = new StringTokenizer(classpath, sep); while (tokenizer.hasMoreElements()) { String pathElement = tokenizer.nextToken(); File repository = new File(pathElement); path.setLocation(repository); info.append(" cp=" + repository + "\n"); } if( log.isDebugEnabled() ) log.debug( "Using classpath: " + System.getProperty("java.class.path") + sep + classpath); // Initializing sourcepath Path srcPath = new Path(project); srcPath.setLocation(options.getScratchDir()); info.append(" work dir=" + options.getScratchDir() + "\n"); // Initialize and set java extensions String exts = System.getProperty("java.ext.dirs"); if (exts != null) { Path extdirs = new Path(project); extdirs.setPath(exts); javac.setExtdirs(extdirs); info.append(" extension dir=" + exts + "\n"); } // Add endorsed directories if any are specified and we're forking // See Bugzilla 31257 if(ctxt.getOptions().getFork()) { String endorsed = System.getProperty("java.endorsed.dirs"); if(endorsed != null) { Javac.ImplementationSpecificArgument endorsedArg = javac.createCompilerArg(); endorsedArg.setLine("-J-Djava.endorsed.dirs=" + quotePathList(endorsed)); info.append(" endorsed dir=" + quotePathList(endorsed) + "\n"); } else { info.append(" no endorsed dirs specified\n"); } } // Configure the compiler object javac.setEncoding(javaEncoding); javac.setClasspath(path); javac.setDebug(ctxt.getOptions().getClassDebugInfo()); javac.setSrcdir(srcPath); javac.setTempdir(options.getScratchDir()); javac.setOptimize(! ctxt.getOptions().getClassDebugInfo() ); javac.setFork(ctxt.getOptions().getFork()); info.append(" srcDir=" + srcPath + "\n" ); // Set the Java compiler to use if (options.getCompiler() != null) { javac.setCompiler(options.getCompiler()); info.append(" compiler=" + options.getCompiler() + "\n"); } if (options.getCompilerTargetVM() != null) { javac.setTarget(options.getCompilerTargetVM()); info.append(" compilerTargetVM=" + options.getCompilerTargetVM() + "\n"); } if (options.getCompilerSourceVM() != null) { javac.setSource(options.getCompilerSourceVM()); info.append(" compilerSourceVM=" + options.getCompilerSourceVM() + "\n"); } // Build includes path PatternSet.NameEntry includes = javac.createInclude(); includes.setName(ctxt.getJavaPath()); info.append(" include="+ ctxt.getJavaPath() + "\n" ); BuildException be = null; try { if (ctxt.getOptions().getFork()) { javac.execute(); } else { synchronized(javacLock) { javac.execute(); } } } catch (BuildException e) { be = e; log.error(Localizer.getMessage("jsp.error.javac"), e); log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString()); } errorReport.append(logger.getReport()); // Stop capturing the System.err output for this thread String errorCapture = SystemLogHandler.unsetThread(); if (errorCapture != null) { errorReport.append(Constants.NEWLINE); errorReport.append(errorCapture); } if (!ctxt.keepGenerated()) { File javaFile = new File(javaFileName); javaFile.delete(); } if (be != null) { String errorReportString = errorReport.toString(); log.error(Localizer.getMessage("jsp.error.compilation", javaFileName, errorReportString)); JavacErrorDetail[] javacErrors = ErrorDispatcher.parseJavacErrors( errorReportString, javaFileName, pageNodes); if (javacErrors != null) { errDispatcher.javacError(javacErrors); } else { errDispatcher.javacError(errorReportString, be); } } if( log.isDebugEnabled() ) { long t2 = System.currentTimeMillis(); log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2-t1) + "ms"); } logger = null; project = null; if (ctxt.isPrototypeMode()) { return; } // JSR45 Support if (! options.isSmapSuppressed()) { SmapUtil.installSmap(smap); } }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof ResourceEnvRef) { Reference ref = (Reference) obj; ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } } // Note: No defaults here if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/factory/OpenEjbFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { Object beanObj = null; if (obj instanceof EjbRef) { Reference ref = (Reference) obj; String factory = DEFAULT_OPENEJB_FACTORY; RefAddr factoryRefAddr = ref.get("openejb.factory"); if (factoryRefAddr != null) { // Retrieving the OpenEJB factory factory = factoryRefAddr.getContent().toString(); } Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, factory); RefAddr linkRefAddr = ref.get("openejb.link"); if (linkRefAddr != null) { String ejbLink = linkRefAddr.getContent().toString(); beanObj = (new InitialContext(env)).lookup(ejbLink); } } return beanObj; }
// in java/org/apache/naming/factory/SendMailFactory.java
Override public Object getObjectInstance(Object refObj, Name name, Context ctx, Hashtable<?,?> env) throws Exception { final Reference ref = (Reference)refObj; // Creation of the DataSource is wrapped inside a doPrivileged // so that javamail can read its default properties without // throwing Security Exceptions if (ref.getClassName().equals(DataSourceClassName)) { return AccessController.doPrivileged( new PrivilegedAction<MimePartDataSource>() { @Override public MimePartDataSource run() { // set up the smtp session that will send the message Properties props = new Properties(); // enumeration of all refaddr Enumeration<RefAddr> list = ref.getAll(); // current refaddr to be set RefAddr refaddr; // set transport to smtp props.put("mail.transport.protocol", "smtp"); while (list.hasMoreElements()) { refaddr = list.nextElement(); // set property props.put(refaddr.getType(), refaddr.getContent()); } MimeMessage message = new MimeMessage( Session.getInstance(props)); try { RefAddr fromAddr = ref.get("mail.from"); String from = null; if (fromAddr != null) { from = (String)ref.get("mail.from").getContent(); } if (from != null) { message.setFrom(new InternetAddress(from)); } message.setSubject(""); } catch (Exception e) {/*Ignore*/} MimePartDataSource mds = new MimePartDataSource(message); return mds; } } ); }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof ServiceRef) { Reference ref = (Reference) obj; // ClassLoader ClassLoader tcl = Thread.currentThread().getContextClassLoader(); if (tcl == null) tcl = this.getClass().getClassLoader(); ServiceFactory factory = ServiceFactory.newInstance(); javax.xml.rpc.Service service = null; // Service Interface RefAddr tmp = ref.get(ServiceRef.SERVICE_INTERFACE); String serviceInterface = null; if (tmp != null) serviceInterface = (String) tmp.getContent(); // WSDL tmp = ref.get(ServiceRef.WSDL); String wsdlRefAddr = null; if (tmp != null) wsdlRefAddr = (String) tmp.getContent(); // PortComponent Hashtable<String,QName> portComponentRef = new Hashtable<String,QName>(); // Create QName object QName serviceQname = null; tmp = ref.get(ServiceRef.SERVICE_LOCAL_PART); if (tmp != null) { String serviceLocalPart = (String) tmp.getContent(); tmp = ref.get(ServiceRef.SERVICE_NAMESPACE); if (tmp == null) { serviceQname = new QName(serviceLocalPart); } else { String serviceNamespace = (String) tmp.getContent(); serviceQname = new QName(serviceNamespace, serviceLocalPart); } } Class<?> serviceInterfaceClass = null; // Create service object if (serviceInterface == null) { if (serviceQname == null) { throw new NamingException ("Could not create service-ref instance"); } try { if (wsdlRefAddr == null) { service = factory.createService( serviceQname ); } else { service = factory.createService( new URL(wsdlRefAddr), serviceQname ); } } catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; } } else { // Loading service Interface try { serviceInterfaceClass = tcl.loadClass(serviceInterface); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load service Interface"); ex.initCause(e); throw ex; } if (serviceInterfaceClass == null) { throw new NamingException ("Could not load service Interface"); } try { if (wsdlRefAddr == null) { if (!Service.class.isAssignableFrom(serviceInterfaceClass)) { throw new NamingException ("service Interface should extend javax.xml.rpc.Service"); } service = factory.loadService( serviceInterfaceClass ); } else { service = factory.loadService( new URL(wsdlRefAddr), serviceInterfaceClass, new Properties() ); } } catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; } } if (service == null) { throw new NamingException ("Cannot create service object"); } serviceQname = service.getServiceName(); serviceInterfaceClass = service.getClass(); if (wsdlRefAddr != null) { try { WSDLFactory wsdlfactory = WSDLFactory.newInstance(); WSDLReader reader = wsdlfactory.newWSDLReader(); reader.setFeature("javax.wsdl.importDocuments", true); Definition def = reader.readWSDL((new URL(wsdlRefAddr)).toExternalForm()); javax.wsdl.Service wsdlservice = def.getService(serviceQname); @SuppressWarnings("unchecked") // Can't change the API Map<String,?> ports = wsdlservice.getPorts(); Method m = serviceInterfaceClass.getMethod("setEndpointAddress", new Class[] { java.lang.String.class, java.lang.String.class }); for (Iterator<String> i = ports.keySet().iterator(); i.hasNext();) { String portName = i.next(); Port port = wsdlservice.getPort(portName); String endpoint = getSOAPLocation(port); m.invoke(service, new Object[] {port.getName(), endpoint }); portComponentRef.put(endpoint, new QName(port.getName())); } } catch (Exception e) { if (e instanceof InvocationTargetException) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } } NamingException ex = new NamingException ("Error while reading Wsdl File"); ex.initCause(e); throw ex; } } ServiceProxy proxy = new ServiceProxy(service); // Use port-component-ref for (int i = 0; i < ref.size(); i++) if (ServiceRef.SERVICEENDPOINTINTERFACE.equals(ref.get(i).getType())) { String serviceendpoint = ""; String portlink = ""; serviceendpoint = (String) ref.get(i).getContent(); if (ServiceRef.PORTCOMPONENTLINK.equals(ref.get(i + 1).getType())) { i++; portlink = (String) ref.get(i).getContent(); } portComponentRef.put(serviceendpoint, new QName(portlink)); } proxy.setPortComponentRef(portComponentRef); // Instantiate service with proxy class Class<?>[] interfaces = null; Class<?>[] serviceInterfaces = serviceInterfaceClass.getInterfaces(); interfaces = new Class[serviceInterfaces.length + 1]; for (int i = 0; i < serviceInterfaces.length; i++) { interfaces[i] = serviceInterfaces[i]; } interfaces[interfaces.length - 1] = javax.xml.rpc.Service.class; Object proxyInstance = null; try { proxyInstance = Proxy.newProxyInstance(tcl, interfaces, proxy); } catch (IllegalArgumentException e) { proxyInstance = Proxy.newProxyInstance(tcl, serviceInterfaces, proxy); } // Use handler if (((ServiceRef) ref).getHandlersSize() > 0) { HandlerRegistry handlerRegistry = service.getHandlerRegistry(); ArrayList<String> soaproles = new ArrayList<String>(); while (((ServiceRef) ref).getHandlersSize() > 0) { HandlerRef handlerRef = ((ServiceRef) ref).getHandler(); HandlerInfo handlerInfo = new HandlerInfo(); // Loading handler Class tmp = handlerRef.get(HandlerRef.HANDLER_CLASS); if ((tmp == null) || (tmp.getContent() == null)) break; Class<?> handlerClass = null; try { handlerClass = tcl.loadClass((String) tmp.getContent()); } catch(ClassNotFoundException e) { break; } // Load all datas relative to the handler : SOAPHeaders, config init element, // portNames to be set on ArrayList<QName> headers = new ArrayList<QName>(); Hashtable<String,String> config = new Hashtable<String,String>(); ArrayList<String> portNames = new ArrayList<String>(); for (int i = 0; i < handlerRef.size(); i++) if (HandlerRef.HANDLER_LOCALPART.equals(handlerRef.get(i).getType())) { String localpart = ""; String namespace = ""; localpart = (String) handlerRef.get(i).getContent(); if (HandlerRef.HANDLER_NAMESPACE.equals(handlerRef.get(i + 1).getType())) { i++; namespace = (String) handlerRef.get(i).getContent(); } QName header = new QName(namespace, localpart); headers.add(header); } else if (HandlerRef.HANDLER_PARAMNAME.equals(handlerRef.get(i).getType())) { String paramName = ""; String paramValue = ""; paramName = (String) handlerRef.get(i).getContent(); if (HandlerRef.HANDLER_PARAMVALUE.equals(handlerRef.get(i + 1).getType())) { i++; paramValue = (String) handlerRef.get(i).getContent(); } config.put(paramName, paramValue); } else if (HandlerRef.HANDLER_SOAPROLE.equals(handlerRef.get(i).getType())) { String soaprole = ""; soaprole = (String) handlerRef.get(i).getContent(); soaproles.add(soaprole); } else if (HandlerRef.HANDLER_PORTNAME.equals(handlerRef.get(i).getType())) { String portName = ""; portName = (String) handlerRef.get(i).getContent(); portNames.add(portName); } // Set the handlers informations handlerInfo.setHandlerClass(handlerClass); handlerInfo.setHeaders(headers.toArray(new QName[headers.size()])); handlerInfo.setHandlerConfig(config); if (!portNames.isEmpty()) { Iterator<String> iter = portNames.iterator(); while (iter.hasNext()) initHandlerChain(new QName(iter.next()), handlerRegistry, handlerInfo, soaproles); } else { Enumeration<QName> e = portComponentRef.elements(); while(e.hasMoreElements()) initHandlerChain(e.nextElement(), handlerRegistry, handlerInfo, soaproles); } } } return proxyInstance; } return null; }
// in java/org/apache/naming/factory/ResourceFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof ResourceRef) { Reference ref = (Reference) obj; ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch (Exception e) { if (e instanceof NamingException) throw (NamingException) e; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; } } } else { if (ref.getClassName().equals("javax.sql.DataSource")) { String javaxSqlDataSourceFactoryClassName = System.getProperty("javax.sql.DataSource.Factory", Constants.DBCP_DATASOURCE_FACTORY); try { factory = (ObjectFactory) Class.forName(javaxSqlDataSourceFactoryClassName) .newInstance(); } catch (Exception e) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; } } else if (ref.getClassName().equals("javax.mail.Session")) { String javaxMailSessionFactoryClassName = System.getProperty("javax.mail.Session.Factory", "org.apache.naming.factory.MailSessionFactory"); try { factory = (ObjectFactory) Class.forName(javaxMailSessionFactoryClassName) .newInstance(); } catch(Throwable t) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } } if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/factory/EjbFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof EjbRef) { Reference ref = (Reference) obj; // If ejb-link has been specified, resolving the link using JNDI RefAddr linkRefAddr = ref.get(EjbRef.LINK); if (linkRefAddr != null) { // Retrieving the EJB link String ejbLink = linkRefAddr.getContent().toString(); Object beanObj = (new InitialContext()).lookup(ejbLink); return beanObj; } ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch(Throwable t) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(t); throw ex; } } } else { String javaxEjbFactoryClassName = System.getProperty("javax.ejb.Factory", Constants.OPENEJB_EJB_FACTORY); try { factory = (ObjectFactory) Class.forName(javaxEjbFactoryClassName).newInstance(); } catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/factory/TransactionFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof TransactionRef) { Reference ref = (Reference) obj; ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } } if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/factory/MailSessionFactory.java
Override public Object getObjectInstance(Object refObj, Name name, Context context, Hashtable<?,?> env) throws Exception { // Return null if we cannot create an object of the requested type final Reference ref = (Reference) refObj; if (!ref.getClassName().equals(factoryType)) return (null); // Create a new Session inside a doPrivileged block, so that JavaMail // can read its default properties without throwing Security // exceptions. // // Bugzilla 31288, 33077: add support for authentication. return AccessController.doPrivileged(new PrivilegedAction<Session>() { @Override public Session run() { // Create the JavaMail properties we will use Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", "localhost"); String password = null; Enumeration<RefAddr> attrs = ref.getAll(); while (attrs.hasMoreElements()) { RefAddr attr = attrs.nextElement(); if ("factory".equals(attr.getType())) { continue; } if ("password".equals(attr.getType())) { password = (String) attr.getContent(); continue; } props.put(attr.getType(), attr.getContent()); } Authenticator auth = null; if (password != null) { String user = props.getProperty("mail.smtp.user"); if(user == null) { user = props.getProperty("mail.user"); } if(user != null) { final PasswordAuthentication pa = new PasswordAuthentication(user, password); auth = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return pa; } }; } } // Create and return the new Session object Session session = Session.getInstance(props, auth); return (session); } } ); }
// in java/org/apache/coyote/AbstractProtocol.java
Override public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { oname = name; mserver = server; domain = name.getDomain(); return name; }
// in java/org/apache/coyote/AbstractProtocol.java
Override public void preDeregister() throws Exception { // NOOP }
// in java/org/apache/coyote/AbstractProtocol.java
Override public void init() throws Exception { if (getLog().isInfoEnabled()) getLog().info(sm.getString("abstractProtocolHandler.init", getName())); if (oname == null) { // Component not pre-registered so register it oname = createObjectName(); if (oname != null) { Registry.getRegistry(null, null).registerComponent(this, oname, null); } } if (this.domain != null) { try { tpOname = new ObjectName(domain + ":" + "type=ThreadPool,name=" + getName()); Registry.getRegistry(null, null).registerComponent(endpoint, tpOname, null); } catch (Exception e) { getLog().error(sm.getString( "abstractProtocolHandler.mbeanRegistrationFailed", tpOname, getName()), e); } rgOname=new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getName()); Registry.getRegistry(null, null).registerComponent( getHandler().getGlobal(), rgOname, null ); } String endpointName = getName(); endpoint.setName(endpointName.substring(1, endpointName.length()-1)); try { endpoint.init(); } catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.initError", getName()), ex); throw ex; } }
// in java/org/apache/coyote/AbstractProtocol.java
Override public void start() throws Exception { if (getLog().isInfoEnabled()) getLog().info(sm.getString("abstractProtocolHandler.start", getName())); try { endpoint.start(); } catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.startError", getName()), ex); throw ex; } }
// in java/org/apache/coyote/AbstractProtocol.java
Override public void pause() throws Exception { if(getLog().isInfoEnabled()) getLog().info(sm.getString("abstractProtocolHandler.pause", getName())); try { endpoint.pause(); } catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.pauseError", getName()), ex); throw ex; } }
// in java/org/apache/coyote/AbstractProtocol.java
Override public void resume() throws Exception { if(getLog().isInfoEnabled()) getLog().info(sm.getString("abstractProtocolHandler.resume", getName())); try { endpoint.resume(); } catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.resumeError", getName()), ex); throw ex; } }
// in java/org/apache/coyote/AbstractProtocol.java
Override public void stop() throws Exception { if(getLog().isInfoEnabled()) getLog().info(sm.getString("abstractProtocolHandler.stop", getName())); try { endpoint.stop(); } catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.stopError", getName()), ex); throw ex; } }
// in java/org/apache/coyote/http11/Http11NioProtocol.java
Override public void start() throws Exception { super.start(); if (npnHandler != null) { npnHandler.init(getEndpoint(), 0, adapter); } }
// in java/org/apache/coyote/http11/Http11Protocol.java
Override public void start() throws Exception { super.start(); if (npnHandler != null) { npnHandler.init(endpoint, 0, adapter); } }
// in java/org/apache/coyote/http11/AbstractHttp11JsseProtocol.java
Override public void init() throws Exception { // SSL implementation needs to be in place before end point is // initialized sslImplementation = SSLImplementation.getInstance(sslImplementationName); super.init(); }
// in java/org/apache/coyote/http11/Http11AprProtocol.java
Override public void start() throws Exception { super.start(); if (npnHandler != null) { long sslCtx = ((AprEndpoint) endpoint).getJniSslContext(); npnHandler.init(endpoint, sslCtx, adapter); } }
// in java/org/apache/coyote/spdy/SpdyProxyProtocol.java
Override public void start() throws Exception { super.start(); spdyContext = new SpdyContext(); spdyContext.setTlsComprression(false, false); spdyContext.setHandler(new SpdyHandler() { @Override public void onStream(SpdyConnection con, SpdyStream ch) throws IOException { SpdyProcessor sp = new SpdyProcessor(con, endpoint); sp.setAdapter(adapter); sp.onSynStream(ch); } }); spdyContext.setNetSupport(new NetSupportSocket()); spdyContext.setExecutor(endpoint.getExecutor()); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
long getSslCtx() throws Exception { if (sslCtx == 0) { synchronized (AprSocketContext.class) { boolean serverMode = acceptor != null; sslCtx = SSLContext.make(getRootPool(), sslProtocol, serverMode ? SSL.SSL_MODE_SERVER : SSL.SSL_MODE_CLIENT); // SSL.SSL_OP_NO_SSLv3 int opts = SSL.SSL_OP_NO_SSLv2 | SSL.SSL_OP_SINGLE_DH_USE; if (!USE_TICKETS || serverMode && ticketKey == null) { opts |= SSL.SSL_OP_NO_TICKET; } SSLContext.setOptions(sslCtx, opts); // Set revocation // SSLContext.setCARevocation(sslContext, SSLCARevocationFile, SSLCARevocationPath); // Client certificate verification - maybe make it option try { SSLContext.setCipherSuite(sslCtx, SSLCipherSuite); if (serverMode) { if (ticketKey != null) { //SSLExt.setTicketKeys(sslCtx, ticketKey, ticketKey.length); } if (certFile != null) { boolean rc = SSLContext.setCertificate(sslCtx, certFile, keyFile, null, SSL.SSL_AIDX_DSA); if (!rc) { throw new IOException("Can't set keys"); } } SSLContext.setVerify(sslCtx, SSL.SSL_CVERIFY_NONE, 10); if (spdyNPN != null) { SSLExt.setNPN(sslCtx, spdyNPN, spdyNPN.length); } } else { if (tlsCertVerifier != null) { // NONE ? SSLContext.setVerify(sslCtx, SSL.SSL_CVERIFY_NONE, 10); } else { SSLContext.setCACertificate(sslCtx, "/etc/ssl/certs/ca-certificates.crt", "/etc/ssl/certs"); SSLContext.setVerify(sslCtx, SSL.SSL_CVERIFY_REQUIRE, 10); } if (spdyNPN != null) { SSLExt.setNPN(sslCtx, spdyNPN, spdyNPN.length); } } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } long mode = SSLExt.sslCtxSetMode(sslCtx, SSLExt.SSL_MODE_ENABLE_PARTIAL_WRITE | SSLExt.SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); // TODO: try release buffers } }
// in java/org/apache/tomcat/jni/Library.java
public static boolean initialize(String libraryName) throws Exception { if (_instance == null) { if (libraryName == null) _instance = new Library(); else _instance = new Library(libraryName); TCN_MAJOR_VERSION = version(0x01); TCN_MINOR_VERSION = version(0x02); TCN_PATCH_VERSION = version(0x03); TCN_IS_DEV_VERSION = version(0x04); APR_MAJOR_VERSION = version(0x11); APR_MINOR_VERSION = version(0x12); APR_PATCH_VERSION = version(0x13); APR_IS_DEV_VERSION = version(0x14); APR_SIZEOF_VOIDP = size(1); APR_PATH_MAX = size(2); APRMAXHOSTLEN = size(3); APR_MAX_IOVEC_SIZE = size(4); APR_MAX_SECS_TO_LINGER = size(5); APR_MMAP_THRESHOLD = size(6); APR_MMAP_LIMIT = size(7); APR_HAVE_IPV6 = has(0); APR_HAS_SHARED_MEMORY = has(1); APR_HAS_THREADS = has(2); APR_HAS_SENDFILE = has(3); APR_HAS_MMAP = has(4); APR_HAS_FORK = has(5); APR_HAS_RANDOM = has(6); APR_HAS_OTHER_CHILD = has(7); APR_HAS_DSO = has(8); APR_HAS_SO_ACCEPTFILTER = has(9); APR_HAS_UNICODE_FS = has(10); APR_HAS_PROC_INVOKED = has(11); APR_HAS_USER = has(12); APR_HAS_LARGE_FILES = has(13); APR_HAS_XTHREAD_FILES = has(14); APR_HAS_OS_UUID = has(15); APR_IS_BIGENDIAN = has(16); APR_FILES_AS_SOCKETS = has(17); APR_CHARSET_EBCDIC = has(18); APR_TCP_NODELAY_INHERITED = has(19); APR_O_NONBLOCK_INHERITED = has(20); if (APR_MAJOR_VERSION < 1) { throw new UnsatisfiedLinkError("Unsupported APR Version (" + aprVersionString() + ")"); } if (!APR_HAS_THREADS) { throw new UnsatisfiedLinkError("Missing APR_HAS_THREADS"); } } return initialize(); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
Override public void bind() throws Exception { serverSock = ServerSocketChannel.open(); socketProperties.setProperties(serverSock.socket()); InetSocketAddress addr = (getAddress()!=null?new InetSocketAddress(getAddress(),getPort()):new InetSocketAddress(getPort())); serverSock.socket().bind(addr,getBacklog()); serverSock.configureBlocking(true); //mimic APR behavior serverSock.socket().setSoTimeout(getSocketProperties().getSoTimeout()); // Initialize thread count defaults for acceptor, poller if (acceptorThreadCount == 0) { // FIXME: Doesn't seem to work that well with multiple accept threads acceptorThreadCount = 1; } if (pollerThreadCount <= 0) { //minimum one poller thread pollerThreadCount = 1; } stopLatch = new CountDownLatch(pollerThreadCount); // Initialize SSL if needed if (isSSLEnabled()) { SSLUtil sslUtil = handler.getSslImplementation().getSSLUtil(this); sslContext = sslUtil.createSSLContext(); sslContext.init(wrap(sslUtil.getKeyManagers()), sslUtil.getTrustManagers(), null); SSLSessionContext sessionContext = sslContext.getServerSessionContext(); if (sessionContext != null) { sslUtil.configureSessionContext(sessionContext); } } if (oomParachute>0) reclaimParachute(true); selectorPool.open(); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
Override public void startInternal() throws Exception { if (!running) { running = true; paused = false; // Create worker collection if ( getExecutor() == null ) { createExecutor(); } initializeConnectionLatch(); // Start poller threads pollers = new Poller[getPollerThreadCount()]; for (int i=0; i<pollers.length; i++) { pollers[i] = new Poller(); Thread pollerThread = new Thread(pollers[i], getName() + "-ClientPoller-"+i); pollerThread.setPriority(threadPriority); pollerThread.setDaemon(true); pollerThread.start(); } startAcceptorThreads(); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
Override public void unbind() throws Exception { if (log.isDebugEnabled()) { log.debug("Destroy initiated for "+new InetSocketAddress(getAddress(),getPort())); } if (running) { stop(); } // Close server socket serverSock.socket().close(); serverSock.close(); serverSock = null; sslContext = null; releaseCaches(); selectorPool.close(); if (log.isDebugEnabled()) { log.debug("Destroy completed for "+new InetSocketAddress(getAddress(),getPort())); } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
Override public void bind() throws Exception { // Create the root APR memory pool try { rootPool = Pool.create(0); } catch (UnsatisfiedLinkError e) { throw new Exception(sm.getString("endpoint.init.notavail")); } // Create the pool for the server socket serverSockPool = Pool.create(rootPool); // Create the APR address that will be bound String addressStr = null; if (getAddress() != null) { addressStr = getAddress().getHostAddress(); } int family = Socket.APR_INET; if (Library.APR_HAVE_IPV6) { if (addressStr == null) { if (!OS.IS_BSD && !OS.IS_WIN32 && !OS.IS_WIN64) family = Socket.APR_UNSPEC; } else if (addressStr.indexOf(':') >= 0) { family = Socket.APR_UNSPEC; } } long inetAddress = Address.info(addressStr, family, getPort(), 0, rootPool); // Create the APR server socket serverSock = Socket.create(Address.getInfo(inetAddress).family, Socket.SOCK_STREAM, Socket.APR_PROTO_TCP, rootPool); if (OS.IS_UNIX) { Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Deal with the firewalls that tend to drop the inactive sockets Socket.optSet(serverSock, Socket.APR_SO_KEEPALIVE, 1); // Bind the server socket int ret = Socket.bind(serverSock, inetAddress); if (ret != 0) { throw new Exception(sm.getString("endpoint.init.bind", "" + ret, Error.strerror(ret))); } // Start listening on the server socket ret = Socket.listen(serverSock, getBacklog()); if (ret != 0) { throw new Exception(sm.getString("endpoint.init.listen", "" + ret, Error.strerror(ret))); } if (OS.IS_WIN32 || OS.IS_WIN64) { // On Windows set the reuseaddr flag after the bind/listen Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Sendfile usage on systems which don't support it cause major problems if (useSendfile && !Library.APR_HAS_SENDFILE) { useSendfile = false; } // Initialize thread count defaults for acceptor, poller and sendfile if (acceptorThreadCount == 0) { // FIXME: Doesn't seem to work that well with multiple accept threads acceptorThreadCount = 1; } if (pollerThreadCount == 0) { if ((OS.IS_WIN32 || OS.IS_WIN64) && (getMaxConnections() > 1024)) { // The maximum per poller to get reasonable performance is 1024 pollerThreadCount = getMaxConnections() / 1024; // Adjust poller size so that it won't reach the limit setMaxConnections( getMaxConnections() - (getMaxConnections() % 1024)); } else { // No explicit poller size limitation pollerThreadCount = 1; } } if (sendfileThreadCount == 0) { if ((OS.IS_WIN32 || OS.IS_WIN64) && (sendfileSize > 1024)) { // The maximum per poller to get reasonable performance is 1024 sendfileThreadCount = sendfileSize / 1024; // Adjust poller size so that it won't reach the limit sendfileSize = sendfileSize - (sendfileSize % 1024); } else { // No explicit poller size limitation // FIXME: Default to one per CPU ? sendfileThreadCount = 1; } } // Delay accepting of new connections until data is available // Only Linux kernels 2.4 + have that implemented // on other platforms this call is noop and will return APR_ENOTIMPL. if (deferAccept) { if (Socket.optSet(serverSock, Socket.APR_TCP_DEFER_ACCEPT, 1) == Status.APR_ENOTIMPL) { deferAccept = false; } } // Initialize SSL if needed if (isSSLEnabled()) { if (SSLCertificateFile == null) { // This is required throw new Exception(sm.getString("endpoint.apr.noSslCertFile")); } // SSL protocol int value; // This branch can be removed, once the required version is at least 1.1.21. int tcnFullVersion = Library.TCN_MAJOR_VERSION * 1000 + Library.TCN_MINOR_VERSION * 100 + Library.TCN_PATCH_VERSION; if (tcnFullVersion <= 1120) { value = SSL.SSL_PROTOCOL_ALL; if ("SSLv2".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_SSLV2; } else if ("SSLv3".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_SSLV3; } else if ("TLSv1".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_TLSV1; } else if ("SSLv2+SSLv3".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_SSLV2 | SSL.SSL_PROTOCOL_SSLV3; } else if ("all".equalsIgnoreCase(SSLProtocol) || SSLProtocol == null || SSLProtocol.length() == 0) { // NOOP, use the default defined above } else { // Protocol not recognized, fail to start as it is safer than // continuing with the default which might enable more than the // is required throw new Exception(sm.getString( "endpoint.apr.invalidSslProtocol", SSLProtocol)); } } else { value = SSL.SSL_PROTOCOL_NONE; if (SSLProtocol == null || SSLProtocol.length() == 0) { value = SSL.SSL_PROTOCOL_ALL; } else { for (String protocol : SSLProtocol.split("\\+")) { protocol = protocol.trim(); if ("SSLv2".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_SSLV2; } else if ("SSLv3".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_SSLV3; } else if ("TLSv1".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_TLSV1; } else if ("all".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_ALL; } else { // Protocol not recognized, fail to start as it is safer than // continuing with the default which might enable more than the // is required throw new Exception(sm.getString( "endpoint.apr.invalidSslProtocol", SSLProtocol)); } } } } // Create SSL Context sslContext = SSLContext.make(rootPool, value, SSL.SSL_MODE_SERVER); if (SSLInsecureRenegotiation) { boolean legacyRenegSupported = false; try { legacyRenegSupported = SSL.hasOp(SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); if (legacyRenegSupported) SSLContext.setOptions(sslContext, SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); } catch (UnsatisfiedLinkError e) { // Ignore } if (!legacyRenegSupported) { // OpenSSL does not support unsafe legacy renegotiation. log.warn(sm.getString("endpoint.warn.noInsecureReneg", SSL.versionString())); } } // List the ciphers that the client is permitted to negotiate SSLContext.setCipherSuite(sslContext, SSLCipherSuite); // Load Server key and certificate SSLContext.setCertificate(sslContext, SSLCertificateFile, SSLCertificateKeyFile, SSLPassword, SSL.SSL_AIDX_RSA); // Set certificate chain file SSLContext.setCertificateChainFile(sslContext, SSLCertificateChainFile, false); // Support Client Certificates SSLContext.setCACertificate(sslContext, SSLCACertificateFile, SSLCACertificatePath); // Set revocation SSLContext.setCARevocation(sslContext, SSLCARevocationFile, SSLCARevocationPath); // Client certificate verification value = SSL.SSL_CVERIFY_NONE; if ("optional".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_OPTIONAL; } else if ("require".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_REQUIRE; } else if ("optionalNoCA".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_OPTIONAL_NO_CA; } SSLContext.setVerify(sslContext, value, SSLVerifyDepth); // For now, sendfile is not supported with SSL useSendfile = false; } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
Override public void startInternal() throws Exception { if (!running) { running = true; paused = false; // Create worker collection if (getExecutor() == null) { createExecutor(); } initializeConnectionLatch(); // Start poller threads pollers = new Poller[pollerThreadCount]; for (int i = 0; i < pollerThreadCount; i++) { pollers[i] = new Poller(false); pollers[i].init(); pollers[i].setName(getName() + "-Poller-" + i); pollers[i].setPriority(threadPriority); pollers[i].setDaemon(true); pollers[i].start(); } // Start comet poller threads cometPollers = new Poller[pollerThreadCount]; for (int i = 0; i < pollerThreadCount; i++) { cometPollers[i] = new Poller(true); cometPollers[i].init(); cometPollers[i].setName(getName() + "-CometPoller-" + i); cometPollers[i].setPriority(threadPriority); cometPollers[i].setDaemon(true); cometPollers[i].start(); } // Start sendfile threads if (useSendfile) { sendfiles = new Sendfile[sendfileThreadCount]; for (int i = 0; i < sendfileThreadCount; i++) { sendfiles[i] = new Sendfile(); sendfiles[i].init(); sendfiles[i].setName(getName() + "-Sendfile-" + i); sendfiles[i].setPriority(threadPriority); sendfiles[i].setDaemon(true); sendfiles[i].start(); } } startAcceptorThreads(); // Start async timeout thread Thread timeoutThread = new Thread(new AsyncTimeout(), getName() + "-AsyncTimeout"); timeoutThread.setPriority(threadPriority); timeoutThread.setDaemon(true); timeoutThread.start(); } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
Override public void unbind() throws Exception { if (running) { stop(); } // Destroy pool if it was initialised if (serverSockPool != 0) { Pool.destroy(serverSockPool); serverSockPool = 0; } // Close server socket if it was initialised if (serverSock != 0) { Socket.close(serverSock); serverSock = 0; } sslContext = 0; // Close all APR memory pools and resources if initialised if (rootPool != 0) { Pool.destroy(rootPool); rootPool = 0; } handler.recycle(); }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
public final void init() throws Exception { if (bindOnInit) { bind(); bindState = BindState.BOUND_ON_INIT; } }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
public final void start() throws Exception { if (bindState == BindState.UNBOUND) { bind(); bindState = BindState.BOUND_ON_START; } startInternal(); }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
public final void stop() throws Exception { stopInternal(); if (bindState == BindState.BOUND_ON_START) { unbind(); bindState = BindState.UNBOUND; } }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
public final void destroy() throws Exception { if (bindState == BindState.BOUND_ON_INIT) { unbind(); bindState = BindState.UNBOUND; } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
Override public void bind() throws Exception { // Initialize thread count defaults for acceptor if (acceptorThreadCount == 0) { acceptorThreadCount = 1; } // Initialize maxConnections if (getMaxConnections() == 0) { // User hasn't set a value - use the default setMaxConnections(getMaxThreadsExecutor(true)); } if (serverSocketFactory == null) { if (isSSLEnabled()) { serverSocketFactory = handler.getSslImplementation().getServerSocketFactory(this); } else { serverSocketFactory = new DefaultServerSocketFactory(this); } } if (serverSocket == null) { try { if (getAddress() == null) { serverSocket = serverSocketFactory.createSocket(getPort(), getBacklog()); } else { serverSocket = serverSocketFactory.createSocket(getPort(), getBacklog(), getAddress()); } } catch (BindException orig) { String msg; if (getAddress() == null) msg = orig.getMessage() + " <null>:" + getPort(); else msg = orig.getMessage() + " " + getAddress().toString() + ":" + getPort(); BindException be = new BindException(msg); be.initCause(orig); throw be; } } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
Override public void startInternal() throws Exception { if (!running) { running = true; paused = false; // Create worker collection if (getExecutor() == null) { createExecutor(); } initializeConnectionLatch(); startAcceptorThreads(); // Start async timeout thread Thread timeoutThread = new Thread(new AsyncTimeout(), getName() + "-AsyncTimeout"); timeoutThread.setPriority(threadPriority); timeoutThread.setDaemon(true); timeoutThread.start(); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
Override public void unbind() throws Exception { if (running) { stop(); } if (serverSocket != null) { try { if (serverSocket != null) serverSocket.close(); } catch (Exception e) { log.error(sm.getString("endpoint.err.close"), e); } serverSocket = null; } handler.recycle(); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public SSLContext createSSLContext() throws Exception { // SSL protocol variant (e.g., TLS, SSL v3, etc.) String protocol = endpoint.getSslProtocol(); if (protocol == null) { protocol = defaultProtocol; } SSLContext context = SSLContext.getInstance(protocol); return context; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public KeyManager[] getKeyManagers() throws Exception { String keystoreType = endpoint.getKeystoreType(); if (keystoreType == null) { keystoreType = defaultKeystoreType; } String algorithm = endpoint.getAlgorithm(); if (algorithm == null) { algorithm = KeyManagerFactory.getDefaultAlgorithm(); } return getKeyManagers(keystoreType, endpoint.getKeystoreProvider(), algorithm, endpoint.getKeyAlias()); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public TrustManager[] getTrustManagers() throws Exception { String truststoreType = endpoint.getTruststoreType(); if (truststoreType == null) { truststoreType = System.getProperty("javax.net.ssl.trustStoreType"); } if (truststoreType == null) { truststoreType = endpoint.getKeystoreType(); } if (truststoreType == null) { truststoreType = defaultKeystoreType; } String algorithm = endpoint.getTruststoreAlgorithm(); if (algorithm == null) { algorithm = TrustManagerFactory.getDefaultAlgorithm(); } return getTrustManagers(truststoreType, endpoint.getKeystoreProvider(), algorithm); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected KeyManager[] getKeyManagers(String keystoreType, String keystoreProvider, String algorithm, String keyAlias) throws Exception { KeyManager[] kms = null; String keystorePass = getKeystorePassword(); KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass); if (keyAlias != null && !ks.isKeyEntry(keyAlias)) { throw new IOException( sm.getString("jsse.alias_no_key_entry", keyAlias)); } KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); String keyPass = endpoint.getKeyPass(); if (keyPass == null) { keyPass = keystorePass; } kmf.init(ks, keyPass.toCharArray()); kms = kmf.getKeyManagers(); if (keyAlias != null) { String alias = keyAlias; if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) { alias = alias.toLowerCase(Locale.ENGLISH); } for(int i=0; i<kms.length; i++) { kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias); } } return kms; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected TrustManager[] getTrustManagers(String keystoreType, String keystoreProvider, String algorithm) throws Exception { String crlf = endpoint.getCrlFile(); String className = endpoint.getTrustManagerClassName(); if(className != null && className.length() > 0) { ClassLoader classLoader = getClass().getClassLoader(); Class<?> clazz = classLoader.loadClass(className); if(!(TrustManager.class.isAssignableFrom(clazz))){ throw new InstantiationException(sm.getString( "jsse.invalidTrustManagerClassName", className)); } Object trustManagerObject = clazz.newInstance(); TrustManager trustManager = (TrustManager) trustManagerObject; return new TrustManager[]{ trustManager }; } TrustManager[] tms = null; KeyStore trustStore = getTrustStore(keystoreType, keystoreProvider); if (trustStore != null || endpoint.getTrustManagerClassName() != null) { if (crlf == null) { TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init(trustStore); tms = tmf.getTrustManagers(); } else { TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); CertPathParameters params = getParameters(algorithm, crlf, trustStore); ManagerFactoryParameters mfp = new CertPathTrustManagerParameters(params); tmf.init(mfp); tms = tmf.getTrustManagers(); } } return tms; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected CertPathParameters getParameters(String algorithm, String crlf, KeyStore trustStore) throws Exception { CertPathParameters params = null; if("PKIX".equalsIgnoreCase(algorithm)) { PKIXBuilderParameters xparams = new PKIXBuilderParameters(trustStore, new X509CertSelector()); Collection<? extends CRL> crls = getCRLs(crlf); CertStoreParameters csp = new CollectionCertStoreParameters(crls); CertStore store = CertStore.getInstance("Collection", csp); xparams.addCertStore(store); xparams.setRevocationEnabled(true); String trustLength = endpoint.getTrustMaxCertLength(); if(trustLength != null) { try { xparams.setMaxPathLength(Integer.parseInt(trustLength)); } catch(Exception ex) { log.warn("Bad maxCertLength: "+trustLength); } } params = xparams; } else { throw new CRLException("CRLs not supported for type: "+algorithm); } return params; }
// in java/org/apache/tomcat/util/http/mapper/Mapper.java
public void map(MessageBytes host, MessageBytes uri, String version, MappingData mappingData) throws Exception { if (host.isNull()) { host.getCharChunk().append(defaultHostName); } host.toChars(); uri.toChars(); internalMap(host.getCharChunk(), uri.getCharChunk(), version, mappingData); }
// in java/org/apache/tomcat/util/http/mapper/Mapper.java
public void map(MessageBytes uri, MappingData mappingData) throws Exception { uri.toChars(); CharChunk uricc = uri.getCharChunk(); uricc.setLimit(-1); internalMapWrapper(context, uricc, mappingData); }
// in java/org/apache/tomcat/util/http/mapper/Mapper.java
private final void internalMap(CharChunk host, CharChunk uri, String version, MappingData mappingData) throws Exception { uri.setLimit(-1); Context[] contexts = null; Context context = null; ContextVersion contextVersion = null; int nesting = 0; // Virtual host mapping if (mappingData.host == null) { Host[] hosts = this.hosts; int pos = findIgnoreCase(hosts, host); if ((pos != -1) && (host.equalsIgnoreCase(hosts[pos].name))) { mappingData.host = hosts[pos].object; contexts = hosts[pos].contextList.contexts; nesting = hosts[pos].contextList.nesting; } else { if (defaultHostName == null) { return; } pos = find(hosts, defaultHostName); if ((pos != -1) && (defaultHostName.equals(hosts[pos].name))) { mappingData.host = hosts[pos].object; contexts = hosts[pos].contextList.contexts; nesting = hosts[pos].contextList.nesting; } else { return; } } } // Context mapping if (mappingData.context == null) { int pos = find(contexts, uri); if (pos == -1) { return; } int lastSlash = -1; int uriEnd = uri.getEnd(); int length = -1; boolean found = false; while (pos >= 0) { if (uri.startsWith(contexts[pos].name)) { length = contexts[pos].name.length(); if (uri.getLength() == length) { found = true; break; } else if (uri.startsWithIgnoreCase("/", length)) { found = true; break; } } if (lastSlash == -1) { lastSlash = nthSlash(uri, nesting + 1); } else { lastSlash = lastSlash(uri); } uri.setEnd(lastSlash); pos = find(contexts, uri); } uri.setEnd(uriEnd); if (!found) { if (contexts[0].name.equals("")) { context = contexts[0]; } } else { context = contexts[pos]; } if (context != null) { mappingData.contextPath.setString(context.name); } } if (context != null) { ContextVersion[] contextVersions = context.versions; int versionCount = contextVersions.length; if (versionCount > 1) { Object[] contextObjects = new Object[contextVersions.length]; for (int i = 0; i < contextObjects.length; i++) { contextObjects[i] = contextVersions[i].object; } mappingData.contexts = contextObjects; } if (version == null) { // Return the latest version contextVersion = contextVersions[versionCount - 1]; } else { int pos = find(contextVersions, version); if (pos < 0 || !contextVersions[pos].name.equals(version)) { // Return the latest version contextVersion = contextVersions[versionCount - 1]; } else { contextVersion = contextVersions[pos]; } } mappingData.context = contextVersion.object; } // Wrapper mapping if ((contextVersion != null) && (mappingData.wrapper == null)) { internalMapWrapper(contextVersion, uri, mappingData); } }
// in java/org/apache/tomcat/util/http/mapper/Mapper.java
private final void internalMapWrapper(ContextVersion contextVersion, CharChunk path, MappingData mappingData) throws Exception { int pathOffset = path.getOffset(); int pathEnd = path.getEnd(); int servletPath = pathOffset; boolean noServletPath = false; int length = contextVersion.path.length(); if (length != (pathEnd - pathOffset)) { servletPath = pathOffset + length; } else { noServletPath = true; path.append('/'); pathOffset = path.getOffset(); pathEnd = path.getEnd(); servletPath = pathOffset+length; } path.setOffset(servletPath); // Rule 1 -- Exact Match Wrapper[] exactWrappers = contextVersion.exactWrappers; internalMapExactWrapper(exactWrappers, path, mappingData); // Rule 2 -- Prefix Match boolean checkJspWelcomeFiles = false; Wrapper[] wildcardWrappers = contextVersion.wildcardWrappers; if (mappingData.wrapper == null) { internalMapWildcardWrapper(wildcardWrappers, contextVersion.nesting, path, mappingData); if (mappingData.wrapper != null && mappingData.jspWildCard) { char[] buf = path.getBuffer(); if (buf[pathEnd - 1] == '/') { /* * Path ending in '/' was mapped to JSP servlet based on * wildcard match (e.g., as specified in url-pattern of a * jsp-property-group. * Force the context's welcome files, which are interpreted * as JSP files (since they match the url-pattern), to be * considered. See Bugzilla 27664. */ mappingData.wrapper = null; checkJspWelcomeFiles = true; } else { // See Bugzilla 27704 mappingData.wrapperPath.setChars(buf, path.getStart(), path.getLength()); mappingData.pathInfo.recycle(); } } } if(mappingData.wrapper == null && noServletPath) { // The path is empty, redirect to "/" mappingData.redirectPath.setChars (path.getBuffer(), pathOffset, pathEnd-pathOffset); path.setEnd(pathEnd - 1); return; } // Rule 3 -- Extension Match Wrapper[] extensionWrappers = contextVersion.extensionWrappers; if (mappingData.wrapper == null && !checkJspWelcomeFiles) { internalMapExtensionWrapper(extensionWrappers, path, mappingData, true); } // Rule 4 -- Welcome resources processing for servlets if (mappingData.wrapper == null) { boolean checkWelcomeFiles = checkJspWelcomeFiles; if (!checkWelcomeFiles) { char[] buf = path.getBuffer(); checkWelcomeFiles = (buf[pathEnd - 1] == '/'); } if (checkWelcomeFiles) { for (int i = 0; (i < contextVersion.welcomeResources.length) && (mappingData.wrapper == null); i++) { path.setOffset(pathOffset); path.setEnd(pathEnd); path.append(contextVersion.welcomeResources[i], 0, contextVersion.welcomeResources[i].length()); path.setOffset(servletPath); // Rule 4a -- Welcome resources processing for exact macth internalMapExactWrapper(exactWrappers, path, mappingData); // Rule 4b -- Welcome resources processing for prefix match if (mappingData.wrapper == null) { internalMapWildcardWrapper (wildcardWrappers, contextVersion.nesting, path, mappingData); } // Rule 4c -- Welcome resources processing // for physical folder if (mappingData.wrapper == null && contextVersion.resources != null) { Object file = null; String pathStr = path.toString(); try { file = contextVersion.resources.lookup(pathStr); } catch(NamingException nex) { // Swallow not found, since this is normal } if (file != null && !(file instanceof DirContext) ) { internalMapExtensionWrapper(extensionWrappers, path, mappingData, true); if (mappingData.wrapper == null && contextVersion.defaultWrapper != null) { mappingData.wrapper = contextVersion.defaultWrapper.object; mappingData.requestPath.setChars (path.getBuffer(), path.getStart(), path.getLength()); mappingData.wrapperPath.setChars (path.getBuffer(), path.getStart(), path.getLength()); mappingData.requestPath.setString(pathStr); mappingData.wrapperPath.setString(pathStr); } } } } path.setOffset(servletPath); path.setEnd(pathEnd); } }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
Override public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { // Save the length of the file size = outputFile.length(); /* * The uploaded file is being stored on disk * in a temporary location so move it to the * desired file. */ if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream( new FileInputStream(outputFile)); out = new BufferedOutputStream( new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } if (out != null) { try { out.close(); } catch (IOException e) { // ignore } } } } } else { /* * For whatever reason we cannot write the * file to disk. */ throw new FileUploadException( "Cannot write uploaded file to disk!"); } } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { if( log.isDebugEnabled()) log.debug("preRegister " + resource + " " + name ); oname=name; if( resource instanceof MBeanRegistration ) { oname = ((MBeanRegistration)resource).preRegister(server, name ); } return oname; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void preDeregister() throws Exception { if( resource instanceof MBeanRegistration ) { ((MBeanRegistration)resource).preDeregister(); } }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsSerSource.java
Override public List<ObjectName> loadDescriptors( Registry registry, String type, Object source) throws Exception { setRegistry(registry); setType(type); setSource(source); execute(); return mbeans; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsSerSource.java
public void execute() throws Exception { if( registry==null ) registry=Registry.getRegistry(null, null); long t1=System.currentTimeMillis(); try { InputStream stream=null; if( source instanceof URL ) { stream=((URL)source).openStream(); } if( source instanceof InputStream ) { stream=(InputStream)source; } if( stream==null ) { throw new Exception( "Can't process "+ source); } ObjectInputStream ois=new ObjectInputStream(stream); Thread.currentThread().setContextClassLoader(ManagedBean.class.getClassLoader()); Object obj=ois.readObject(); //log.info("Reading " + obj); ManagedBean beans[]=(ManagedBean[])obj; // after all are read without error for( int i=0; i<beans.length; i++ ) { registry.addManagedBean(beans[i]); } } catch( Exception ex ) { log.error( "Error reading descriptors " + source + " " + ex.toString(), ex); throw ex; } long t2=System.currentTimeMillis(); log.info( "Reading descriptors ( ser ) " + (t2-t1)); }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java
Override public List<ObjectName> loadDescriptors( Registry registry, String type, Object source) throws Exception { setRegistry(registry); setType(type); setSource(source); execute(); return mbeans; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java
public void execute() throws Exception { if (registry == null) { registry = Registry.getRegistry(null, null); } InputStream stream = (InputStream) source; if (digester == null) { digester = createDigester(); } ArrayList<ManagedBean> loadedMbeans = new ArrayList<ManagedBean>(); synchronized (digester) { // Process the input file to configure our registry try { // Push our registry object onto the stack digester.push(loadedMbeans); digester.parse(stream); } catch (Exception e) { log.error("Error digesting Registry data", e); throw e; } finally { digester.reset(); } } Iterator<ManagedBean> iter = loadedMbeans.iterator(); while (iter.hasNext()) { registry.addManagedBean(iter.next()); } }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsIntrospectionSource.java
Override public List<ObjectName> loadDescriptors(Registry registry, String type, Object source) throws Exception { setRegistry(registry); setType(type); setSource(source); execute(); return mbeans; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsIntrospectionSource.java
public void execute() throws Exception { if( registry==null ) registry=Registry.getRegistry(null, null); try { ManagedBean managed = createManagedBean(registry, null, (Class<?>)source, type); if( managed==null ) return; managed.setName( type ); registry.addManagedBean(managed); } catch( Exception ex ) { log.error( "Error reading descriptors ", ex); } }
// in java/org/apache/tomcat/util/modeler/Registry.java
Override public void registerComponent(Object bean, String oname, String type) throws Exception { registerComponent(bean, new ObjectName(oname), type); }
// in java/org/apache/tomcat/util/modeler/Registry.java
Override public void invoke(List<ObjectName> mbeans, String operation, boolean failFirst ) throws Exception { if( mbeans==null ) { return; } Iterator<ObjectName> itr = mbeans.iterator(); while(itr.hasNext()) { ObjectName current = itr.next(); try { if(current == null) { continue; } if(getMethodInfo(current, operation) == null) { continue; } getMBeanServer().invoke(current, operation, new Object[] {}, new String[] {}); } catch( Exception t ) { if( failFirst ) throw t; log.info("Error initializing " + current + " " + t.toString()); } } }
// in java/org/apache/tomcat/util/modeler/Registry.java
public ManagedBean findManagedBean(Object bean, Class<?> beanClass, String type) throws Exception { if( bean!=null && beanClass==null ) { beanClass=bean.getClass(); } if( type==null ) { type=beanClass.getName(); } // first look for existing descriptor ManagedBean managed = findManagedBean(type); // Search for a descriptor in the same package if( managed==null ) { // check package and parent packages if( log.isDebugEnabled() ) { log.debug( "Looking for descriptor "); } findDescriptor( beanClass, type ); managed=findManagedBean(type); } // Still not found - use introspection if( managed==null ) { if( log.isDebugEnabled() ) { log.debug( "Introspecting "); } // introspection load("MbeansDescriptorsIntrospectionSource", beanClass, type); managed=findManagedBean(type); if( managed==null ) { log.warn( "No metadata found for " + type ); return null; } managed.setName( type ); addManagedBean(managed); } return managed; }
// in java/org/apache/tomcat/util/modeler/Registry.java
public List<ObjectName> load( String sourceType, Object source, String param) throws Exception { if( log.isTraceEnabled()) { log.trace("load " + source ); } String location=null; String type=null; Object inputsource=null; if( source instanceof URL ) { URL url=(URL)source; location=url.toString(); type=param; inputsource=url.openStream(); if( sourceType == null ) { sourceType = sourceTypeFromExt(location); } } else if( source instanceof File ) { location=((File)source).getAbsolutePath(); inputsource=new FileInputStream((File)source); type=param; if( sourceType == null ) { sourceType = sourceTypeFromExt(location); } } else if( source instanceof InputStream ) { type=param; inputsource=source; } else if( source instanceof Class<?> ) { location=((Class<?>)source).getName(); type=param; inputsource=source; if( sourceType== null ) { sourceType="MbeansDescriptorsIntrospectionSource"; } } if( sourceType==null ) { sourceType="MbeansDescriptorsDigesterSource"; } ModelerSource ds=getModelerSource(sourceType); List<ObjectName> mbeans = ds.loadDescriptors(this, type, inputsource); return mbeans; }
// in java/org/apache/tomcat/util/modeler/Registry.java
public void registerComponent(Object bean, ObjectName oname, String type) throws Exception { if( log.isDebugEnabled() ) { log.debug( "Managed= "+ oname); } if( bean ==null ) { log.error("Null component " + oname ); return; } try { if( type==null ) { type=bean.getClass().getName(); } ManagedBean managed = findManagedBean(null, bean.getClass(), type); // The real mbean is created and registered DynamicMBean mbean = managed.createMBean(bean); if( getMBeanServer().isRegistered( oname )) { if( log.isDebugEnabled()) { log.debug("Unregistering existing component " + oname ); } getMBeanServer().unregisterMBean( oname ); } getMBeanServer().registerMBean( mbean, oname); } catch( Exception ex) { log.error("Error registering " + oname, ex ); throw ex; } }
// in java/org/apache/tomcat/util/modeler/Registry.java
private ModelerSource getModelerSource( String type ) throws Exception { if( type==null ) type="MbeansDescriptorsDigesterSource"; if( type.indexOf( ".") < 0 ) { type="org.apache.tomcat.util.modeler.modules." + type; } Class<?> c = Class.forName(type); ModelerSource ds=(ModelerSource)c.newInstance(); return ds; }
// in java/org/apache/tomcat/util/modeler/Registry.java
Override public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { this.server=server; return name; }
// in java/org/apache/tomcat/util/modeler/Registry.java
Override public void preDeregister() throws Exception { }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
public static Object callMethod1(Object target, String methodN, Object param1, String typeParam1, ClassLoader cl) throws Exception { if (target == null || param1 == null) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Assert: Illegal params " + target + " " + param1); } if (log.isDebugEnabled()) log.debug("IntrospectionUtils: callMethod1 " + target.getClass().getName() + " " + param1.getClass().getName() + " " + typeParam1); Class<?> params[] = new Class[1]; if (typeParam1 == null) params[0] = param1.getClass(); else params[0] = cl.loadClass(typeParam1); Method m = findMethod(target.getClass(), methodN, params); if (m == null) throw new NoSuchMethodException(target.getClass().getName() + " " + methodN); try { return m.invoke(target, new Object[] { param1 }); } catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; } }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
public static Object callMethodN(Object target, String methodN, Object params[], Class<?> typeParams[]) throws Exception { Method m = null; m = findMethod(target.getClass(), methodN, typeParams); if (m == null) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Can't find method " + methodN + " in " + target + " CLASS " + target.getClass()); return null; } try { Object o = m.invoke(target, params); if (log.isDebugEnabled()) { // debug StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()).append('.') .append(methodN).append("( "); for (int i = 0; i < params.length; i++) { if (i > 0) sb.append(", "); sb.append(params[i]); } sb.append(")"); log.debug("IntrospectionUtils:" + sb.toString()); } return o; } catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; } }
// in java/org/apache/tomcat/util/digester/SetPropertyRule.java
Override public void begin(String namespace, String theName, Attributes attributes) throws Exception { // Identify the actual property name and value to be used String actualName = null; String actualValue = null; for (int i = 0; i < attributes.getLength(); i++) { String name = attributes.getLocalName(i); if ("".equals(name)) { name = attributes.getQName(i); } String value = attributes.getValue(i); if (name.equals(this.name)) { actualName = value; } else if (name.equals(this.value)) { actualValue = value; } } // Get a reference to the top object Object top = digester.peek(); // Log some debugging information if (digester.log.isDebugEnabled()) { digester.log.debug("[SetPropertyRule]{" + digester.match + "} Set " + top.getClass().getName() + " property " + actualName + " to " + actualValue); } // Set the property (with conversion as necessary) if (!digester.isFakeAttribute(top, actualName) && !IntrospectionUtils.setProperty(top, actualName, actualValue) && digester.getRulesValidation()) { digester.log.warn("[SetPropertyRule]{" + digester.match + "} Setting property '" + name + "' to '" + value + "' did not find a matching property."); } }
// in java/org/apache/tomcat/util/digester/ObjectCreateRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { // Identify the name of the class to instantiate String realClassName = className; if (attributeName != null) { String value = attributes.getValue(attributeName); if (value != null) { realClassName = value; } } if (digester.log.isDebugEnabled()) { digester.log.debug("[ObjectCreateRule]{" + digester.match + "}New " + realClassName); } if (realClassName == null) { throw new NullPointerException("No class name specified for " + namespace + " " + name); } // Instantiate the new object and push it on the context stack Class<?> clazz = digester.getClassLoader().loadClass(realClassName); Object instance = clazz.newInstance(); digester.push(instance); }
// in java/org/apache/tomcat/util/digester/ObjectCreateRule.java
Override public void end(String namespace, String name) throws Exception { Object top = digester.pop(); if (digester.log.isDebugEnabled()) { digester.log.debug("[ObjectCreateRule]{" + digester.match + "} Pop " + top.getClass().getName()); } }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (ignoreCreateExceptions) { if (exceptionIgnoredStack == null) { exceptionIgnoredStack = new ArrayStack<Boolean>(); } try { Object instance = getFactory(attributes).createObject(attributes); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule]{" + digester.match + "} New " + instance.getClass().getName()); } digester.push(instance); exceptionIgnoredStack.push(Boolean.FALSE); } catch (Exception e) { // log message and error if (digester.log.isInfoEnabled()) { digester.log.info("[FactoryCreateRule] Create exception ignored: " + ((e.getMessage() == null) ? e.getClass().getName() : e.getMessage())); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule] Ignored exception:", e); } } exceptionIgnoredStack.push(Boolean.TRUE); } } else { Object instance = getFactory(attributes).createObject(attributes); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule]{" + digester.match + "} New " + instance.getClass().getName()); } digester.push(instance); } }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
Override public void end(String namespace, String name) throws Exception { // check if object was created // this only happens if an exception was thrown and we're ignoring them if ( ignoreCreateExceptions && exceptionIgnoredStack != null && !(exceptionIgnoredStack.empty())) { if ((exceptionIgnoredStack.pop()).booleanValue()) { // creation exception was ignored // nothing was put onto the stack if (digester.log.isTraceEnabled()) { digester.log.trace("[FactoryCreateRule] No creation so no push so no pop"); } return; } } Object top = digester.pop(); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule]{" + digester.match + "} Pop " + top.getClass().getName()); } }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
Override public void finish() throws Exception { if (attributeName != null) { creationFactory = null; } }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
protected ObjectCreationFactory getFactory(Attributes attributes) throws Exception { if (creationFactory == null) { String realClassName = className; if (attributeName != null) { String value = attributes.getValue(attributeName); if (value != null) { realClassName = value; } } if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule]{" + digester.match + "} New factory " + realClassName); } Class<?> clazz = digester.getClassLoader().loadClass(realClassName); creationFactory = (ObjectCreationFactory) clazz.newInstance(); creationFactory.setDigester(digester); } return (creationFactory); }
// in java/org/apache/tomcat/util/digester/SetPropertiesRule.java
Override public void begin(String namespace, String theName, Attributes attributes) throws Exception { // Populate the corresponding properties of the top object Object top = digester.peek(); if (digester.log.isDebugEnabled()) { if (top != null) { digester.log.debug("[SetPropertiesRule]{" + digester.match + "} Set " + top.getClass().getName() + " properties"); } else { digester.log.debug("[SetPropertiesRule]{" + digester.match + "} Set NULL properties"); } } // set up variables for custom names mappings int attNamesLength = 0; if (attributeNames != null) { attNamesLength = attributeNames.length; } int propNamesLength = 0; if (propertyNames != null) { propNamesLength = propertyNames.length; } for (int i = 0; i < attributes.getLength(); i++) { String name = attributes.getLocalName(i); if ("".equals(name)) { name = attributes.getQName(i); } String value = attributes.getValue(i); // we'll now check for custom mappings for (int n = 0; n<attNamesLength; n++) { if (name.equals(attributeNames[n])) { if (n < propNamesLength) { // set this to value from list name = propertyNames[n]; } else { // set name to null // we'll check for this later name = null; } break; } } if (digester.log.isDebugEnabled()) { digester.log.debug("[SetPropertiesRule]{" + digester.match + "} Setting property '" + name + "' to '" + value + "'"); } if (!digester.isFakeAttribute(top, name) && !IntrospectionUtils.setProperty(top, name, value) && digester.getRulesValidation()) { digester.log.warn("[SetPropertiesRule]{" + digester.match + "} Setting property '" + name + "' to '" + value + "' did not find a matching property."); } } }
// in java/org/apache/tomcat/util/digester/CallMethodRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { // Push an array to capture the parameter values if necessary if (paramCount > 0) { Object parameters[] = new Object[paramCount]; for (int i = 0; i < parameters.length; i++) { parameters[i] = null; } digester.pushParams(parameters); } }
// in java/org/apache/tomcat/util/digester/CallMethodRule.java
Override public void body(String namespace, String name, String bodyText) throws Exception { if (paramCount == 0) { this.bodyText = bodyText.trim(); } }
// in java/org/apache/tomcat/util/digester/CallMethodRule.java
Override public void end(String namespace, String name) throws Exception { // Retrieve or construct the parameter values array Object parameters[] = null; if (paramCount > 0) { parameters = (Object[]) digester.popParams(); if (digester.log.isTraceEnabled()) { for (int i=0,size=parameters.length;i<size;i++) { digester.log.trace("[CallMethodRule](" + i + ")" + parameters[i]) ; } } // In the case where the parameter for the method // is taken from an attribute, and that attribute // isn't actually defined in the source XML file, // skip the method call if (paramCount == 1 && parameters[0] == null) { return; } } else if (paramTypes != null && paramTypes.length != 0) { // In the case where the parameter for the method // is taken from the body text, but there is no // body text included in the source XML file, // skip the method call if (bodyText == null) { return; } parameters = new Object[1]; parameters[0] = bodyText; if (paramTypes.length == 0) { paramTypes = new Class[1]; paramTypes[0] = "abc".getClass(); } } // Construct the parameter values array we will need // We only do the conversion if the param value is a String and // the specified paramType is not String. Object paramValues[] = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { // convert nulls and convert stringy parameters // for non-stringy param types if( parameters[i] == null || (parameters[i] instanceof String && !String.class.isAssignableFrom(paramTypes[i]))) { paramValues[i] = IntrospectionUtils.convert((String) parameters[i], paramTypes[i]); } else { paramValues[i] = parameters[i]; } } // Determine the target object for the method call Object target; if (targetOffset >= 0) { target = digester.peek(targetOffset); } else { target = digester.peek( digester.getCount() + targetOffset ); } if (target == null) { StringBuilder sb = new StringBuilder(); sb.append("[CallMethodRule]{"); sb.append(digester.match); sb.append("} Call target is null ("); sb.append("targetOffset="); sb.append(targetOffset); sb.append(",stackdepth="); sb.append(digester.getCount()); sb.append(")"); throw new org.xml.sax.SAXException(sb.toString()); } // Invoke the required method on the top object if (digester.log.isDebugEnabled()) { StringBuilder sb = new StringBuilder("[CallMethodRule]{"); sb.append(digester.match); sb.append("} Call "); sb.append(target.getClass().getName()); sb.append("."); sb.append(methodName); sb.append("("); for (int i = 0; i < paramValues.length; i++) { if (i > 0) { sb.append(","); } if (paramValues[i] == null) { sb.append("null"); } else { sb.append(paramValues[i].toString()); } sb.append("/"); if (paramTypes[i] == null) { sb.append("null"); } else { sb.append(paramTypes[i].getName()); } } sb.append(")"); digester.log.debug(sb.toString()); } Object result = IntrospectionUtils.callMethodN(target, methodName, paramValues, paramTypes); processMethodCallResult(result); }
// in java/org/apache/tomcat/util/digester/CallMethodRule.java
Override public void finish() throws Exception { bodyText = null; }
// in java/org/apache/tomcat/util/digester/SetTopRule.java
Override public void end(String namespace, String name) throws Exception { // Identify the objects to be used Object child = digester.peek(0); Object parent = digester.peek(1); if (digester.log.isDebugEnabled()) { if (child == null) { digester.log.debug("[SetTopRule]{" + digester.match + "} Call [NULL CHILD]." + methodName + "(" + parent + ")"); } else { digester.log.debug("[SetTopRule]{" + digester.match + "} Call " + child.getClass().getName() + "." + methodName + "(" + parent + ")"); } } // Call the specified method IntrospectionUtils.callMethod1(child, methodName, parent, paramType, digester.getClassLoader()); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void begin(String namespaceURI, String name, Attributes attributes) throws Exception { XMLReader xmlReader = getDigester().getXMLReader(); Document doc = documentBuilder.newDocument(); NodeBuilder builder = null; if (nodeType == Node.ELEMENT_NODE) { Element element = null; if (getDigester().getNamespaceAware()) { element = doc.createElementNS(namespaceURI, name); for (int i = 0; i < attributes.getLength(); i++) { element.setAttributeNS(attributes.getURI(i), attributes.getLocalName(i), attributes.getValue(i)); } } else { element = doc.createElement(name); for (int i = 0; i < attributes.getLength(); i++) { element.setAttribute(attributes.getQName(i), attributes.getValue(i)); } } builder = new NodeBuilder(doc, element); } else { builder = new NodeBuilder(doc, doc.createDocumentFragment()); } xmlReader.setContentHandler(builder); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void end(String namespace, String name) throws Exception { digester.pop(); }
// in java/org/apache/tomcat/util/digester/ObjectParamRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { Object anAttribute = null; Object parameters[] = (Object[]) digester.peekParams(); if (attributeName != null) { anAttribute = attributes.getValue(attributeName); if(anAttribute != null) { parameters[paramIndex] = param; } // note -- if attributeName != null and anAttribute == null, this rule // will pass null as its parameter! }else{ parameters[paramIndex] = param; } }
// in java/org/apache/tomcat/util/digester/SetRootRule.java
Override public void end(String namespace, String name) throws Exception { // Identify the objects to be used Object child = digester.peek(0); Object parent = digester.root; if (digester.log.isDebugEnabled()) { if (parent == null) { digester.log.debug("[SetRootRule]{" + digester.match + "} Call [NULL ROOT]." + methodName + "(" + child + ")"); } else { digester.log.debug("[SetRootRule]{" + digester.match + "} Call " + parent.getClass().getName() + "." + methodName + "(" + child + ")"); } } // Call the specified method IntrospectionUtils.callMethod1(parent, methodName, child, paramType, digester.getClassLoader()); }
// in java/org/apache/tomcat/util/digester/CallParamRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { Object param = null; if (attributeName != null) { param = attributes.getValue(attributeName); } else if(fromStack) { param = digester.peek(stackIndex); if (digester.log.isDebugEnabled()) { StringBuilder sb = new StringBuilder("[CallParamRule]{"); sb.append(digester.match); sb.append("} Save from stack; from stack?").append(fromStack); sb.append("; object=").append(param); digester.log.debug(sb.toString()); } } // Have to save the param object to the param stack frame here. // Can't wait until end(). Otherwise, the object will be lost. // We can't save the object as instance variables, as // the instance variables will be overwritten // if this CallParamRule is reused in subsequent nesting. if(param != null) { Object parameters[] = (Object[]) digester.peekParams(); parameters[paramIndex] = param; } }
// in java/org/apache/tomcat/util/digester/CallParamRule.java
Override public void body(String namespace, String name, String bodyText) throws Exception { if (attributeName == null && !fromStack) { // We must wait to set the parameter until end // so that we can make sure that the right set of parameters // is at the top of the stack if (bodyTextStack == null) { bodyTextStack = new ArrayStack<String>(); } bodyTextStack.push(bodyText.trim()); } }
// in java/org/apache/tomcat/util/digester/Rule.java
Deprecated public void begin(Attributes attributes) throws Exception { // The default implementation does nothing }
// in java/org/apache/tomcat/util/digester/Rule.java
public void begin(String namespace, String name, Attributes attributes) throws Exception { begin(attributes); }
// in java/org/apache/tomcat/util/digester/Rule.java
Deprecated public void body(String text) throws Exception { // The default implementation does nothing }
// in java/org/apache/tomcat/util/digester/Rule.java
public void body(String namespace, String name, String text) throws Exception { body(text); }
// in java/org/apache/tomcat/util/digester/Rule.java
Deprecated public void end() throws Exception { // The default implementation does nothing }
// in java/org/apache/tomcat/util/digester/Rule.java
public void end(String namespace, String name) throws Exception { end(); }
// in java/org/apache/tomcat/util/digester/Rule.java
public void finish() throws Exception { // The default implementation does nothing }
// in java/org/apache/tomcat/util/digester/SetNextRule.java
Override public void end(String namespace, String name) throws Exception { // Identify the objects to be used Object child = digester.peek(0); Object parent = digester.peek(1); if (digester.log.isDebugEnabled()) { if (parent == null) { digester.log.debug("[SetNextRule]{" + digester.match + "} Call [NULL PARENT]." + methodName + "(" + child + ")"); } else { digester.log.debug("[SetNextRule]{" + digester.match + "} Call " + parent.getClass().getName() + "." + methodName + "(" + child + ")"); } } // Call the specified method IntrospectionUtils.callMethod1(parent, methodName, child, paramType, digester.getClassLoader()); }
// in java/org/apache/tomcat/util/digester/PathCallParamRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { String param = getDigester().getMatch(); if(param != null) { Object parameters[] = (Object[]) digester.peekParams(); parameters[paramIndex] = param; } }
// in java/org/apache/el/parser/SimpleNode.java
Override public void accept(NodeVisitor visitor) throws Exception { visitor.visit(this); if (this.children != null && this.children.length > 0) { for (int i = 0; i < this.children.length; i++) { this.children[i].accept(visitor); } } }
// in java/org/apache/catalina/startup/ConnectorCreateRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { Service svc = (Service)digester.peek(); Executor ex = null; if ( attributes.getValue("executor")!=null ) { ex = svc.getExecutor(attributes.getValue("executor")); } Connector con = new Connector(attributes.getValue("protocol")); if ( ex != null ) _setExecutor(con,ex); digester.push(con); }
// in java/org/apache/catalina/startup/ConnectorCreateRule.java
public void _setExecutor(Connector con, Executor ex) throws Exception { Method m = IntrospectionUtils.findMethod(con.getProtocolHandler().getClass(),"setExecutor",new Class[] {java.util.concurrent.Executor.class}); if (m!=null) { m.invoke(con.getProtocolHandler(), new Object[] {ex}); }else { log.warn("Connector ["+con+"] does not support external executors. Method setExecutor(java.util.concurrent.Executor) not found."); } }
// in java/org/apache/catalina/startup/ConnectorCreateRule.java
Override public void end(String namespace, String name) throws Exception { digester.pop(); }
// in java/org/apache/catalina/startup/LifecycleListenerRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { Container c = (Container) digester.peek(); Container p = null; Object obj = digester.peek(1); if (obj instanceof Container) { p = (Container) obj; } String className = null; // Check the container for the specified attribute if (attributeName != null) { String value = attributes.getValue(attributeName); if (value != null) className = value; } // Check the container's parent for the specified attribute if (p != null && className == null) { String configClass = (String) IntrospectionUtils.getProperty(p, attributeName); if (configClass != null && configClass.length() > 0) { className = configClass; } } // Use the default if (className == null) { className = listenerClass; } // Instantiate a new LifecyleListener implementation object Class<?> clazz = Class.forName(className); LifecycleListener listener = (LifecycleListener) clazz.newInstance(); // Add this LifecycleListener to our associated component c.addLifecycleListener(listener); }
// in java/org/apache/catalina/startup/SetAllPropertiesRule.java
Override public void begin(String namespace, String nameX, Attributes attributes) throws Exception { for (int i = 0; i < attributes.getLength(); i++) { String name = attributes.getLocalName(i); if ("".equals(name)) { name = attributes.getQName(i); } String value = attributes.getValue(i); if ( !excludes.containsKey(name)) { if (!digester.isFakeAttribute(digester.peek(), name) && !IntrospectionUtils.setProperty(digester.peek(), name, value) && digester.getRulesValidation()) { digester.getLogger().warn("[SetAllPropertiesRule]{" + digester.getMatch() + "} Setting property '" + name + "' to '" + value + "' did not find a matching property."); } } } }
// in java/org/apache/catalina/startup/SetContextPropertiesRule.java
Override public void begin(String namespace, String nameX, Attributes attributes) throws Exception { for (int i = 0; i < attributes.getLength(); i++) { String name = attributes.getLocalName(i); if ("".equals(name)) { name = attributes.getQName(i); } if ("path".equals(name) || "docBase".equals(name)) { continue; } String value = attributes.getValue(i); if (!digester.isFakeAttribute(digester.peek(), name) && !IntrospectionUtils.setProperty(digester.peek(), name, value) && digester.getRulesValidation()) { digester.getLogger().warn("[SetContextPropertiesRule]{" + digester.getMatch() + "} Setting property '" + name + "' to '" + value + "' did not find a matching property."); } } }
// in java/org/apache/catalina/startup/ClassLoaderFactory.java
public static ClassLoader createClassLoader(File unpacked[], File packed[], final ClassLoader parent) throws Exception { if (log.isDebugEnabled()) log.debug("Creating new class loader"); // Construct the "class path" for this class loader Set<URL> set = new LinkedHashSet<URL>(); // Add unpacked directories if (unpacked != null) { for (int i = 0; i < unpacked.length; i++) { File file = unpacked[i]; if (!file.exists() || !file.canRead()) continue; file = new File(file.getCanonicalPath() + File.separator); URL url = file.toURI().toURL(); if (log.isDebugEnabled()) log.debug(" Including directory " + url); set.add(url); } } // Add packed directory JAR files if (packed != null) { for (int i = 0; i < packed.length; i++) { File directory = packed[i]; if (!directory.isDirectory() || !directory.exists() || !directory.canRead()) continue; String filenames[] = directory.list(); for (int j = 0; j < filenames.length; j++) { String filename = filenames[j].toLowerCase(Locale.ENGLISH); if (!filename.endsWith(".jar")) continue; File file = new File(directory, filenames[j]); if (log.isDebugEnabled()) log.debug(" Including jar file " + file.getAbsolutePath()); URL url = file.toURI().toURL(); set.add(url); } } } // Construct the class loader itself final URL[] array = set.toArray(new URL[set.size()]); return AccessController.doPrivileged( new PrivilegedAction<URLClassLoader>() { @Override public URLClassLoader run() { if (parent == null) return new URLClassLoader(array); else return new URLClassLoader(array, parent); } }); }
// in java/org/apache/catalina/startup/ClassLoaderFactory.java
public static ClassLoader createClassLoader(List<Repository> repositories, final ClassLoader parent) throws Exception { if (log.isDebugEnabled()) log.debug("Creating new class loader"); // Construct the "class path" for this class loader Set<URL> set = new LinkedHashSet<URL>(); if (repositories != null) { for (Repository repository : repositories) { if (repository.getType() == RepositoryType.URL) { URL url = new URL(repository.getLocation()); if (log.isDebugEnabled()) log.debug(" Including URL " + url); set.add(url); } else if (repository.getType() == RepositoryType.DIR) { File directory = new File(repository.getLocation()); directory = directory.getCanonicalFile(); if (!validateFile(directory, RepositoryType.DIR)) { continue; } URL url = directory.toURI().toURL(); if (log.isDebugEnabled()) log.debug(" Including directory " + url); set.add(url); } else if (repository.getType() == RepositoryType.JAR) { File file=new File(repository.getLocation()); file = file.getCanonicalFile(); if (!validateFile(file, RepositoryType.JAR)) { continue; } URL url = file.toURI().toURL(); if (log.isDebugEnabled()) log.debug(" Including jar file " + url); set.add(url); } else if (repository.getType() == RepositoryType.GLOB) { File directory=new File(repository.getLocation()); directory = directory.getCanonicalFile(); if (!validateFile(directory, RepositoryType.GLOB)) { continue; } if (log.isDebugEnabled()) log.debug(" Including directory glob " + directory.getAbsolutePath()); String filenames[] = directory.list(); for (int j = 0; j < filenames.length; j++) { String filename = filenames[j].toLowerCase(Locale.ENGLISH); if (!filename.endsWith(".jar")) continue; File file = new File(directory, filenames[j]); file = file.getCanonicalFile(); if (!validateFile(file, RepositoryType.JAR)) { continue; } if (log.isDebugEnabled()) log.debug(" Including glob jar file " + file.getAbsolutePath()); URL url = file.toURI().toURL(); set.add(url); } } } } // Construct the class loader itself final URL[] array = set.toArray(new URL[set.size()]); if (log.isDebugEnabled()) for (int i = 0; i < array.length; i++) { log.debug(" location " + i + " is " + array[i]); } return AccessController.doPrivileged( new PrivilegedAction<URLClassLoader>() { @Override public URLClassLoader run() { if (parent == null) return new URLClassLoader(array); else return new URLClassLoader(array, parent); } }); }
// in java/org/apache/catalina/startup/CopyParentClassLoaderRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (digester.getLogger().isDebugEnabled()) digester.getLogger().debug("Copying parent class loader"); Container child = (Container) digester.peek(0); Object parent = digester.peek(1); Method method = parent.getClass().getMethod("getParentClassLoader", new Class[0]); ClassLoader classLoader = (ClassLoader) method.invoke(parent, new Object[0]); child.setParentClassLoader(classLoader); }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isLoginConfigSet){ throw new IllegalArgumentException( "<login-config> element is limited to 1 occurrence"); } isLoginConfigSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isJspConfigSet){ throw new IllegalArgumentException( "<jsp-config> element is limited to 1 occurrence"); } isJspConfigSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isSessionConfigSet){ throw new IllegalArgumentException( "<session-config> element is limited to 1 occurrence"); } isSessionConfigSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { SecurityConstraint securityConstraint = (SecurityConstraint) digester.peek(); securityConstraint.setAuthConstraint(true); if (digester.getLogger().isDebugEnabled()) { digester.getLogger() .debug("Calling SecurityConstraint.setAuthConstraint(true)"); } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { WebXml webXml = (WebXml) digester.peek(); webXml.setDistributable(true); if (digester.getLogger().isDebugEnabled()) { digester.getLogger().debug (webXml.getClass().getName() + ".setDistributable(true)"); } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { Object top = digester.peek(); Class<?> paramClasses[] = new Class[1]; paramClasses[0] = "String".getClass(); String paramValues[] = new String[1]; paramValues[0] = digester.getPublicId(); Method m = null; try { m = top.getClass().getMethod(method, paramClasses); } catch (NoSuchMethodException e) { digester.getLogger().error("Can't find method " + method + " in " + top + " CLASS " + top.getClass()); return; } m.invoke(top, (Object [])paramValues); if (digester.getLogger().isDebugEnabled()) digester.getLogger().debug("" + top.getClass().getName() + "." + method + "(" + paramValues[0] + ")"); }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { ServletDef servletDef = new ServletDef(); digester.push(servletDef); if (digester.getLogger().isDebugEnabled()) digester.getLogger().debug("new " + servletDef.getClass().getName()); }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void end(String namespace, String name) throws Exception { ServletDef servletDef = (ServletDef) digester.pop(); if (digester.getLogger().isDebugEnabled()) digester.getLogger().debug("pop " + servletDef.getClass().getName()); }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void end(String namespace, String name) throws Exception { // Retrieve or construct the parameter values array Object parameters[] = null; if (paramCount > 0) { parameters = (Object[]) digester.popParams(); } else { parameters = new Object[0]; super.end(namespace, name); } ArrayList<?> multiParams = (ArrayList<?>) parameters[multiParamIndex]; // Construct the parameter values array we will need // We only do the conversion if the param value is a String and // the specified paramType is not String. Object paramValues[] = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { if (i != multiParamIndex) { // convert nulls and convert stringy parameters // for non-stringy param types if(parameters[i] == null || (parameters[i] instanceof String && !String.class.isAssignableFrom(paramTypes[i]))) { paramValues[i] = IntrospectionUtils.convert((String) parameters[i], paramTypes[i]); } else { paramValues[i] = parameters[i]; } } } // Determine the target object for the method call Object target; if (targetOffset >= 0) { target = digester.peek(targetOffset); } else { target = digester.peek(digester.getCount() + targetOffset); } if (target == null) { StringBuilder sb = new StringBuilder(); sb.append("[CallMethodRule]{"); sb.append(""); sb.append("} Call target is null ("); sb.append("targetOffset="); sb.append(targetOffset); sb.append(",stackdepth="); sb.append(digester.getCount()); sb.append(")"); throw new org.xml.sax.SAXException(sb.toString()); } if (multiParams == null) { paramValues[multiParamIndex] = null; IntrospectionUtils.callMethodN(target, methodName, paramValues, paramTypes); return; } for (int j = 0; j < multiParams.size(); j++) { Object param = multiParams.get(j); if(param == null || (param instanceof String && !String.class.isAssignableFrom(paramTypes[multiParamIndex]))) { paramValues[multiParamIndex] = IntrospectionUtils.convert((String) param, paramTypes[multiParamIndex]); } else { paramValues[multiParamIndex] = param; } IntrospectionUtils.callMethodN(target, methodName, paramValues, paramTypes); } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { WebXml webxml = (WebXml) digester.peek(digester.getCount() - 1); String value = attributes.getValue("metadata-complete"); if ("true".equals(value)) { webxml.setMetadataComplete(true); } else if ("false".equals(value)) { webxml.setMetadataComplete(false); } if (digester.getLogger().isDebugEnabled()) { digester.getLogger().debug (webxml.getClass().getName() + ".setMetadataComplete( " + webxml.isMetadataComplete() + ")"); } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { WebXml webxml = (WebXml) digester.peek(digester.getCount() - 1); webxml.setVersion(attributes.getValue("version")); if (digester.getLogger().isDebugEnabled()) { digester.getLogger().debug (webxml.getClass().getName() + ".setVersion( " + webxml.getVersion() + ")"); } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isNameSet){ throw new IllegalArgumentException(WebRuleSet.sm.getString( "webRuleSet.nameCount")); } isNameSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void body(String namespace, String name, String text) throws Exception { super.body(namespace, name, text); ((WebXml) digester.peek()).setName(text); }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (fragment) { digester.getLogger().warn( WebRuleSet.sm.getString("webRuleSet.absoluteOrdering")); } if (isAbsoluteOrderingSet) { throw new IllegalArgumentException(WebRuleSet.sm.getString( "webRuleSet.absoluteOrderingCount")); } else { isAbsoluteOrderingSet = true; } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (!fragment) { digester.getLogger().warn( WebRuleSet.sm.getString("webRuleSet.relativeOrdering")); } if (isRelativeOrderingSet) { throw new IllegalArgumentException(WebRuleSet.sm.getString( "webRuleSet.relativeOrderingCount")); } else { isRelativeOrderingSet = true; } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void body(String namespace, String name, String text) throws Exception { String namespaceuri = null; String localpart = text; int colon = text.indexOf(':'); if (colon >= 0) { String prefix = text.substring(0,colon); namespaceuri = digester.findNamespaceURI(prefix); localpart = text.substring(colon+1); } ContextHandler contextHandler = (ContextHandler)digester.peek(); contextHandler.addSoapHeaders(localpart,namespaceuri); }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void body(String namespace, String name, String text) throws Exception { String namespaceuri = null; String localpart = text; int colon = text.indexOf(':'); if (colon >= 0) { String prefix = text.substring(0,colon); namespaceuri = digester.findNamespaceURI(prefix); localpart = text.substring(colon+1); } ContextService contextService = (ContextService)digester.peek(); contextService.setServiceqnameLocalpart(localpart); contextService.setServiceqnameNamespaceURI(namespaceuri); }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { WebXml webXml = (WebXml) digester.peek(digester.getCount() - 1); // If we have a public ID, this is not a 2.4 or later webapp boolean havePublicId = (webXml.getPublicId() != null); // havePublicId and isServlet24OrLater should be mutually exclusive if (havePublicId == isServlet24OrLater) { throw new IllegalArgumentException( "taglib definition not consistent with specification version"); } }
// in java/org/apache/catalina/startup/Catalina.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (digester.getLogger().isDebugEnabled()) { digester.getLogger().debug("Setting parent class loader"); } Container top = (Container) digester.peek(); top.setParentClassLoader(parentClassLoader); }
// in java/org/apache/catalina/startup/SetNextNamingRule.java
Override public void end(String namespace, String name) throws Exception { // Identify the objects to be used Object child = digester.peek(0); Object parent = digester.peek(1); NamingResources namingResources = null; if (parent instanceof Context) { namingResources = ((Context) parent).getNamingResources(); } else { namingResources = (NamingResources) parent; } // Call the specified method IntrospectionUtils.callMethod1(namingResources, methodName, child, paramType, digester.getClassLoader()); }
// in java/org/apache/catalina/startup/Bootstrap.java
private ClassLoader createClassLoader(String name, ClassLoader parent) throws Exception { String value = CatalinaProperties.getProperty(name + ".loader"); if ((value == null) || (value.equals(""))) return parent; value = replace(value); List<Repository> repositories = new ArrayList<Repository>(); StringTokenizer tokenizer = new StringTokenizer(value, ","); while (tokenizer.hasMoreElements()) { String repository = tokenizer.nextToken().trim(); if (repository.length() == 0) { continue; } // Check for a JAR URL repository try { @SuppressWarnings("unused") URL url = new URL(repository); repositories.add( new Repository(repository, RepositoryType.URL)); continue; } catch (MalformedURLException e) { // Ignore } // Local repository if (repository.endsWith("*.jar")) { repository = repository.substring (0, repository.length() - "*.jar".length()); repositories.add( new Repository(repository, RepositoryType.GLOB)); } else if (repository.endsWith(".jar")) { repositories.add( new Repository(repository, RepositoryType.JAR)); } else { repositories.add( new Repository(repository, RepositoryType.DIR)); } } return ClassLoaderFactory.createClassLoader(repositories, parent); }
// in java/org/apache/catalina/startup/Bootstrap.java
public void init() throws Exception { initClassLoaders(); Thread.currentThread().setContextClassLoader(catalinaLoader); SecurityClassLoad.securityClassLoad(catalinaLoader); // Load our startup class and call its process() method if (log.isDebugEnabled()) log.debug("Loading startup class"); Class<?> startupClass = catalinaLoader.loadClass ("org.apache.catalina.startup.Catalina"); Object startupInstance = startupClass.newInstance(); // Set the shared extensions class loader if (log.isDebugEnabled()) log.debug("Setting startup class properties"); String methodName = "setParentClassLoader"; Class<?> paramTypes[] = new Class[1]; paramTypes[0] = Class.forName("java.lang.ClassLoader"); Object paramValues[] = new Object[1]; paramValues[0] = sharedLoader; Method method = startupInstance.getClass().getMethod(methodName, paramTypes); method.invoke(startupInstance, paramValues); catalinaDaemon = startupInstance; }
// in java/org/apache/catalina/startup/Bootstrap.java
private void load(String[] arguments) throws Exception { // Call the load() method String methodName = "load"; Object param[]; Class<?> paramTypes[]; if (arguments==null || arguments.length==0) { paramTypes = null; param = null; } else { paramTypes = new Class[1]; paramTypes[0] = arguments.getClass(); param = new Object[1]; param[0] = arguments; } Method method = catalinaDaemon.getClass().getMethod(methodName, paramTypes); if (log.isDebugEnabled()) log.debug("Calling startup class " + method); method.invoke(catalinaDaemon, param); }
// in java/org/apache/catalina/startup/Bootstrap.java
private Object getServer() throws Exception { String methodName = "getServer"; Method method = catalinaDaemon.getClass().getMethod(methodName); return method.invoke(catalinaDaemon); }
// in java/org/apache/catalina/startup/Bootstrap.java
public void init(String[] arguments) throws Exception { init(); load(arguments); }
// in java/org/apache/catalina/startup/Bootstrap.java
public void start() throws Exception { if( catalinaDaemon==null ) init(); Method method = catalinaDaemon.getClass().getMethod("start", (Class [] )null); method.invoke(catalinaDaemon, (Object [])null); }
// in java/org/apache/catalina/startup/Bootstrap.java
public void stop() throws Exception { Method method = catalinaDaemon.getClass().getMethod("stop", (Class [] ) null); method.invoke(catalinaDaemon, (Object [] ) null); }
// in java/org/apache/catalina/startup/Bootstrap.java
public void stopServer() throws Exception { Method method = catalinaDaemon.getClass().getMethod("stopServer", (Class []) null); method.invoke(catalinaDaemon, (Object []) null); }
// in java/org/apache/catalina/startup/Bootstrap.java
public void stopServer(String[] arguments) throws Exception { Object param[]; Class<?> paramTypes[]; if (arguments==null || arguments.length==0) { paramTypes = null; param = null; } else { paramTypes = new Class[1]; paramTypes[0] = arguments.getClass(); param = new Object[1]; param[0] = arguments; } Method method = catalinaDaemon.getClass().getMethod("stopServer", paramTypes); method.invoke(catalinaDaemon, param); }
// in java/org/apache/catalina/startup/Bootstrap.java
public void setAwait(boolean await) throws Exception { Class<?> paramTypes[] = new Class[1]; paramTypes[0] = Boolean.TYPE; Object paramValues[] = new Object[1]; paramValues[0] = Boolean.valueOf(await); Method method = catalinaDaemon.getClass().getMethod("setAwait", paramTypes); method.invoke(catalinaDaemon, paramValues); }
// in java/org/apache/catalina/startup/Bootstrap.java
public boolean getAwait() throws Exception { Class<?> paramTypes[] = new Class[0]; Object paramValues[] = new Object[0]; Method method = catalinaDaemon.getClass().getMethod("getAwait", paramTypes); Boolean b=(Boolean)method.invoke(catalinaDaemon, paramValues); return b.booleanValue(); }
// in java/org/apache/catalina/startup/TldRuleSet.java
Override public void body(String namespace, String name, String text) throws Exception { taglibUriRule.setDuplicateUri(false); }
// in java/org/apache/catalina/startup/TldRuleSet.java
Override public void body(String namespace, String name, String text) throws Exception { TldConfig tldConfig = (TldConfig) digester.peek(digester.getCount() - 1); if (tldConfig.isKnownTaglibUri(text)) { // Already seen this URI duplicateUri = true; // This is expected if the URI was defined in web.xml // Log message at debug in this case if (tldConfig.isKnownWebxmlTaglibUri(text)) { if (digester.getLogger().isDebugEnabled()) { digester.getLogger().debug( "TLD skipped. URI: " + text + " is already defined"); } } else { digester.getLogger().info( "TLD skipped. URI: " + text + " is already defined"); } } else { // New URI. Add it to known list and carry on tldConfig.addTaglibUri(text); } }
// in java/org/apache/catalina/startup/TldRuleSet.java
Override public void body(String namespace, String name, String text) throws Exception { TldConfig tldConfig = (TldConfig) digester.peek(digester.getCount() - 1); // Only process the listener if the URI is not a duplicate if (!taglibUriRule.isDuplicateUri()) { tldConfig.addApplicationListener(text.trim()); } }
// in java/org/apache/catalina/loader/WebappLoader.java
private WebappClassLoader createClassLoader() throws Exception { Class<?> clazz = Class.forName(loaderClass); WebappClassLoader classLoader = null; if (parentClassLoader == null) { parentClassLoader = container.getParentClassLoader(); } Class<?>[] argTypes = { ClassLoader.class }; Object[] args = { parentClassLoader }; Constructor<?> constr = clazz.getConstructor(argTypes); classLoader = (WebappClassLoader) constr.newInstance(args); return classLoader; }
// in java/org/apache/catalina/realm/MemoryRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { String username = attributes.getValue("name"); if (username == null) { username = attributes.getValue("username"); } String password = attributes.getValue("password"); String roles = attributes.getValue("roles"); MemoryRealm realm = (MemoryRealm) digester.peek(digester.getCount() - 1); realm.addUser(username, password, roles); }
// in java/org/apache/catalina/realm/GenericPrincipal.java
Override public void logout() throws Exception { if (loginContext != null) { loginContext.logout(); } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
private Container getParentContainerFromParent(ObjectName pname) throws Exception { String type = pname.getKeyProperty("type"); String j2eeType = pname.getKeyProperty("j2eeType"); Service service = getService(pname); StandardEngine engine = (StandardEngine) service.getContainer(); if ((j2eeType!=null) && (j2eeType.equals("WebModule"))) { String name = pname.getKeyProperty("name"); name = name.substring(2); int i = name.indexOf("/"); String hostName = name.substring(0,i); String path = name.substring(i); Container host = engine.findChild(hostName); String pathStr = getPathStr(path); Container context = host.findChild(pathStr); return context; } else if (type != null) { if (type.equals("Engine")) { return engine; } else if (type.equals("Host")) { String hostName = pname.getKeyProperty("host"); Container host = engine.findChild(hostName); return host; } } return null; }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
private Container getParentContainerFromChild(ObjectName oname) throws Exception { String hostName = oname.getKeyProperty("host"); String path = oname.getKeyProperty("path"); Service service = getService(oname); Container engine = service.getContainer(); if (hostName == null) { // child's container is Engine return engine; } else if (path == null) { // child's container is Host Container host = engine.findChild(hostName); return host; } else { // child's container is Context Container host = engine.findChild(hostName); path = getPathStr(path); Container context = host.findChild(path); return context; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
private Service getService(ObjectName oname) throws Exception { if (container instanceof Service) { // Don't bother checking the domain - this is the only option return (Service) container; } StandardService service = null; String domain = oname.getDomain(); if (container instanceof Server) { Service[] services = ((Server)container).findServices(); for (int i = 0; i < services.length; i++) { service = (StandardService) services[i]; if (domain.equals(service.getObjectName().getDomain())) { break; } } } if (service == null || !service.getObjectName().getDomain().equals(domain)) { throw new Exception("Service with the domain is not found"); } return service; }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createAjpConnector(String parent, String address, int port) throws Exception { return createConnector(parent, address, port, true, false); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createDataSourceRealm(String parent, String dataSourceName, String roleNameCol, String userCredCol, String userNameCol, String userRoleTable, String userTable) throws Exception { // Create a new DataSourceRealm instance DataSourceRealm realm = new DataSourceRealm(); realm.setDataSourceName(dataSourceName); realm.setRoleNameCol(roleNameCol); realm.setUserCredCol(userCredCol); realm.setUserNameCol(userNameCol); realm.setUserRoleTable(userRoleTable); realm.setUserTable(userTable); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); // Add the new instance to its parent component container.setRealm(realm); // Return the corresponding MBean name ObjectName oname = realm.getObjectName(); if (oname != null) { return (oname.toString()); } else { return null; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createHttpConnector(String parent, String address, int port) throws Exception { return createConnector(parent, address, port, false, false); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
private String createConnector(String parent, String address, int port, boolean isAjp, boolean isSSL) throws Exception { Connector retobj = new Connector(); if ((address!=null) && (address.length()>0)) { retobj.setProperty("address", address); } // Set port number retobj.setPort(port); // Set the protocol retobj.setProtocol(isAjp ? "AJP/1.3" : "HTTP/1.1"); // Set SSL retobj.setSecure(isSSL); retobj.setScheme(isSSL ? "https" : "http"); // Add the new instance to its parent component // FIX ME - addConnector will fail ObjectName pname = new ObjectName(parent); Service service = getService(pname); service.addConnector(retobj); // Return the corresponding MBean name ObjectName coname = retobj.getObjectName(); return (coname.toString()); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createHttpsConnector(String parent, String address, int port) throws Exception { return createConnector(parent, address, port, false, true); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createJDBCRealm(String parent, String driverName, String connectionName, String connectionPassword, String connectionURL) throws Exception { // Create a new JDBCRealm instance JDBCRealm realm = new JDBCRealm(); realm.setDriverName(driverName); realm.setConnectionName(connectionName); realm.setConnectionPassword(connectionPassword); realm.setConnectionURL(connectionURL); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); // Add the new instance to its parent component container.setRealm(realm); // Return the corresponding MBean name ObjectName oname = realm.getObjectName(); if (oname != null) { return (oname.toString()); } else { return null; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createJNDIRealm(String parent) throws Exception { // Create a new JNDIRealm instance JNDIRealm realm = new JNDIRealm(); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); // Add the new instance to its parent component container.setRealm(realm); // Return the corresponding MBean name ObjectName oname = realm.getObjectName(); if (oname != null) { return (oname.toString()); } else { return null; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createMemoryRealm(String parent) throws Exception { // Create a new MemoryRealm instance MemoryRealm realm = new MemoryRealm(); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); // Add the new instance to its parent component container.setRealm(realm); // Return the corresponding MBean name ObjectName oname = realm.getObjectName(); if (oname != null) { return (oname.toString()); } else { return null; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createStandardContext(String parent, String path, String docBase) throws Exception { return createStandardContext(parent, path, docBase, false, false, false, false); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createStandardContext(String parent, String path, String docBase, boolean xmlValidation, boolean xmlNamespaceAware, boolean tldValidation, boolean tldNamespaceAware) throws Exception { // Create a new StandardContext instance StandardContext context = new StandardContext(); path = getPathStr(path); context.setPath(path); context.setDocBase(docBase); context.setXmlValidation(xmlValidation); context.setXmlNamespaceAware(xmlNamespaceAware); context.setTldValidation(tldValidation); context.setTldNamespaceAware(tldNamespaceAware); ContextConfig contextConfig = new ContextConfig(); context.addLifecycleListener(contextConfig); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); ObjectName deployer = new ObjectName(pname.getDomain()+ ":type=Deployer,host="+ pname.getKeyProperty("host")); if(mserver.isRegistered(deployer)) { String contextName = context.getName(); mserver.invoke(deployer, "addServiced", new Object [] {contextName}, new String [] {"java.lang.String"}); String configPath = (String)mserver.getAttribute(deployer, "configBaseName"); String baseName = context.getBaseName(); File configFile = new File(new File(configPath), baseName+".xml"); if (configFile.isFile()) { context.setConfigFile(configFile.toURI().toURL()); } mserver.invoke(deployer, "manageApp", new Object[] {context}, new String[] {"org.apache.catalina.Context"}); mserver.invoke(deployer, "removeServiced", new Object [] {contextName}, new String [] {"java.lang.String"}); } else { log.warn("Deployer not found for "+pname.getKeyProperty("host")); Service service = getService(pname); Engine engine = (Engine) service.getContainer(); Host host = (Host) engine.findChild(pname.getKeyProperty("host")); host.addChild(context); } // Return the corresponding MBean name return context.getObjectName().toString(); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createStandardHost(String parent, String name, String appBase, boolean autoDeploy, boolean deployOnStartup, boolean deployXML, boolean unpackWARs) throws Exception { // Create a new StandardHost instance StandardHost host = new StandardHost(); host.setName(name); host.setAppBase(appBase); host.setAutoDeploy(autoDeploy); host.setDeployOnStartup(deployOnStartup); host.setDeployXML(deployXML); host.setUnpackWARs(unpackWARs); // add HostConfig for active reloading HostConfig hostConfig = new HostConfig(); host.addLifecycleListener(hostConfig); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Service service = getService(pname); Engine engine = (Engine) service.getContainer(); engine.addChild(host); // Return the corresponding MBean name return (host.getObjectName().toString()); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createStandardServiceEngine(String domain, String defaultHost, String baseDir) throws Exception{ if (!(container instanceof Server)) { throw new Exception("Container not Server"); } StandardEngine engine = new StandardEngine(); engine.setDomain(domain); engine.setName(domain); engine.setDefaultHost(defaultHost); Service service = new StandardService(); service.setContainer(engine); service.setName(domain); ((Server) container).addService(service); return engine.getObjectName().toString(); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createStandardManager(String parent) throws Exception { // Create a new StandardManager instance StandardManager manager = new StandardManager(); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); if (container != null) { container.setManager(manager); } ObjectName oname = manager.getObjectName(); if (oname != null) { return (oname.toString()); } else { return null; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createUserDatabaseRealm(String parent, String resourceName) throws Exception { // Create a new UserDatabaseRealm instance UserDatabaseRealm realm = new UserDatabaseRealm(); realm.setResourceName(resourceName); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); // Add the new instance to its parent component container.setRealm(realm); // Return the corresponding MBean name ObjectName oname = realm.getObjectName(); // FIXME getObjectName() returns null //ObjectName oname = // MBeanUtils.createObjectName(pname.getDomain(), realm); if (oname != null) { return (oname.toString()); } else { return null; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createValve(String className, String parent) throws Exception { // Look for the parent ObjectName parentName = new ObjectName(parent); Container container = getParentContainerFromParent(parentName); if (container == null) { // TODO throw new IllegalArgumentException(); } Valve valve = (Valve) Class.forName(className).newInstance(); container.getPipeline().addValve(valve); if (valve instanceof JmxEnabled) { return ((JmxEnabled) valve).getObjectName().toString(); } else { return null; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createWebappLoader(String parent) throws Exception { // Create a new WebappLoader instance WebappLoader loader = new WebappLoader(); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); if (container != null) { container.setLoader(loader); } // FIXME add Loader.getObjectName //ObjectName oname = loader.getObjectName(); ObjectName oname = MBeanUtils.createObjectName(pname.getDomain(), loader); return (oname.toString()); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeConnector(String name) throws Exception { // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(name); Service service = getService(oname); String port = oname.getKeyProperty("port"); //String address = oname.getKeyProperty("address"); Connector conns[] = service.findConnectors(); for (int i = 0; i < conns.length; i++) { String connAddress = String.valueOf(conns[i].getProperty("address")); String connPort = ""+conns[i].getPort(); // if (((address.equals("null")) && if ((connAddress==null) && port.equals(connPort)) { service.removeConnector(conns[i]); conns[i].destroy(); break; } // } else if (address.equals(connAddress)) if (port.equals(connPort)) { // Remove this component from its parent component service.removeConnector(conns[i]); conns[i].destroy(); break; } } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeContext(String contextName) throws Exception { // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(contextName); String domain = oname.getDomain(); StandardService service = (StandardService) getService(oname); Engine engine = (Engine) service.getContainer(); String name = oname.getKeyProperty("name"); name = name.substring(2); int i = name.indexOf("/"); String hostName = name.substring(0,i); String path = name.substring(i); ObjectName deployer = new ObjectName(domain+":type=Deployer,host="+ hostName); String pathStr = getPathStr(path); if(mserver.isRegistered(deployer)) { mserver.invoke(deployer,"addServiced", new Object[]{pathStr}, new String[] {"java.lang.String"}); mserver.invoke(deployer,"unmanageApp", new Object[] {pathStr}, new String[] {"java.lang.String"}); mserver.invoke(deployer,"removeServiced", new Object[] {pathStr}, new String[] {"java.lang.String"}); } else { log.warn("Deployer not found for "+hostName); Host host = (Host) engine.findChild(hostName); Context context = (Context) host.findChild(pathStr); // Remove this component from its parent component host.removeChild(context); if(context instanceof StandardContext) try { ((StandardContext)context).destroy(); } catch (Exception e) { log.warn("Error during context [" + context.getName() + "] destroy ", e); } } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeHost(String name) throws Exception { // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(name); String hostName = oname.getKeyProperty("host"); Service service = getService(oname); Engine engine = (Engine) service.getContainer(); Host host = (Host) engine.findChild(hostName); // Remove this component from its parent component if(host!=null) { engine.removeChild(host); } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeLoader(String name) throws Exception { ObjectName oname = new ObjectName(name); // Acquire a reference to the component to be removed Container container = getParentContainerFromChild(oname); container.setLoader(null); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeManager(String name) throws Exception { ObjectName oname = new ObjectName(name); // Acquire a reference to the component to be removed Container container = getParentContainerFromChild(oname); container.setManager(null); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeRealm(String name) throws Exception { ObjectName oname = new ObjectName(name); // Acquire a reference to the component to be removed Container container = getParentContainerFromChild(oname); container.setRealm(null); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeService(String name) throws Exception { if (!(container instanceof Server)) { throw new Exception(); } // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(name); Service service = getService(oname); ((Server) container).removeService(service); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeValve(String name) throws Exception { // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(name); Container container = getParentContainerFromChild(oname); Valve[] valves = container.getPipeline().getValves(); for (int i = 0; i < valves.length; i++) { ObjectName voname = ((JmxEnabled) valves[i]).getObjectName(); if (voname.equals(oname)) { container.getPipeline().removeValve(valves[i]); } } }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
protected void createMBeans(String name, UserDatabase database) throws Exception { // Create the MBean for the UserDatabase itself if (log.isDebugEnabled()) { log.debug("Creating UserDatabase MBeans for resource " + name); log.debug("Database=" + database); } if (MBeanUtils.createMBean(database) == null) { throw new IllegalArgumentException ("Cannot create UserDatabase MBean for resource " + name); } // Create the MBeans for each defined Role Iterator<Role> roles = database.getRoles(); while (roles.hasNext()) { Role role = roles.next(); if (log.isDebugEnabled()) { log.debug(" Creating Role MBean for role " + role); } if (MBeanUtils.createMBean(role) == null) { throw new IllegalArgumentException ("Cannot create Role MBean for role " + role); } } // Create the MBeans for each defined Group Iterator<Group> groups = database.getGroups(); while (groups.hasNext()) { Group group = groups.next(); if (log.isDebugEnabled()) { log.debug(" Creating Group MBean for group " + group); } if (MBeanUtils.createMBean(group) == null) { throw new IllegalArgumentException ("Cannot create Group MBean for group " + group); } } // Create the MBeans for each defined User Iterator<User> users = database.getUsers(); while (users.hasNext()) { User user = users.next(); if (log.isDebugEnabled()) { log.debug(" Creating User MBean for user " + user); } if (MBeanUtils.createMBean(user) == null) { throw new IllegalArgumentException ("Cannot create User MBean for user " + user); } } }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static DynamicMBean createMBean(ContextEnvironment environment) throws Exception { String mname = createManagedName(environment); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(environment); ObjectName oname = createObjectName(domain, environment); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static DynamicMBean createMBean(ContextResource resource) throws Exception { String mname = createManagedName(resource); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(resource); ObjectName oname = createObjectName(domain, resource); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static DynamicMBean createMBean(ContextResourceLink resourceLink) throws Exception { String mname = createManagedName(resourceLink); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(resourceLink); ObjectName oname = createObjectName(domain, resourceLink); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(Group group) throws Exception { String mname = createManagedName(group); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(group); ObjectName oname = createObjectName(domain, group); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(Role role) throws Exception { String mname = createManagedName(role); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(role); ObjectName oname = createObjectName(domain, role); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(User user) throws Exception { String mname = createManagedName(user); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(user); ObjectName oname = createObjectName(domain, user); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(UserDatabase userDatabase) throws Exception { String mname = createManagedName(userDatabase); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(userDatabase); ObjectName oname = createObjectName(domain, userDatabase); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static void destroyMBean(ContextEnvironment environment) throws Exception { String mname = createManagedName(environment); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, environment); if( mserver.isRegistered(oname) ) mserver.unregisterMBean(oname); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static void destroyMBean(ContextResource resource) throws Exception { // If this is a user database resource need to destroy groups, roles, // users and UserDatabase mbean if ("org.apache.catalina.UserDatabase".equals(resource.getType())) { destroyMBeanUserDatabase(resource.getName()); } String mname = createManagedName(resource); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, resource); if( mserver.isRegistered(oname )) mserver.unregisterMBean(oname); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static void destroyMBean(ContextResourceLink resourceLink) throws Exception { String mname = createManagedName(resourceLink); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, resourceLink); if( mserver.isRegistered(oname) ) mserver.unregisterMBean(oname); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static void destroyMBean(Group group) throws Exception { String mname = createManagedName(group); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, group); if( mserver.isRegistered(oname) ) mserver.unregisterMBean(oname); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static void destroyMBean(Role role) throws Exception { String mname = createManagedName(role); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, role); if( mserver.isRegistered(oname) ) mserver.unregisterMBean(oname); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static void destroyMBean(User user) throws Exception { String mname = createManagedName(user); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, user); if( mserver.isRegistered(oname) ) mserver.unregisterMBean(oname); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static void destroyMBeanUserDatabase(String userDatabase) throws Exception { ObjectName query = null; Set<ObjectName> results = null; // Groups query = new ObjectName( "Users:type=Group,database=" + userDatabase + ",*"); results = mserver.queryNames(query, null); for(ObjectName result : results) { mserver.unregisterMBean(result); } // Roles query = new ObjectName( "Users:type=Role,database=" + userDatabase + ",*"); results = mserver.queryNames(query, null); for(ObjectName result : results) { mserver.unregisterMBean(result); } // Users query = new ObjectName( "Users:type=User,database=" + userDatabase + ",*"); results = mserver.queryNames(query, null); for(ObjectName result : results) { mserver.unregisterMBean(result); } // The database itself ObjectName db = new ObjectName( "Users:type=UserDatabase,database=" + userDatabase); mserver.unregisterMBean(db); }
// in java/org/apache/catalina/users/MemoryUserDatabaseFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { // We only know how to deal with <code>javax.naming.Reference</code>s // that specify a class name of "org.apache.catalina.UserDatabase" if ((obj == null) || !(obj instanceof Reference)) { return (null); } Reference ref = (Reference) obj; if (!"org.apache.catalina.UserDatabase".equals(ref.getClassName())) { return (null); } // Create and configure a MemoryUserDatabase instance based on the // RefAddr values associated with this Reference MemoryUserDatabase database = new MemoryUserDatabase(name.toString()); RefAddr ra = null; ra = ref.get("pathname"); if (ra != null) { database.setPathname(ra.getContent().toString()); } ra = ref.get("readonly"); if (ra != null) { database.setReadonly(Boolean.valueOf(ra.getContent().toString()).booleanValue()); } // Return the configured database instance database.open(); // Don't try something we know won't work if (!database.getReadonly()) database.save(); return (database); }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
Override public void close() throws Exception { save(); synchronized (groups) { synchronized (users) { users.clear(); groups.clear(); } } }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
Override public void open() throws Exception { synchronized (groups) { synchronized (users) { // Erase any previous groups and users users.clear(); groups.clear(); roles.clear(); // Construct a reader for the XML input file (if it exists) File file = new File(pathname); if (!file.isAbsolute()) { file = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathname); } if (!file.exists()) { return; } // Construct a digester to read the XML input file Digester digester = new Digester(); try { digester.setFeature( "http://apache.org/xml/features/allow-java-encodings", true); } catch (Exception e) { log.warn(sm.getString("memoryUserDatabase.xmlFeatureEncoding"), e); } digester.addFactoryCreate ("tomcat-users/group", new MemoryGroupCreationFactory(this), true); digester.addFactoryCreate ("tomcat-users/role", new MemoryRoleCreationFactory(this), true); digester.addFactoryCreate ("tomcat-users/user", new MemoryUserCreationFactory(this), true); // Parse the XML input file to load this database FileInputStream fis = null; try { fis = new FileInputStream(file); digester.parse(fis); } finally { if (fis != null) { try { fis.close(); } catch (IOException ioe) { // Ignore } } } } } }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
Override public void save() throws Exception { if (getReadonly()) { log.error(sm.getString("memoryUserDatabase.readOnly")); return; } if (!isWriteable()) { log.warn(sm.getString("memoryUserDatabase.notPersistable")); return; } // Write out contents to a temporary file File fileNew = new File(pathnameNew); if (!fileNew.isAbsolute()) { fileNew = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathnameNew); } PrintWriter writer = null; try { // Configure our PrintWriter FileOutputStream fos = new FileOutputStream(fileNew); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF8"); writer = new PrintWriter(osw); // Print the file prolog writer.println("<?xml version='1.0' encoding='utf-8'?>"); writer.println("<tomcat-users>"); // Print entries for each defined role, group, and user Iterator<?> values = null; values = getRoles(); while (values.hasNext()) { writer.print(" "); writer.println(values.next()); } values = getGroups(); while (values.hasNext()) { writer.print(" "); writer.println(values.next()); } values = getUsers(); while (values.hasNext()) { writer.print(" "); writer.println(((MemoryUser) values.next()).toXml()); } // Print the file epilog writer.println("</tomcat-users>"); // Check for errors that occurred while printing if (writer.checkError()) { writer.close(); fileNew.delete(); throw new IOException (sm.getString("memoryUserDatabase.writeException", fileNew.getAbsolutePath())); } writer.close(); } catch (IOException e) { if (writer != null) { writer.close(); } fileNew.delete(); throw e; } // Perform the required renames to permanently save this file File fileOld = new File(pathnameOld); if (!fileOld.isAbsolute()) { fileOld = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathnameOld); } fileOld.delete(); File fileOrig = new File(pathname); if (!fileOrig.isAbsolute()) { fileOrig = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathname); } if (fileOrig.exists()) { fileOld.delete(); if (!fileOrig.renameTo(fileOld)) { throw new IOException (sm.getString("memoryUserDatabase.renameOld", fileOld.getAbsolutePath())); } } if (!fileNew.renameTo(fileOrig)) { if (fileOld.exists()) { fileOld.renameTo(fileOrig); } throw new IOException (sm.getString("memoryUserDatabase.renameNew", fileOrig.getAbsolutePath())); } fileOld.delete(); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if ((jmxServerConnection == null)) { throw new BuildException("Must open a connection!"); } else if (isEcho()) { handleOutput("JMX Connection ref=" + ref + " is open!"); } return null; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorSetTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((attribute == null || value == null)) { throw new BuildException( "Must specify a 'attribute' and 'value' for set"); } return jmxSet(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorSetTask.java
protected String jmxSet(MBeanServerConnection jmxServerConnection, String name) throws Exception { Object realValue; if (type != null) { realValue = convertStringToType(value, type); } else { if (isConvert()) { String mType = getMBeanAttributeType(jmxServerConnection, name, attribute); realValue = convertStringToType(value, mType); } else realValue = value; } jmxServerConnection.setAttribute(new ObjectName(name), new Attribute( attribute, realValue)); return null; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorSetTask.java
protected String getMBeanAttributeType( MBeanServerConnection jmxServerConnection, String name, String attribute) throws Exception { ObjectName oname = new ObjectName(name); String mattrType = null; MBeanInfo minfo = jmxServerConnection.getMBeanInfo(oname); MBeanAttributeInfo attrs[] = minfo.getAttributes(); if (attrs != null) { for (int i = 0; mattrType == null && i < attrs.length; i++) { if (attribute.equals(attrs[i].getName())) mattrType = attrs[i].getType(); } } return mattrType; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorGetTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((attribute == null)) { throw new BuildException( "Must specify a 'attribute' for get"); } return jmxGet(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorGetTask.java
protected String jmxGet(MBeanServerConnection jmxServerConnection,String name) throws Exception { String error = null; if(isEcho()) { handleOutput("MBean " + name + " get attribute " + attribute ); } Object result = jmxServerConnection.getAttribute( new ObjectName(name), attribute); if (result != null) { echoResult(attribute,result); createProperty(result); } else error = "Attribute " + attribute + " is empty"; return error; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } return jmxQuery(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorUnregisterTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } return jmxUuregister(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorUnregisterTask.java
protected String jmxUuregister(MBeanServerConnection jmxServerConnection,String name) throws Exception { String error = null; if(isEcho()) { handleOutput("Unregister MBean " + name ); } jmxServerConnection.unregisterMBean( new ObjectName(name)); return error; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorCreateTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((className == null)) { throw new BuildException( "Must specify a 'className' for get"); } return jmxCreate(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorCreateTask.java
protected String jmxCreate(MBeanServerConnection jmxServerConnection, String name) throws Exception { String error = null; Object argsA[] = null; String sigA[] = null; if (args != null) { argsA = new Object[ args.size()]; sigA = new String[args.size()]; for( int i=0; i<args.size(); i++ ) { Arg arg=args.get(i); if( arg.type==null) { arg.type="java.lang.String"; sigA[i]=arg.getType(); argsA[i]=arg.getValue(); } else { sigA[i]=arg.getType(); argsA[i]=convertStringToType(arg.getValue(),arg.getType()); } } } if (classLoader != null && !"".equals(classLoader)) { if (isEcho()) { handleOutput("create MBean " + name + " from class " + className + " with classLoader " + classLoader); } if(args == null) jmxServerConnection.createMBean(className, new ObjectName(name), new ObjectName(classLoader)); else jmxServerConnection.createMBean(className, new ObjectName(name), new ObjectName(classLoader),argsA,sigA); } else { if (isEcho()) { handleOutput("create MBean " + name + " from class " + className); } if(args == null) jmxServerConnection.createMBean(className, new ObjectName(name)); else jmxServerConnection.createMBean(className, new ObjectName(name),argsA,sigA); } return error; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorInvokeTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((operation == null)) { throw new BuildException( "Must specify a 'operation' for call"); } return jmxInvoke(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorInvokeTask.java
protected String jmxInvoke(MBeanServerConnection jmxServerConnection, String name) throws Exception { Object result ; if (args == null) { result = jmxServerConnection.invoke(new ObjectName(name), operation, null, null); } else { Object argsA[]=new Object[ args.size()]; String sigA[]=new String[args.size()]; for( int i=0; i<args.size(); i++ ) { Arg arg=args.get(i); if( arg.type==null) { arg.type="java.lang.String"; sigA[i]=arg.getType(); argsA[i]=arg.getValue(); } else { sigA[i]=arg.getType(); argsA[i]=convertStringToType(arg.getValue(),arg.getType()); } } result = jmxServerConnection.invoke(new ObjectName(name), operation, argsA, sigA); } if(result != null) { echoResult(operation,result); createProperty(result); } return null; }
// in java/org/apache/catalina/manager/StatusTransformer.java
public static void writeVMState(PrintWriter writer, int mode) throws Exception { if (mode == 0){ writer.print("<h1>JVM</h1>"); writer.print("<p>"); writer.print(" Free memory: "); writer.print(formatSize( Long.valueOf(Runtime.getRuntime().freeMemory()), true)); writer.print(" Total memory: "); writer.print(formatSize( Long.valueOf(Runtime.getRuntime().totalMemory()), true)); writer.print(" Max memory: "); writer.print(formatSize( Long.valueOf(Runtime.getRuntime().maxMemory()), true)); writer.print("</p>"); } else if (mode == 1){ writer.write("<jvm>"); writer.write("<memory"); writer.write(" free='" + Runtime.getRuntime().freeMemory() + "'"); writer.write(" total='" + Runtime.getRuntime().totalMemory() + "'"); writer.write(" max='" + Runtime.getRuntime().maxMemory() + "'/>"); writer.write("</jvm>"); } }
// in java/org/apache/catalina/manager/StatusTransformer.java
public static void writeConnectorState(PrintWriter writer, ObjectName tpName, String name, MBeanServer mBeanServer, Vector<ObjectName> globalRequestProcessors, Vector<ObjectName> requestProcessors, int mode) throws Exception { if (mode == 0) { writer.print("<h1>"); writer.print(name); writer.print("</h1>"); writer.print("<p>"); writer.print(" Max threads: "); writer.print(mBeanServer.getAttribute(tpName, "maxThreads")); writer.print(" Current thread count: "); writer.print(mBeanServer.getAttribute(tpName, "currentThreadCount")); writer.print(" Current thread busy: "); writer.print(mBeanServer.getAttribute(tpName, "currentThreadsBusy")); try { Object value = mBeanServer.getAttribute(tpName, "keepAliveCount"); writer.print(" Keeped alive sockets count: "); writer.print(value); } catch (Exception e) { // Ignore } writer.print("<br>"); ObjectName grpName = null; Enumeration<ObjectName> enumeration = globalRequestProcessors.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); if (name.equals(objectName.getKeyProperty("name"))) { grpName = objectName; } } if (grpName == null) { return; } writer.print(" Max processing time: "); writer.print(formatTime(mBeanServer.getAttribute (grpName, "maxTime"), false)); writer.print(" Processing time: "); writer.print(formatTime(mBeanServer.getAttribute (grpName, "processingTime"), true)); writer.print(" Request count: "); writer.print(mBeanServer.getAttribute(grpName, "requestCount")); writer.print(" Error count: "); writer.print(mBeanServer.getAttribute(grpName, "errorCount")); writer.print(" Bytes received: "); writer.print(formatSize(mBeanServer.getAttribute (grpName, "bytesReceived"), true)); writer.print(" Bytes sent: "); writer.print(formatSize(mBeanServer.getAttribute (grpName, "bytesSent"), true)); writer.print("</p>"); writer.print("<table border=\"0\"><tr><th>Stage</th><th>Time</th><th>B Sent</th><th>B Recv</th><th>Client</th><th>VHost</th><th>Request</th></tr>"); enumeration = requestProcessors.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); if (name.equals(objectName.getKeyProperty("worker"))) { writer.print("<tr>"); writeProcessorState(writer, objectName, mBeanServer, mode); writer.print("</tr>"); } } writer.print("</table>"); writer.print("<p>"); writer.print("P: Parse and prepare request S: Service F: Finishing R: Ready K: Keepalive"); writer.print("</p>"); } else if (mode == 1){ writer.write("<connector name='" + name + "'>"); writer.write("<threadInfo "); writer.write(" maxThreads=\"" + mBeanServer.getAttribute(tpName, "maxThreads") + "\""); writer.write(" currentThreadCount=\"" + mBeanServer.getAttribute(tpName, "currentThreadCount") + "\""); writer.write(" currentThreadsBusy=\"" + mBeanServer.getAttribute(tpName, "currentThreadsBusy") + "\""); writer.write(" />"); ObjectName grpName = null; Enumeration<ObjectName> enumeration = globalRequestProcessors.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); if (name.equals(objectName.getKeyProperty("name"))) { grpName = objectName; } } if (grpName != null) { writer.write("<requestInfo "); writer.write(" maxTime=\"" + mBeanServer.getAttribute(grpName, "maxTime") + "\""); writer.write(" processingTime=\"" + mBeanServer.getAttribute(grpName, "processingTime") + "\""); writer.write(" requestCount=\"" + mBeanServer.getAttribute(grpName, "requestCount") + "\""); writer.write(" errorCount=\"" + mBeanServer.getAttribute(grpName, "errorCount") + "\""); writer.write(" bytesReceived=\"" + mBeanServer.getAttribute(grpName, "bytesReceived") + "\""); writer.write(" bytesSent=\"" + mBeanServer.getAttribute(grpName, "bytesSent") + "\""); writer.write(" />"); writer.write("<workers>"); enumeration = requestProcessors.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); if (name.equals(objectName.getKeyProperty("worker"))) { writeProcessorState(writer, objectName, mBeanServer, mode); } } writer.write("</workers>"); } writer.write("</connector>"); } }
// in java/org/apache/catalina/manager/StatusTransformer.java
protected static void writeProcessorState(PrintWriter writer, ObjectName pName, MBeanServer mBeanServer, int mode) throws Exception { Integer stageValue = (Integer) mBeanServer.getAttribute(pName, "stage"); int stage = stageValue.intValue(); boolean fullStatus = true; boolean showRequest = true; String stageStr = null; switch (stage) { case (1/*org.apache.coyote.Constants.STAGE_PARSE*/): stageStr = "P"; fullStatus = false; break; case (2/*org.apache.coyote.Constants.STAGE_PREPARE*/): stageStr = "P"; fullStatus = false; break; case (3/*org.apache.coyote.Constants.STAGE_SERVICE*/): stageStr = "S"; break; case (4/*org.apache.coyote.Constants.STAGE_ENDINPUT*/): stageStr = "F"; break; case (5/*org.apache.coyote.Constants.STAGE_ENDOUTPUT*/): stageStr = "F"; break; case (7/*org.apache.coyote.Constants.STAGE_ENDED*/): stageStr = "R"; fullStatus = false; break; case (6/*org.apache.coyote.Constants.STAGE_KEEPALIVE*/): stageStr = "K"; fullStatus = true; showRequest = false; break; case (0/*org.apache.coyote.Constants.STAGE_NEW*/): stageStr = "R"; fullStatus = false; break; default: // Unknown stage stageStr = "?"; fullStatus = false; } if (mode == 0) { writer.write("<td><strong>"); writer.write(stageStr); writer.write("</strong></td>"); if (fullStatus) { writer.write("<td>"); writer.print(formatTime(mBeanServer.getAttribute (pName, "requestProcessingTime"), false)); writer.write("</td>"); writer.write("<td>"); if (showRequest) { writer.print(formatSize(mBeanServer.getAttribute (pName, "requestBytesSent"), false)); } else { writer.write("?"); } writer.write("</td>"); writer.write("<td>"); if (showRequest) { writer.print(formatSize(mBeanServer.getAttribute (pName, "requestBytesReceived"), false)); } else { writer.write("?"); } writer.write("</td>"); writer.write("<td>"); writer.print(filter(mBeanServer.getAttribute (pName, "remoteAddr"))); writer.write("</td>"); writer.write("<td nowrap>"); writer.write(filter(mBeanServer.getAttribute (pName, "virtualHost"))); writer.write("</td>"); writer.write("<td nowrap>"); if (showRequest) { writer.write(filter(mBeanServer.getAttribute (pName, "method"))); writer.write(" "); writer.write(filter(mBeanServer.getAttribute (pName, "currentUri"))); String queryString = (String) mBeanServer.getAttribute (pName, "currentQueryString"); if ((queryString != null) && (!queryString.equals(""))) { writer.write("?"); writer.print(RequestUtil.filter(queryString)); } writer.write(" "); writer.write(filter(mBeanServer.getAttribute (pName, "protocol"))); } else { writer.write("?"); } writer.write("</td>"); } else { writer.write("<td>?</td><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td>"); } } else if (mode == 1){ writer.write("<worker "); writer.write(" stage=\"" + stageStr + "\""); if (fullStatus) { writer.write(" requestProcessingTime=\"" + mBeanServer.getAttribute (pName, "requestProcessingTime") + "\""); writer.write(" requestBytesSent=\""); if (showRequest) { writer.write("" + mBeanServer.getAttribute (pName, "requestBytesSent")); } else { writer.write("0"); } writer.write("\""); writer.write(" requestBytesReceived=\""); if (showRequest) { writer.write("" + mBeanServer.getAttribute (pName, "requestBytesReceived")); } else { writer.write("0"); } writer.write("\""); writer.write(" remoteAddr=\"" + filter(mBeanServer.getAttribute (pName, "remoteAddr")) + "\""); writer.write(" virtualHost=\"" + filter(mBeanServer.getAttribute (pName, "virtualHost")) + "\""); if (showRequest) { writer.write(" method=\"" + filter(mBeanServer.getAttribute (pName, "method")) + "\""); writer.write(" currentUri=\"" + filter(mBeanServer.getAttribute (pName, "currentUri")) + "\""); String queryString = (String) mBeanServer.getAttribute (pName, "currentQueryString"); if ((queryString != null) && (!queryString.equals(""))) { writer.write(" currentQueryString=\"" + RequestUtil.filter(queryString) + "\""); } else { writer.write(" currentQueryString=\"&#63;\""); } writer.write(" protocol=\"" + filter(mBeanServer.getAttribute (pName, "protocol")) + "\""); } else { writer.write(" method=\"&#63;\""); writer.write(" currentUri=\"&#63;\""); writer.write(" currentQueryString=\"&#63;\""); writer.write(" protocol=\"&#63;\""); } } else { writer.write(" requestProcessingTime=\"0\""); writer.write(" requestBytesSent=\"0\""); writer.write(" requestBytesRecieved=\"0\""); writer.write(" remoteAddr=\"&#63;\""); writer.write(" virtualHost=\"&#63;\""); writer.write(" method=\"&#63;\""); writer.write(" currentUri=\"&#63;\""); writer.write(" currentQueryString=\"&#63;\""); writer.write(" protocol=\"&#63;\""); } writer.write(" />"); } }
// in java/org/apache/catalina/manager/StatusTransformer.java
public static void writeDetailedState(PrintWriter writer, MBeanServer mBeanServer, int mode) throws Exception { if (mode == 0){ ObjectName queryHosts = new ObjectName("*:j2eeType=WebModule,*"); Set<ObjectName> hostsON = mBeanServer.queryNames(queryHosts, null); // Navigation menu writer.print("<h1>"); writer.print("Application list"); writer.print("</h1>"); writer.print("<p>"); int count = 0; Iterator<ObjectName> iterator = hostsON.iterator(); while (iterator.hasNext()) { ObjectName contextON = iterator.next(); String webModuleName = contextON.getKeyProperty("name"); if (webModuleName.startsWith("//")) { webModuleName = webModuleName.substring(2); } int slash = webModuleName.indexOf("/"); if (slash == -1) { count++; continue; } writer.print("<a href=\"#" + (count++) + ".0\">"); writer.print(filter(webModuleName)); writer.print("</a>"); if (iterator.hasNext()) { writer.print("<br>"); } } writer.print("</p>"); // Webapp list count = 0; iterator = hostsON.iterator(); while (iterator.hasNext()) { ObjectName contextON = iterator.next(); writer.print("<a class=\"A.name\" name=\"" + (count++) + ".0\">"); writeContext(writer, contextON, mBeanServer, mode); } } else if (mode == 1){ // for now we don't write out the Detailed state in XML } }
// in java/org/apache/catalina/manager/StatusTransformer.java
protected static void writeContext(PrintWriter writer, ObjectName objectName, MBeanServer mBeanServer, int mode) throws Exception { if (mode == 0){ String webModuleName = objectName.getKeyProperty("name"); String name = webModuleName; if (name == null) { return; } String hostName = null; String contextName = null; if (name.startsWith("//")) { name = name.substring(2); } int slash = name.indexOf("/"); if (slash != -1) { hostName = name.substring(0, slash); contextName = name.substring(slash); } else { return; } ObjectName queryManager = new ObjectName (objectName.getDomain() + ":type=Manager,context=" + contextName + ",host=" + hostName + ",*"); Set<ObjectName> managersON = mBeanServer.queryNames(queryManager, null); ObjectName managerON = null; Iterator<ObjectName> iterator2 = managersON.iterator(); while (iterator2.hasNext()) { managerON = iterator2.next(); } ObjectName queryJspMonitor = new ObjectName (objectName.getDomain() + ":type=JspMonitor,WebModule=" + webModuleName + ",*"); Set<ObjectName> jspMonitorONs = mBeanServer.queryNames(queryJspMonitor, null); // Special case for the root context if (contextName.equals("/")) { contextName = ""; } writer.print("<h1>"); writer.print(filter(name)); writer.print("</h1>"); writer.print("</a>"); writer.print("<p>"); Object startTime = mBeanServer.getAttribute(objectName, "startTime"); writer.print(" Start time: " + new Date(((Long) startTime).longValue())); writer.print(" Startup time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "startupTime"), false)); writer.print(" TLD scan time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "tldScanTime"), false)); if (managerON != null) { writeManager(writer, managerON, mBeanServer, mode); } if (jspMonitorONs != null) { writeJspMonitor(writer, jspMonitorONs, mBeanServer, mode); } writer.print("</p>"); String onStr = objectName.getDomain() + ":j2eeType=Servlet,WebModule=" + webModuleName + ",*"; ObjectName servletObjectName = new ObjectName(onStr); Set<ObjectInstance> set = mBeanServer.queryMBeans(servletObjectName, null); Iterator<ObjectInstance> iterator = set.iterator(); while (iterator.hasNext()) { ObjectInstance oi = iterator.next(); writeWrapper(writer, oi.getObjectName(), mBeanServer, mode); } } else if (mode == 1){ // for now we don't write out the context in XML } }
// in java/org/apache/catalina/manager/StatusTransformer.java
public static void writeManager(PrintWriter writer, ObjectName objectName, MBeanServer mBeanServer, int mode) throws Exception { if (mode == 0) { writer.print("<br>"); writer.print(" Active sessions: "); writer.print(mBeanServer.getAttribute (objectName, "activeSessions")); writer.print(" Session count: "); writer.print(mBeanServer.getAttribute (objectName, "sessionCounter")); writer.print(" Max active sessions: "); writer.print(mBeanServer.getAttribute(objectName, "maxActive")); writer.print(" Rejected session creations: "); writer.print(mBeanServer.getAttribute (objectName, "rejectedSessions")); writer.print(" Expired sessions: "); writer.print(mBeanServer.getAttribute (objectName, "expiredSessions")); writer.print(" Longest session alive time: "); writer.print(formatSeconds(mBeanServer.getAttribute( objectName, "sessionMaxAliveTime"))); writer.print(" Average session alive time: "); writer.print(formatSeconds(mBeanServer.getAttribute( objectName, "sessionAverageAliveTime"))); writer.print(" Processing time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "processingTime"), false)); } else if (mode == 1) { // for now we don't write out the wrapper details } }
// in java/org/apache/catalina/manager/StatusTransformer.java
public static void writeJspMonitor(PrintWriter writer, Set<ObjectName> jspMonitorONs, MBeanServer mBeanServer, int mode) throws Exception { int jspCount = 0; int jspReloadCount = 0; Iterator<ObjectName> iter = jspMonitorONs.iterator(); while (iter.hasNext()) { ObjectName jspMonitorON = iter.next(); Object obj = mBeanServer.getAttribute(jspMonitorON, "jspCount"); jspCount += ((Integer) obj).intValue(); obj = mBeanServer.getAttribute(jspMonitorON, "jspReloadCount"); jspReloadCount += ((Integer) obj).intValue(); } if (mode == 0) { writer.print("<br>"); writer.print(" JSPs loaded: "); writer.print(jspCount); writer.print(" JSPs reloaded: "); writer.print(jspReloadCount); } else if (mode == 1) { // for now we don't write out anything } }
// in java/org/apache/catalina/manager/StatusTransformer.java
public static void writeWrapper(PrintWriter writer, ObjectName objectName, MBeanServer mBeanServer, int mode) throws Exception { if (mode == 0) { String servletName = objectName.getKeyProperty("name"); String[] mappings = (String[]) mBeanServer.invoke(objectName, "findMappings", null, null); writer.print("<h2>"); writer.print(filter(servletName)); if ((mappings != null) && (mappings.length > 0)) { writer.print(" [ "); for (int i = 0; i < mappings.length; i++) { writer.print(filter(mappings[i])); if (i < mappings.length - 1) { writer.print(" , "); } } writer.print(" ] "); } writer.print("</h2>"); writer.print("<p>"); writer.print(" Processing time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "processingTime"), true)); writer.print(" Max time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "maxTime"), false)); writer.print(" Request count: "); writer.print(mBeanServer.getAttribute(objectName, "requestCount")); writer.print(" Error count: "); writer.print(mBeanServer.getAttribute(objectName, "errorCount")); writer.print(" Load time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "loadTime"), false)); writer.print(" Classloading time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "classLoadTime"), false)); writer.print("</p>"); } else if (mode == 1){ // for now we don't write out the wrapper details } }
// in java/org/apache/catalina/manager/ManagerServlet.java
protected boolean isDeployed(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; Boolean result = (Boolean) mBeanServer.invoke(oname, "isDeployed", params, signature); return result.booleanValue(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
protected void check(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; mBeanServer.invoke(oname, "check", params, signature); }
// in java/org/apache/catalina/manager/ManagerServlet.java
protected boolean isServiced(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; Boolean result = (Boolean) mBeanServer.invoke(oname, "isServiced", params, signature); return result.booleanValue(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
protected void addServiced(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; mBeanServer.invoke(oname, "addServiced", params, signature); }
// in java/org/apache/catalina/manager/ManagerServlet.java
protected void removeServiced(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; mBeanServer.invoke(oname, "removeServiced", params, signature); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
public void listen() throws Exception { if (doListen()) { log.warn("ServerSocket already started"); return; } setListen(true); while ( doListen() ) { Socket socket = null; if ( getTaskPool().available() < 1 ) { if ( log.isWarnEnabled() ) log.warn("All BIO server replication threads are busy, unable to handle more requests until a thread is freed up."); } BioReplicationTask task = (BioReplicationTask)getTaskPool().getRxTask(); if ( task == null ) continue; //should never happen try { socket = serverSocket.accept(); }catch ( Exception x ) { if ( doListen() ) throw x; } if ( !doListen() ) { task.setDoRun(false); task.serviceSocket(null,null); getExecutor().execute(task); break; //regular shutdown } if ( socket == null ) continue; socket.setReceiveBufferSize(getRxBufSize()); socket.setSendBufferSize(getTxBufSize()); socket.setTcpNoDelay(getTcpNoDelay()); socket.setKeepAlive(getSoKeepAlive()); socket.setOOBInline(getOoBInline()); socket.setReuseAddress(getSoReuseAddress()); socket.setSoLinger(getSoLingerOn(),getSoLingerTime()); socket.setTrafficClass(getSoTrafficClass()); socket.setSoTimeout(getTimeout()); ObjectReader reader = new ObjectReader(socket); task.serviceSocket(socket,reader); getExecutor().execute(task); }//while }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
protected void execute(ObjectReader reader) throws Exception{ int pkgcnt = reader.count(); if ( pkgcnt > 0 ) { ChannelMessage[] msgs = reader.execute(); for ( int i=0; i<msgs.length; i++ ) { /** * Use send ack here if you want to ack the request to the remote * server before completing the request * This is considered an asynchronized request */ if (ChannelData.sendAckAsync(msgs[i].getOptions())) sendAck(Constants.ACK_COMMAND); try { //process the message getCallback().messageDataReceived(msgs[i]); /** * Use send ack here if you want the request to complete on this * server before sending the ack to the remote server * This is considered a synchronized request */ if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(Constants.ACK_COMMAND); }catch ( Exception x ) { if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(Constants.FAIL_ACK_COMMAND); log.error("Error thrown from messageDataReceived.",x); } if ( getUseBufferPool() ) { BufferPool.getBufferPool().returnBuffer(msgs[i].getMessage()); msgs[i].setMessage(null); } } } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
protected void drainSocket () throws Exception { InputStream in = socket.getInputStream(); // loop while data available, channel is non-blocking byte[] buf = new byte[1024]; int length = in.read(buf); while ( length >= 0 ) { int count = reader.append(buf,0,length,true); if ( count > 0 ) execute(reader); length = in.read(buf); } }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
protected void drainChannel (final SelectionKey key, ObjectReader reader) throws Exception { reader.setLastAccess(System.currentTimeMillis()); reader.access(); ReadableByteChannel channel = (ReadableByteChannel) key.channel(); int count=-1; buffer.clear(); // make buffer empty SocketAddress saddr = null; if (channel instanceof SocketChannel) { // loop while data available, channel is non-blocking while ((count = channel.read (buffer)) > 0) { buffer.flip(); // make buffer readable if ( buffer.hasArray() ) reader.append(buffer.array(),0,count,false); else reader.append(buffer,count,false); buffer.clear(); // make buffer empty //do we have at least one package? if ( reader.hasPackage() ) break; } } else if (channel instanceof DatagramChannel) { DatagramChannel dchannel = (DatagramChannel)channel; saddr = dchannel.receive(buffer); buffer.flip(); // make buffer readable if ( buffer.hasArray() ) reader.append(buffer.array(),0,buffer.limit()-buffer.position(),false); else reader.append(buffer,buffer.limit()-buffer.position(),false); buffer.clear(); // make buffer empty //did we get a package count = reader.hasPackage()?1:-1; } int pkgcnt = reader.count(); if (count < 0 && pkgcnt == 0 ) { //end of stream, and no more packages to process remoteEof(key); return; } ChannelMessage[] msgs = pkgcnt == 0? ChannelData.EMPTY_DATA_ARRAY : reader.execute(); registerForRead(key,reader);//register to read new data, before we send it off to avoid dead locks for ( int i=0; i<msgs.length; i++ ) { /** * Use send ack here if you want to ack the request to the remote * server before completing the request * This is considered an asynchronized request */ if (ChannelData.sendAckAsync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.ACK_COMMAND,saddr); try { if ( Logs.MESSAGES.isTraceEnabled() ) { try { Logs.MESSAGES.trace("NioReplicationThread - Received msg:" + new UniqueId(msgs[i].getUniqueId()) + " at " + new java.sql.Timestamp(System.currentTimeMillis())); }catch ( Throwable t ) {} } //process the message getCallback().messageDataReceived(msgs[i]); /** * Use send ack here if you want the request to complete on this * server before sending the ack to the remote server * This is considered a synchronized request */ if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.ACK_COMMAND,saddr); }catch ( RemoteProcessException e ) { if ( log.isDebugEnabled() ) log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); }catch ( Exception e ) { log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); } if ( getUseBufferPool() ) { BufferPool.getBufferPool().returnBuffer(msgs[i].getMessage()); msgs[i].setMessage(null); } } if (count < 0) { remoteEof(key); return; } }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
protected void listen() throws Exception { if (doListen()) { log.warn("ServerSocketChannel already started"); return; } setListen(true); // Avoid NPEs if selector is set to null on stop. Selector selector = this.selector; if (selector!=null && datagramChannel!=null) { ObjectReader oreader = new ObjectReader(MAX_UDP_SIZE); //max size for a datagram packet datagramChannel.socket().setSendBufferSize(getUdpTxBufSize()); datagramChannel.socket().setReceiveBufferSize(getUdpRxBufSize()); datagramChannel.socket().setReuseAddress(getSoReuseAddress()); datagramChannel.socket().setSoTimeout(getTimeout()); datagramChannel.socket().setTrafficClass(getSoTrafficClass()); registerChannel(selector,datagramChannel,SelectionKey.OP_READ,oreader); } while (doListen() && selector != null) { // this may block for a long time, upon return the // selected set contains keys of the ready channels try { events(); socketTimeouts(); int n = selector.select(getSelectorTimeout()); if (n == 0) { //there is a good chance that we got here //because the TcpReplicationThread called //selector wakeup(). //if that happens, we must ensure that that //thread has enough time to call interestOps // synchronized (interestOpsMutex) { //if we got the lock, means there are no //keys trying to register for the //interestOps method // } continue; // nothing to do } // get an iterator over the set of selected keys Iterator<SelectionKey> it = selector.selectedKeys().iterator(); // look at each key in the selected set while (it!=null && it.hasNext()) { SelectionKey key = it.next(); // Is a new connection coming in? if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel channel = server.accept(); channel.socket().setReceiveBufferSize(getRxBufSize()); channel.socket().setSendBufferSize(getTxBufSize()); channel.socket().setTcpNoDelay(getTcpNoDelay()); channel.socket().setKeepAlive(getSoKeepAlive()); channel.socket().setOOBInline(getOoBInline()); channel.socket().setReuseAddress(getSoReuseAddress()); channel.socket().setSoLinger(getSoLingerOn(),getSoLingerTime()); channel.socket().setTrafficClass(getSoTrafficClass()); channel.socket().setSoTimeout(getTimeout()); Object attach = new ObjectReader(channel); registerChannel(selector, channel, SelectionKey.OP_READ, attach); } // is there data to read on this channel? if (key.isReadable()) { readDataFromSocket(key); } else { key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE)); } // remove key from selected set, it's been handled it.remove(); } } catch (java.nio.channels.ClosedSelectorException cse) { // ignore is normal at shutdown or stop listen socket } catch (java.nio.channels.CancelledKeyException nx) { log.warn("Replication client disconnected, error when polling key. Ignoring client."); } catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } log.error("Unable to process request in NioReceiver", t); } } serverChannel.close(); if (datagramChannel!=null) { try { datagramChannel.close(); }catch (Exception iox) { if (log.isDebugEnabled()) log.debug("Unable to close datagram channel.",iox); } datagramChannel=null; } closeSelector(); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
protected void registerChannel(Selector selector, SelectableChannel channel, int ops, Object attach) throws Exception { if (channel == null)return; // could happen // set the new channel non-blocking channel.configureBlocking(false); // register it with the selector channel.register(selector, ops, attach); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
protected void readDataFromSocket(SelectionKey key) throws Exception { NioReplicationTask task = (NioReplicationTask) getTaskPool().getRxTask(); if (task == null) { // No threads/tasks available, do nothing, the selection // loop will keep calling this method until a // thread becomes available, the thread pool itself has a waiting mechanism // so we will not wait here. if (log.isDebugEnabled()) log.debug("No TcpReplicationThread available"); } else { // invoking this wakes up the worker thread then returns //add task to thread pool task.serviceChannel(key); getExecutor().execute(task); } }
// in java/org/apache/catalina/tribes/membership/McastService.java
Override public void start() throws java.lang.Exception { start(MembershipService.MBR_RX); start(MembershipService.MBR_TX); }
// in java/org/apache/catalina/tribes/membership/McastService.java
Override public void start(int level) throws java.lang.Exception { hasProperty(properties,"mcastPort"); hasProperty(properties,"mcastAddress"); hasProperty(properties,"memberDropTime"); hasProperty(properties,"mcastFrequency"); hasProperty(properties,"tcpListenPort"); hasProperty(properties,"tcpListenHost"); hasProperty(properties,"tcpSecurePort"); hasProperty(properties,"udpListenPort"); if ( impl != null ) { impl.start(level); return; } String host = getProperties().getProperty("tcpListenHost"); int port = Integer.parseInt(getProperties().getProperty("tcpListenPort")); int securePort = Integer.parseInt(getProperties().getProperty("tcpSecurePort")); int udpPort = Integer.parseInt(getProperties().getProperty("udpListenPort")); if ( localMember == null ) { localMember = new MemberImpl(host, port, 100); localMember.setUniqueId(UUIDGenerator.randomUUID(true)); } else { localMember.setHostname(host); localMember.setPort(port); localMember.setMemberAliveTime(100); } localMember.setSecurePort(securePort); localMember.setUdpPort(udpPort); if ( this.payload != null ) localMember.setPayload(payload); if ( this.domain != null ) localMember.setDomain(domain); localMember.setServiceStartTime(System.currentTimeMillis()); java.net.InetAddress bind = null; if ( properties.getProperty("mcastBindAddress")!= null ) { bind = java.net.InetAddress.getByName(properties.getProperty("mcastBindAddress")); } int ttl = -1; int soTimeout = -1; if ( properties.getProperty("mcastTTL") != null ) { try { ttl = Integer.parseInt(properties.getProperty("mcastTTL")); } catch ( Exception x ) { log.error("Unable to parse mcastTTL="+properties.getProperty("mcastTTL"),x); } } if ( properties.getProperty("mcastSoTimeout") != null ) { try { soTimeout = Integer.parseInt(properties.getProperty("mcastSoTimeout")); } catch ( Exception x ) { log.error("Unable to parse mcastSoTimeout="+properties.getProperty("mcastSoTimeout"),x); } } impl = new McastServiceImpl(localMember,Long.parseLong(properties.getProperty("mcastFrequency")), Long.parseLong(properties.getProperty("memberDropTime")), Integer.parseInt(properties.getProperty("mcastPort")), bind, java.net.InetAddress.getByName(properties.getProperty("mcastAddress")), ttl, soTimeout, this, this, Boolean.valueOf(properties.getProperty("localLoopbackDisabled","false")).booleanValue()); String value = properties.getProperty("recoveryEnabled","true"); boolean recEnabled = Boolean.valueOf(value).booleanValue() ; impl.setRecoveryEnabled(recEnabled); int recCnt = Integer.parseInt(properties.getProperty("recoveryCounter","10")); impl.setRecoveryCounter(recCnt); long recSlpTime = Long.parseLong(properties.getProperty("recoverySleepTime","5000")); impl.setRecoverySleepTime(recSlpTime); impl.start(level); }
// in java/org/apache/catalina/tribes/membership/McastService.java
public static void main(String args[]) throws Exception { if(log.isInfoEnabled()) log.info("Usage McastService hostname tcpport"); McastService service = new McastService(); java.util.Properties p = new java.util.Properties(); p.setProperty("mcastPort","5555"); p.setProperty("mcastAddress","224.10.10.10"); p.setProperty("mcastClusterDomain","catalina"); p.setProperty("bindAddress","localhost"); p.setProperty("memberDropTime","3000"); p.setProperty("mcastFrequency","500"); p.setProperty("tcpListenPort","4000"); p.setProperty("tcpListenHost","127.0.0.1"); service.setProperties(p); service.start(); Thread.sleep(60*1000*60); }
// in java/org/apache/catalina/tribes/membership/Constants.java
public static void main(String[] args) throws Exception { System.out.println(Arrays.toString("TRIBES-B".getBytes())); System.out.println(Arrays.toString("TRIBES-E".getBytes())); }
// in java/org/apache/catalina/session/StandardManager.java
Override public Void run() throws Exception{ doLoad(); return null; }
// in java/org/apache/catalina/session/StandardManager.java
Override public Void run() throws Exception{ doUnload(); return null; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override public Void run() throws Exception{ store.clear(); return null; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override public Void run() throws Exception{ store.remove(id); return null; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override public Session run() throws Exception{ return store.load(id); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override public Void run() throws Exception{ store.save(session); return null; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override public String[] run() throws Exception{ return store.keys(); }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
public static MBeanServer getMBeanServer() throws Exception { if (mbeanServer == null) { if (MBeanServerFactory.findMBeanServer(null).size() > 0) { mbeanServer = MBeanServerFactory.findMBeanServer(null).get(0); } else { mbeanServer = MBeanServerFactory.createMBeanServer(); } } return mbeanServer; }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
public static DynamicMBean getManagedBean(Object object) throws Exception { DynamicMBean mbean = null; if (getRegistry() != null) { ManagedBean managedBean = registry.findManagedBean(object.getClass().getName()); mbean = managedBean.createMBean(object); } return mbean; }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
private static ObjectName getDefaultClusterName(SimpleTcpCluster cluster) throws Exception { String domain = getMBeanServer().getDefaultDomain(); String type = ":type="; String clusterType= type+"Cluster"; if (cluster.getContainer() instanceof StandardHost) { domain = ((StandardHost) cluster.getContainer()).getDomain(); clusterType += ",host=" + cluster.getContainer().getName(); } else { if (cluster.getContainer() instanceof StandardEngine) { domain = ((StandardEngine) cluster.getContainer()).getDomain(); } } ObjectName clusterName = new ObjectName(domain + clusterType); return clusterName; }
// in java/org/apache/catalina/ha/backend/TcpSender.java
Override public void init(HeartbeatListener config) throws Exception { this.config = config; StringTokenizer tok = new StringTokenizer(config.getProxyList(), ","); proxies = new Proxy[tok.countTokens()]; int i = 0; while (tok.hasMoreTokens()) { String token = tok.nextToken().trim(); int pos = token.indexOf(':'); if (pos <=0) throw new Exception("bad ProxyList"); proxies[i] = new Proxy(); proxies[i].port = Integer.parseInt(token.substring(pos + 1)); try { proxies[i].address = InetAddress.getByName(token.substring(0, pos)); } catch (Exception e) { throw new Exception("bad ProxyList"); } i++; } connections = new Socket[proxies.length]; connectionReaders = new BufferedReader[proxies.length]; connectionWriters = new BufferedWriter[proxies.length]; }
// in java/org/apache/catalina/ha/backend/TcpSender.java
Override public int send(String mess) throws Exception { if (connections == null) { log.error("Not initialized"); return -1; } String requestLine = "POST " + config.getProxyURL() + " HTTP/1.0"; for (int i = 0; i < connections.length; i++) { if (connections[i] == null) { try { if (config.host != null) { connections[i] = new Socket(); InetAddress addr = InetAddress.getByName(config.host); InetSocketAddress addrs = new InetSocketAddress(addr, 0); connections[i].setReuseAddress(true); connections[i].bind(addrs); addrs = new InetSocketAddress(proxies[i].address, proxies[i].port); connections[i].connect(addrs); } else connections[i] = new Socket(proxies[i].address, proxies[i].port); connectionReaders[i] = new BufferedReader(new InputStreamReader(connections[i].getInputStream())); connectionWriters[i] = new BufferedWriter(new OutputStreamWriter(connections[i].getOutputStream())); } catch (Exception ex) { log.error("Unable to connect to proxy: " + ex); close(i); } } if (connections[i] == null) continue; // try next proxy in the list BufferedWriter writer = connectionWriters[i]; try { writer.write(requestLine); writer.write("\r\n"); writer.write("Content-Length: " + mess.length() + "\r\n"); writer.write("User-Agent: HeartbeatListener/1.0\r\n"); writer.write("Connection: Keep-Alive\r\n"); writer.write("\r\n"); writer.write(mess); writer.write("\r\n"); writer.flush(); } catch (Exception ex) { log.error("Unable to send collected load information to proxy: " + ex); close(i); } if (connections[i] == null) continue; // try next proxy in the list /* Read httpd answer */ String responseStatus = connectionReaders[i].readLine(); if (responseStatus == null) { log.error("Unable to read response from proxy"); close(i); continue; } else { responseStatus = responseStatus.substring(responseStatus.indexOf(' ') + 1, responseStatus.indexOf(' ', responseStatus.indexOf(' ') + 1)); int status = Integer.parseInt(responseStatus); if (status != 200) { log.error("Status is " + status); close(i); continue; } // read all the headers. String header = connectionReaders[i].readLine(); int contentLength = 0; while (!"".equals(header)) { int colon = header.indexOf(':'); String headerName = header.substring(0, colon).trim(); String headerValue = header.substring(colon + 1).trim(); if ("content-length".equalsIgnoreCase(headerName)) { contentLength = Integer.parseInt(headerValue); } header = connectionReaders[i].readLine(); } if (contentLength > 0) { char[] buf = new char[512]; while (contentLength > 0) { int thisTime = (contentLength > buf.length) ? buf.length : contentLength; int n = connectionReaders[i].read(buf, 0, thisTime); if (n <= 0) { log.error("Read content failed"); close(i); break; } else { contentLength -= n; } } } } } return 0; }
// in java/org/apache/catalina/ha/backend/CollectedInfo.java
public void init(String host, int port) throws Exception { int iport = 0; String shost = null; mBeanServer = Registry.getRegistry(null, null).getMBeanServer(); String onStr = "*:type=ThreadPool,*"; ObjectName objectName = new ObjectName(onStr); Set<ObjectInstance> set = mBeanServer.queryMBeans(objectName, null); Iterator<ObjectInstance> iterator = set.iterator(); while (iterator.hasNext()) { ObjectInstance oi = iterator.next(); objName = oi.getObjectName(); String name = objName.getKeyProperty("name"); /* Name are: * http-8080 * jk-10.33.144.3-8009 * jk-jfcpc%2F10.33.144.3-8009 */ String [] elenames = name.split("-"); String sport = elenames[elenames.length-1]; iport = Integer.parseInt(sport); String [] shosts = elenames[1].split("%2F"); shost = shosts[0]; if (port==0 && host==null) break; /* Take the first one */ if (host==null && iport==port) break; /* Only port done */ if (shost.compareTo(host) == 0) break; /* Done port and host are the expected ones */ } if (objName == null) throw(new Exception("Can't find connector for " + host + ":" + port)); this.port = iport; this.host = shost; }
// in java/org/apache/catalina/ha/backend/CollectedInfo.java
public void refresh() throws Exception { if (mBeanServer == null || objName == null) { throw(new Exception("Not initialized!!!")); } Integer imax = (Integer) mBeanServer.getAttribute(objName, "maxThreads"); // the currentThreadCount could be 0 before the threads are created... // Integer iready = (Integer) mBeanServer.getAttribute(objName, "currentThreadCount"); Integer ibusy = (Integer) mBeanServer.getAttribute(objName, "currentThreadsBusy"); busy = ibusy.intValue(); ready = imax.intValue() - ibusy.intValue(); }
// in java/org/apache/catalina/ha/backend/MultiCastSender.java
Override public void init(HeartbeatListener config) throws Exception { this.config = config; }
// in java/org/apache/catalina/ha/backend/MultiCastSender.java
Override public int send(String mess) throws Exception { if (s == null) { try { group = InetAddress.getByName(config.getGroup()); if (config.host != null) { InetAddress addr = InetAddress.getByName(config.host); InetSocketAddress addrs = new InetSocketAddress(addr, config.getMultiport()); s = new MulticastSocket(addrs); } else s = new MulticastSocket(config.getMultiport()); s.setTimeToLive(config.getTtl()); s.joinGroup(group); } catch (Exception ex) { log.error("Unable to use multicast: " + ex); s = null; return -1; } } byte[] buf; buf = mess.getBytes(US_ASCII); DatagramPacket data = new DatagramPacket(buf, buf.length, group, config.getMultiport()); try { s.send(data); } catch (Exception ex) { log.error("Unable to send colllected load information: " + ex); s.close(); s = null; return -1; } return 0; }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public static void main(String[] args) throws Exception { System.out .println("Usage: FileMessageFactory fileToBeRead fileToBeWritten"); System.out .println("Usage: This will make a copy of the file on the local file system"); FileMessageFactory read = getInstance(new File(args[0]), false); FileMessageFactory write = getInstance(new File(args[1]), true); FileMessage msg = new FileMessage(null, args[0], args[0]); msg = read.readMessage(msg); System.out.println("Expecting to write " + msg.getTotalNrOfMsgs() + " messages."); int cnt = 0; while (msg != null) { write.writeMessage(msg); cnt++; msg = read.readMessage(msg); }//while System.out.println("Actually wrote " + cnt + " messages."); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
Override public void start() throws Exception { if (started) return; Container hcontainer = getCluster().getContainer(); if(!(hcontainer instanceof Host)) { log.error(sm.getString("farmWarDeployer.hostOnly")); return ; } host = (Host) hcontainer; // Check to correct engine and host setup Container econtainer = host.getParent(); if(!(econtainer instanceof Engine)) { log.error(sm.getString("farmWarDeployer.hostParentEngine", host.getName())); return ; } Engine engine = (Engine) econtainer; String hostname = null; hostname = host.getName(); try { oname = new ObjectName(engine.getName() + ":type=Deployer,host=" + hostname); } catch (Exception e) { log.error(sm.getString("farmWarDeployer.mbeanNameFail", engine.getName(), hostname),e); return; } if (watchEnabled) { watcher = new WarWatcher(this, new File(getWatchDir())); if (log.isInfoEnabled()) { log.info(sm.getString( "farmWarDeployer.watchDir", getWatchDir())); } } configBase = new File(engine.getCatalinaBase(), "conf"); configBase = new File(configBase, engine.getName()); configBase = new File(configBase, hostname); // Retrieve the MBean server mBeanServer = Registry.getRegistry(null, null).getMBeanServer(); started = true; count = 0; getCluster().addClusterListener(this); if (log.isInfoEnabled()) log.info(sm.getString("farmWarDeployer.started")); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
protected void remove(String contextName) throws Exception { // TODO Handle remove also work dir content ! // Stop the context first to be nicer Context context = (Context) host.findChild(contextName); if (context != null) { if(log.isDebugEnabled()) log.debug(sm.getString("farmWarDeployer.undeployLocal", contextName)); context.stop(); String baseName = context.getBaseName(); File war = new File(host.getAppBaseFile(), baseName + ".war"); File dir = new File(host.getAppBaseFile(), baseName); File xml = new File(configBase, baseName + ".xml"); if (war.exists()) { if (!war.delete()) { log.error(sm.getString("farmWarDeployer.deleteFail", war)); } } else if (dir.exists()) { undeployDir(dir); } else { if (!xml.delete()) { log.error(sm.getString("farmWarDeployer.deleteFail", xml)); } } // Perform new deployment and remove internal HostConfig state check(contextName); } }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
protected void check(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; mBeanServer.invoke(oname, "check", params, signature); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
protected boolean isServiced(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; Boolean result = (Boolean) mBeanServer.invoke(oname, "isServiced", params, signature); return result.booleanValue(); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
protected void addServiced(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; mBeanServer.invoke(oname, "addServiced", params, signature); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
protected void removeServiced(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; mBeanServer.invoke(oname, "removeServiced", params, signature); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
protected void registerClusterValve() throws Exception { if(container != null ) { for (Iterator<Valve> iter = valves.iterator(); iter.hasNext();) { ClusterValve valve = (ClusterValve) iter.next(); if (log.isDebugEnabled()) log.debug("Invoking addValve on " + getContainer() + " with class=" + valve.getClass().getName()); if (valve != null) { IntrospectionUtils.callMethodN(getContainer(), "addValve", new Object[] { valve }, new Class[] { org.apache.catalina.Valve.class }); valve.setCluster(this); } } } }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
protected void unregisterClusterValve() throws Exception { for (Iterator<Valve> iter = valves.iterator(); iter.hasNext();) { ClusterValve valve = (ClusterValve) iter.next(); if (log.isDebugEnabled()) log.debug("Invoking removeValve on " + getContainer() + " with class=" + valve.getClass().getName()); if (valve != null) { IntrospectionUtils.callMethodN(getContainer(), "removeValve", new Object[] { valve }, new Class[] { org.apache.catalina.Valve.class }); valve.setCluster(this); } } }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
Override public boolean asyncDispatch(org.apache.coyote.Request req, org.apache.coyote.Response res, SocketStatus status) throws Exception { Request request = (Request) req.getNote(ADAPTER_NOTES); Response response = (Response) res.getNote(ADAPTER_NOTES); if (request == null) { throw new IllegalStateException( "Dispatch may only happen on an existing request."); } boolean comet = false; boolean success = true; AsyncContextImpl asyncConImpl = (AsyncContextImpl)request.getAsyncContext(); req.getRequestProcessor().setWorkerThreadName(Thread.currentThread().getName()); try { if (!request.isAsync() && !comet) { // Error or timeout - need to tell listeners the request is over // Have to test this first since state may change while in this // method and this is only required if entering this method in // this state Context ctxt = (Context) request.getMappingData().context; if (ctxt != null) { ctxt.fireRequestDestroyEvent(request); } // Lift any suspension (e.g. if sendError() was used by an async // request) to allow the response to be written to the client response.setSuspended(false); } if (status==SocketStatus.TIMEOUT) { success = true; if (!asyncConImpl.timeout()) { asyncConImpl.setErrorState(null); } } if (request.isAsyncDispatching()) { success = true; connector.getService().getContainer().getPipeline().getFirst().invoke(request, response); Throwable t = (Throwable) request.getAttribute( RequestDispatcher.ERROR_EXCEPTION); if (t != null) { asyncConImpl.setErrorState(t); } } if (request.isComet()) { if (!response.isClosed() && !response.isError()) { if (request.getAvailable() || (request.getContentLength() > 0 && (!request.isParametersParsed()))) { // Invoke a read event right away if there are available bytes if (event(req, res, SocketStatus.OPEN)) { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { // Clear the filter chain, as otherwise it will not be reset elsewhere // since this is a Comet request request.setFilterChain(null); } } if (!request.isAsync() && !comet) { request.finishRequest(); response.finishResponse(); req.action(ActionCode.POST_REQUEST , null); ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); } } catch (IOException e) { success = false; // Ignore } catch (Throwable t) { ExceptionUtils.handleThrowable(t); success = false; log.error(sm.getString("coyoteAdapter.service"), t); } finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!success || (!comet && !request.isAsync())) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } } return success; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
Override public void service(org.apache.coyote.Request req, org.apache.coyote.Response res) throws Exception { Request request = (Request) req.getNote(ADAPTER_NOTES); Response response = (Response) res.getNote(ADAPTER_NOTES); if (request == null) { // Create objects request = connector.createRequest(); request.setCoyoteRequest(req); response = connector.createResponse(); response.setCoyoteResponse(res); // Link objects request.setResponse(response); response.setRequest(request); // Set as notes req.setNote(ADAPTER_NOTES, request); res.setNote(ADAPTER_NOTES, response); // Set query string encoding req.getParameters().setQueryStringEncoding (connector.getURIEncoding()); } if (connector.getXpoweredBy()) { response.addHeader("X-Powered-By", POWERED_BY); } boolean comet = false; boolean async = false; try { // Parse and set Catalina and configuration specific // request parameters req.getRequestProcessor().setWorkerThreadName(Thread.currentThread().getName()); boolean postParseSuccess = postParseRequest(req, request, res, response); if (postParseSuccess) { //check valves if we support async request.setAsyncSupported(connector.getService().getContainer().getPipeline().isAsyncSupported()); // Calling the container connector.getService().getContainer().getPipeline().getFirst().invoke(request, response); if (request.isComet()) { if (!response.isClosed() && !response.isError()) { if (request.getAvailable() || (request.getContentLength() > 0 && (!request.isParametersParsed()))) { // Invoke a read event right away if there are available bytes if (event(req, res, SocketStatus.OPEN)) { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { // Clear the filter chain, as otherwise it will not be reset elsewhere // since this is a Comet request request.setFilterChain(null); } } } AsyncContextImpl asyncConImpl = (AsyncContextImpl)request.getAsyncContext(); if (asyncConImpl != null) { async = true; } else if (!comet) { request.finishRequest(); response.finishResponse(); if (postParseSuccess && request.getMappingData().context != null) { // Log only if processing was invoked. // If postParseRequest() failed, it has already logged it. // If context is null this was the start of a comet request // that failed and has already been logged. ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); } req.action(ActionCode.POST_REQUEST , null); } } catch (IOException e) { // Ignore } finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!comet && !async) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } } }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
protected boolean postParseRequest(org.apache.coyote.Request req, Request request, org.apache.coyote.Response res, Response response) throws Exception { // XXX the processor may have set a correct scheme and port prior to this point, // in ajp13 protocols dont make sense to get the port from the connector... // otherwise, use connector configuration if (! req.scheme().isNull()) { // use processor specified scheme to determine secure state request.setSecure(req.scheme().equals("https")); } else { // use connector scheme and secure configuration, (defaults to // "http" and false respectively) req.scheme().setString(connector.getScheme()); request.setSecure(connector.getSecure()); } // FIXME: the code below doesnt belongs to here, // this is only have sense // in Http11, not in ajp13.. // At this point the Host header has been processed. // Override if the proxyPort/proxyHost are set String proxyName = connector.getProxyName(); int proxyPort = connector.getProxyPort(); if (proxyPort != 0) { req.setServerPort(proxyPort); } if (proxyName != null) { req.serverName().setString(proxyName); } // Copy the raw URI to the decodedURI MessageBytes decodedURI = req.decodedURI(); decodedURI.duplicate(req.requestURI()); // Parse the path parameters. This will: // - strip out the path parameters // - convert the decodedURI to bytes parsePathParameters(req, request); // URI decoding // %xx decoding of the URL try { req.getURLDecoder().convert(decodedURI, false); } catch (IOException ioe) { res.setStatus(400); res.setMessage("Invalid URI: " + ioe.getMessage()); connector.getService().getContainer().logAccess( request, response, 0, true); return false; } // Normalization if (!normalize(req.decodedURI())) { res.setStatus(400); res.setMessage("Invalid URI"); connector.getService().getContainer().logAccess( request, response, 0, true); return false; } // Character decoding convertURI(decodedURI, request); // Check that the URI is still normalized if (!checkNormalize(req.decodedURI())) { res.setStatus(400); res.setMessage("Invalid URI character encoding"); connector.getService().getContainer().logAccess( request, response, 0, true); return false; } // Set the remote principal String principal = req.getRemoteUser().toString(); if (principal != null) { request.setUserPrincipal(new CoyotePrincipal(principal)); } // Set the authorization type String authtype = req.getAuthType().toString(); if (authtype != null) { request.setAuthType(authtype); } // Request mapping. MessageBytes serverName; if (connector.getUseIPVHosts()) { serverName = req.localName(); if (serverName.isNull()) { // well, they did ask for it res.action(ActionCode.REQ_LOCAL_NAME_ATTRIBUTE, null); } } else { serverName = req.serverName(); } if (request.isAsyncStarted()) { //TODO SERVLET3 - async //reset mapping data, should prolly be done elsewhere request.getMappingData().recycle(); } boolean mapRequired = true; String version = null; while (mapRequired) { if (version != null) { // Once we have a version - that is it mapRequired = false; } // This will map the the latest version by default connector.getMapper().map(serverName, decodedURI, version, request.getMappingData()); request.setContext((Context) request.getMappingData().context); request.setWrapper((Wrapper) request.getMappingData().wrapper); // Single contextVersion therefore no possibility of remap if (request.getMappingData().contexts == null) { mapRequired = false; } // If there is no context at this point, it is likely no ROOT context // has been deployed if (request.getContext() == null) { res.setStatus(404); res.setMessage("Not found"); // No context, so use host Host host = request.getHost(); // Make sure there is a host (might not be during shutdown) if (host != null) { host.logAccess(request, response, 0, true); } return false; } // Now we have the context, we can parse the session ID from the URL // (if any). Need to do this before we redirect in case we need to // include the session id in the redirect String sessionID = null; if (request.getServletContext().getEffectiveSessionTrackingModes() .contains(SessionTrackingMode.URL)) { // Get the session ID if there was one sessionID = request.getPathParameter( SessionConfig.getSessionUriParamName( request.getContext())); if (sessionID != null) { request.setRequestedSessionId(sessionID); request.setRequestedSessionURL(true); } } // Look for session ID in cookies and SSL session parseSessionCookiesId(req, request); parseSessionSslId(request); sessionID = request.getRequestedSessionId(); if (mapRequired) { if (sessionID == null) { // No session means no possibility of needing to remap mapRequired = false; } else { // Find the context associated with the session Object[] objs = request.getMappingData().contexts; for (int i = (objs.length); i > 0; i--) { Context ctxt = (Context) objs[i - 1]; if (ctxt.getManager().findSession(sessionID) != null) { // Was the correct context already mapped? if (ctxt.equals(request.getMappingData().context)) { mapRequired = false; } else { // Set version so second time through mapping the // correct context is found version = ctxt.getWebappVersion(); // Reset mapping request.getMappingData().recycle(); break; } } } if (version == null) { // No matching context found. No need to re-map mapRequired = false; } } } if (!mapRequired && request.getContext().getPaused()) { // Found a matching context but it is paused. Mapping data will // be wrong since some Wrappers may not be registered at this // point. try { Thread.sleep(1000); } catch (InterruptedException e) { // Should never happen } // Reset mapping request.getMappingData().recycle(); mapRequired = true; } } // Possible redirect MessageBytes redirectPathMB = request.getMappingData().redirectPath; if (!redirectPathMB.isNull()) { String redirectPath = urlEncoder.encode(redirectPathMB.toString()); String query = request.getQueryString(); if (request.isRequestedSessionIdFromURL()) { // This is not optimal, but as this is not very common, it // shouldn't matter redirectPath = redirectPath + ";" + SessionConfig.getSessionUriParamName( request.getContext()) + "=" + request.getRequestedSessionId(); } if (query != null) { // This is not optimal, but as this is not very common, it // shouldn't matter redirectPath = redirectPath + "?" + query; } response.sendRedirect(redirectPath); request.getContext().logAccess(request, response, 0, true); return false; } // Filter trace method if (!connector.getAllowTrace() && req.method().equalsIgnoreCase("TRACE")) { Wrapper wrapper = request.getWrapper(); String header = null; if (wrapper != null) { String[] methods = wrapper.getServletMethods(); if (methods != null) { for (int i=0; i<methods.length; i++) { if ("TRACE".equals(methods[i])) { continue; } if (header == null) { header = methods[i]; } else { header += ", " + methods[i]; } } } } res.setStatus(405); res.addHeader("Allow", header); res.setMessage("TRACE method is not allowed"); request.getContext().logAccess(request, response, 0, true); return false; } return true; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
protected void convertURI(MessageBytes uri, Request request) throws Exception { ByteChunk bc = uri.getByteChunk(); int length = bc.getLength(); CharChunk cc = uri.getCharChunk(); cc.allocate(length, -1); String enc = connector.getURIEncoding(); if (enc != null) { B2CConverter conv = request.getURIConverter(); try { if (conv == null) { conv = new B2CConverter(enc); request.setURIConverter(conv); } } catch (IOException e) { // Ignore log.error("Invalid URI encoding; using HTTP default"); connector.setURIEncoding(null); } if (conv != null) { try { conv.convert(bc, cc, cc.getBuffer().length - cc.getEnd()); uri.setChars(cc.getBuffer(), cc.getStart(), cc.getLength()); return; } catch (IOException e) { log.error("Invalid URI character encoding; trying ascii"); cc.recycle(); } } } // Default encoding: fast conversion byte[] bbuf = bc.getBuffer(); char[] cbuf = cc.getBuffer(); int start = bc.getStart(); for (int i = 0; i < length; i++) { cbuf[i] = (char) (bbuf[i + start] & 0xff); } uri.setChars(cbuf, 0, length); }
// in java/org/apache/catalina/core/StandardHost.java
public String [] getValveNames() throws Exception { Valve [] valves = this.getPipeline().getValves(); String [] mbeanNames = new String[valves.length]; for (int i = 0; i < valves.length; i++) { if (valves[i] instanceof JmxEnabled) { ObjectName oname = ((JmxEnabled) valves[i]).getObjectName(); if (oname != null) { mbeanNames[i] = oname.toString(); } } } return mbeanNames; }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected Class<?> loadClassMaybePrivileged(final String className, final ClassLoader classLoader) throws ClassNotFoundException { Class<?> clazz; if (SecurityUtil.isPackageProtectionEnabled()) { try { clazz = AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() { @Override public Class<?> run() throws Exception { return loadClass(className, classLoader); } }); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Class<?> run() throws Exception { return loadClass(className, classLoader); }
// in java/org/apache/catalina/core/StandardServer.java
public synchronized void storeConfig() throws Exception { ObjectName sname = new ObjectName("Catalina:type=StoreConfig"); mserver.invoke(sname, "storeConfig", null, null); }
// in java/org/apache/catalina/core/StandardServer.java
public synchronized void storeContext(Context context) throws Exception { ObjectName sname = null; try { sname = new ObjectName("Catalina:type=StoreConfig"); if(mserver.isRegistered(sname)) { mserver.invoke(sname, "store", new Object[] {context}, new String [] { "java.lang.String"}); } else log.error("StoreConfig mbean not registered" + sname); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(t); } }
// in java/org/apache/catalina/core/StandardContext.java
private void resetContext() throws Exception { // Restore the original state ( pre reading web.xml in start ) // If you extend this - override this method and make sure to clean up // Don't reset anything that is read from a <Context.../> element since // <Context .../> elements are read at initialisation will not be read // again for this object for (Container child : findChildren()) { removeChild(child); } startupTime = 0; startTime = 0; tldScanTime = 0; // Bugzilla 32867 distributable = false; applicationListeners = new String[0]; applicationEventListenersObjects = new Object[0]; applicationLifecycleListenersObjects = new Object[0]; jspConfigDescriptor = new ApplicationJspConfigDescriptor(); initializers.clear(); createdServlets.clear(); if(log.isDebugEnabled()) log.debug("resetContext " + getObjectName()); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
Override public Void run() throws java.lang.Exception { doForward(request,response); return null; }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
Override public final void preDeregister() throws Exception { // NOOP }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
Override public final ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { this.mserver = server; this.oname = name; this.domain = name.getDomain(); return oname; }
// in java/org/apache/catalina/security/SecurityUtil.java
public static void doAsPrivilege(final String methodName, final Servlet targetObject) throws java.lang.Exception{ doAsPrivilege(methodName, targetObject, null, null, null); }
// in java/org/apache/catalina/security/SecurityUtil.java
public static void doAsPrivilege(final String methodName, final Servlet targetObject, final Class<?>[] targetType, final Object[] targetArguments) throws java.lang.Exception{ doAsPrivilege(methodName, targetObject, targetType, targetArguments, null); }
// in java/org/apache/catalina/security/SecurityUtil.java
public static void doAsPrivilege(final String methodName, final Servlet targetObject, final Class<?>[] targetType, final Object[] targetArguments, Principal principal) throws java.lang.Exception{ Method method = null; Method[] methodsCache = objectCache.get(targetObject); if(methodsCache == null) { method = createMethodAndCacheIt(methodsCache, methodName, targetObject, targetType); } else { method = findMethod(methodsCache, methodName); if (method == null) { method = createMethodAndCacheIt(methodsCache, methodName, targetObject, targetType); } } execute(method, targetObject, targetArguments, principal); }
// in java/org/apache/catalina/security/SecurityUtil.java
public static void doAsPrivilege(final String methodName, final Filter targetObject) throws java.lang.Exception{ doAsPrivilege(methodName, targetObject, null, null); }
// in java/org/apache/catalina/security/SecurityUtil.java
public static void doAsPrivilege(final String methodName, final Filter targetObject, final Class<?>[] targetType, final Object[] targetArguments) throws java.lang.Exception{ doAsPrivilege( methodName, targetObject, targetType, targetArguments, null); }
// in java/org/apache/catalina/security/SecurityUtil.java
public static void doAsPrivilege(final String methodName, final Filter targetObject, final Class<?>[] targetType, final Object[] targetArguments, Principal principal) throws java.lang.Exception{ Method method = null; Method[] methodsCache = objectCache.get(targetObject); if(methodsCache == null) { method = createMethodAndCacheIt(methodsCache, methodName, targetObject, targetType); } else { method = findMethod(methodsCache, methodName); if (method == null) { method = createMethodAndCacheIt(methodsCache, methodName, targetObject, targetType); } } execute(method, targetObject, targetArguments, principal); }
// in java/org/apache/catalina/security/SecurityUtil.java
private static void execute(final Method method, final Object targetObject, final Object[] targetArguments, Principal principal) throws java.lang.Exception{ try{ Subject subject = null; PrivilegedExceptionAction<Void> pea = new PrivilegedExceptionAction<Void>(){ @Override public Void run() throws Exception{ method.invoke(targetObject, targetArguments); return null; } }; // The first argument is always the request object if (targetArguments != null && targetArguments[0] instanceof HttpServletRequest){ HttpServletRequest request = (HttpServletRequest)targetArguments[0]; boolean hasSubject = false; HttpSession session = request.getSession(false); if (session != null){ subject = (Subject)session.getAttribute(Globals.SUBJECT_ATTR); hasSubject = (subject != null); } if (subject == null){ subject = new Subject(); if (principal != null){ subject.getPrincipals().add(principal); } } if (session != null && !hasSubject) { session.setAttribute(Globals.SUBJECT_ATTR, subject); } } Subject.doAsPrivileged(subject, pea, null); } catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/org/apache/catalina/security/SecurityUtil.java
Override public Void run() throws Exception{ method.invoke(targetObject, targetArguments); return null; }
// in java/org/apache/catalina/security/SecurityUtil.java
private static Method createMethodAndCacheIt(Method[] methodsCache, String methodName, Object targetObject, Class<?>[] targetType) throws Exception{ if ( methodsCache == null){ methodsCache = new Method[4]; } Method method = targetObject.getClass().getMethod(methodName, targetType); if (methodName.equalsIgnoreCase(INIT_METHOD)){ methodsCache[INIT] = method; } else if (methodName.equalsIgnoreCase(DESTROY_METHOD)){ methodsCache[DESTROY] = method; } else if (methodName.equalsIgnoreCase(SERVICE_METHOD)){ methodsCache[SERVICE] = method; } else if (methodName.equalsIgnoreCase(DOFILTER_METHOD)){ methodsCache[DOFILTER] = method; } else if (methodName.equalsIgnoreCase(EVENT_METHOD)){ methodsCache[EVENT] = method; } else if (methodName.equalsIgnoreCase(DOFILTEREVENT_METHOD)){ methodsCache[DOFILTEREVENT] = method; } objectCache.put(targetObject, methodsCache ); return method; }
// in java/org/apache/catalina/security/SecurityClassLoad.java
public static void securityClassLoad(ClassLoader loader) throws Exception { if( System.getSecurityManager() == null ){ return; } loadCorePackage(loader); loadCoyotePackage(loader); loadLoaderPackage(loader); loadRealmPackage(loader); loadSessionPackage(loader); loadUtilPackage(loader); loadJavaxPackage(loader); loadConnectorPackage(loader); loadTomcatPackage(loader); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadCorePackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.catalina.core."; loader.loadClass (basePackage + "ApplicationContextFacade$1"); loader.loadClass (basePackage + "ApplicationDispatcher$PrivilegedForward"); loader.loadClass (basePackage + "ApplicationDispatcher$PrivilegedInclude"); loader.loadClass (basePackage + "AsyncContextImpl"); loader.loadClass (basePackage + "AsyncContextImpl$DebugException"); loader.loadClass (basePackage + "AsyncContextImpl$1"); loader.loadClass (basePackage + "AsyncListenerWrapper"); loader.loadClass (basePackage + "ContainerBase$PrivilegedAddChild"); loader.loadClass (basePackage + "DefaultInstanceManager$1"); loader.loadClass (basePackage + "DefaultInstanceManager$2"); loader.loadClass (basePackage + "DefaultInstanceManager$3"); loader.loadClass (basePackage + "DefaultInstanceManager$AnnotationCacheEntry"); loader.loadClass (basePackage + "DefaultInstanceManager$AnnotationCacheEntryType"); loader.loadClass (basePackage + "ApplicationHttpRequest$AttributeNamesEnumerator"); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadLoaderPackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.catalina.loader."; loader.loadClass (basePackage + "WebappClassLoader$PrivilegedFindResourceByName"); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadRealmPackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.catalina.realm."; loader.loadClass (basePackage + "LockOutRealm$LockRecord"); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadSessionPackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.catalina.session."; loader.loadClass (basePackage + "StandardSession"); loader.loadClass (basePackage + "StandardSession$PrivilegedSetTccl"); loader.loadClass (basePackage + "StandardSession$1"); loader.loadClass (basePackage + "StandardManager$PrivilegedDoUnload"); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadUtilPackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.catalina.util."; loader.loadClass(basePackage + "ParameterMap"); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadCoyotePackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.coyote."; loader.loadClass(basePackage + "http11.AbstractOutputBuffer$1"); loader.loadClass(basePackage + "http11.Constants"); // Make sure system property is read at this point Class<?> clazz = loader.loadClass(basePackage + "Constants"); clazz.newInstance(); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadJavaxPackage(ClassLoader loader) throws Exception { loader.loadClass("javax.servlet.http.Cookie"); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadConnectorPackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.catalina.connector."; loader.loadClass (basePackage + "RequestFacade$GetAttributePrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetParameterMapPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetRequestDispatcherPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetParameterPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetParameterNamesPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetParameterValuePrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetCharacterEncodingPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetHeadersPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetHeaderNamesPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetCookiesPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetLocalePrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetLocalesPrivilegedAction"); loader.loadClass (basePackage + "ResponseFacade$SetContentTypePrivilegedAction"); loader.loadClass (basePackage + "ResponseFacade$DateHeaderPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetSessionPrivilegedAction"); loader.loadClass (basePackage + "ResponseFacade$1"); loader.loadClass (basePackage + "OutputBuffer$1"); loader.loadClass (basePackage + "CoyoteInputStream$1"); loader.loadClass (basePackage + "CoyoteInputStream$2"); loader.loadClass (basePackage + "CoyoteInputStream$3"); loader.loadClass (basePackage + "CoyoteInputStream$4"); loader.loadClass (basePackage + "CoyoteInputStream$5"); loader.loadClass (basePackage + "InputBuffer$1"); loader.loadClass (basePackage + "Response$1"); loader.loadClass (basePackage + "Response$2"); loader.loadClass (basePackage + "Response$3"); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadTomcatPackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.tomcat."; loader.loadClass(basePackage + "util.buf.HexUtils"); loader.loadClass(basePackage + "util.buf.StringCache"); loader.loadClass(basePackage + "util.buf.StringCache$ByteEntry"); loader.loadClass(basePackage + "util.buf.StringCache$CharEntry"); loader.loadClass(basePackage + "util.http.HttpMessages"); // Make sure system property is read at this point Class<?> clazz = loader.loadClass( basePackage + "util.http.FastHttpDateFormat"); clazz.newInstance(); loader.loadClass(basePackage + "util.http.HttpMessages"); loader.loadClass(basePackage + "util.net.Constants"); loader.loadClass(basePackage + "util.net.NioBlockingSelector$BlockPoller$1"); loader.loadClass(basePackage + "util.net.NioBlockingSelector$BlockPoller$2"); loader.loadClass(basePackage + "util.net.NioBlockingSelector$BlockPoller$3"); loader.loadClass(basePackage + "util.net.SSLSupport$CipherData"); loader.loadClass (basePackage + "util.net.JIoEndpoint$PrivilegedSetTccl"); loader.loadClass (basePackage + "util.net.AprEndpoint$PrivilegedSetTccl"); }
(Lib) FileNotFoundException 13
              
// in java/org/apache/jasper/compiler/JspUtil.java
public static InputStream getInputStream(String fname, JarFile jarFile, JspCompilationContext ctxt) throws IOException { InputStream in = null; if (jarFile != null) { String jarEntryName = fname.substring(1, fname.length()); ZipEntry jarEntry = jarFile.getEntry(jarEntryName); if (jarEntry == null) { throw new FileNotFoundException(Localizer.getMessage( "jsp.error.file.not.found", fname)); } in = jarFile.getInputStream(jarEntry); } else { in = ctxt.getResourceAsStream(fname); } if (in == null) { throw new FileNotFoundException(Localizer.getMessage( "jsp.error.file.not.found", fname)); } return in; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public Class<?> loadTagFile() throws JasperException { try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; ctxt.compile(); } } else { if (compileException != null) { throw compileException; } } if (reload) { tagHandlerClass = ctxt.load(); reload = false; } } catch (FileNotFoundException ex) { throw new JasperException(ex); } return tagHandlerClass; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile) throws ServletException, IOException, FileNotFoundException { Servlet servlet; try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if ((available > 0L) && (available < Long.MAX_VALUE)) { if (available > System.currentTimeMillis()) { response.setDateHeader("Retry-After", available); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, Localizer.getMessage("jsp.error.unavailable")); return; } // Wait period has expired. Reset. available = 0; } /* * (1) Compile */ if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; // The following sets reload to true, if necessary ctxt.compile(); } } else { if (compileException != null) { // Throw cached compilation exception throw compileException; } } /* * (2) (Re)load servlet class file */ servlet = getServlet(); // If a page is to be precompiled only, return. if (precompile) { return; } } catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; } catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } try { /* * (3) Handle limitation of number of loaded Jsps */ if (unloadAllowed) { synchronized(this) { if (unloadByCount) { if (unloadHandle == null) { unloadHandle = ctxt.getRuntimeContext().push(this); } else if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { ctxt.getRuntimeContext().makeYoungest(unloadHandle); lastUsageTime = System.currentTimeMillis(); } } else { if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { lastUsageTime = System.currentTimeMillis(); } } } } /* * (4) Service request */ if (servlet instanceof SingleThreadModel) { // sync on the wrapper so that the freshness // of the page is determined right before servicing synchronized (this) { servlet.service(request, response); } } else { servlet.service(request, response); } } catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); } catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } }
// in java/org/apache/jasper/JspCompilationContext.java
public void compile() throws JasperException, FileNotFoundException { createCompiler(); if (jspCompiler.isOutDated()) { if (isRemoved()) { throw new FileNotFoundException(jspUri); } try { jspCompiler.removeGeneratedFiles(); jspLoader = null; jspCompiler.compile(); jsw.setReload(true); jsw.setCompilationException(null); } catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; } catch (FileNotFoundException fnfe) { // Re-throw to let caller handle this - will result in a 404 throw fnfe; } catch (Exception ex) { JasperException je = new JasperException( Localizer.getMessage("jsp.error.unable.compile"), ex); // Cache compilation exception jsw.setCompilationException(je); throw je; } } }
// in java/org/apache/naming/resources/DirContextURLConnection.java
Override public Object getContent() throws IOException { if (!connected) connect(); if (resource != null) return getInputStream(); if (collection != null) return collection; if (object != null) return object; throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); }
// in java/org/apache/naming/resources/DirContextURLConnection.java
Override public InputStream getInputStream() throws IOException { if (!connected) connect(); if (resource == null) { throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); } // Reopen resource try { resource = (Resource) context.lookup( URLDecoder.decode(getURL().getFile(), "UTF-8")); } catch (NamingException e) { // Ignore } return (resource.streamContent()); }
// in java/org/apache/naming/resources/DirContextURLConnection.java
public Enumeration<String> list() throws IOException { if (!connected) { connect(); } if ((resource == null) && (collection == null)) { throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); } Vector<String> result = new Vector<String>(); if (collection != null) { try { String file = getURL().getFile(); // This will be of the form /<hostname>/<contextpath>/file name // if <contextpath> is not empty otherwise this will be of the // form /<hostname>/file name // Strip off the hostname and the contextpath (note that context // path may contain '/' int start; if (context instanceof ProxyDirContext) { String cp = ((ProxyDirContext)context).getContextPath(); String h = ((ProxyDirContext)context).getHostName(); if ("".equals(cp)) { start = h.length() + 2; } else { start = h.length() + cp.length() + 2; } } else { start = file.indexOf('/', file.indexOf('/', 1) + 1); } NamingEnumeration<NameClassPair> enumeration = context.list(file.substring(start)); while (enumeration.hasMoreElements()) { NameClassPair ncp = enumeration.nextElement(); result.addElement( URLEncoder.encode(ncp.getName(), "UTF-8")); } } catch (NamingException e) { // Unexpected exception throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); } } return result.elements(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void forceDelete(File file) throws IOException { if (file.isDirectory()) { deleteDirectory(file); } else { boolean filePresent = file.exists(); if (!file.delete()) { if (!filePresent){ throw new FileNotFoundException("File does not exist: " + file); } String message = "Unable to delete file: " + file; throw new IOException(message); } } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException { boolean serveContent = content; // Identify the requested resource path String path = getRelativePath(request); if (debug > 0) { if (serveContent) log("DefaultServlet.serveResource: Serving resource '" + path + "' headers and data"); else log("DefaultServlet.serveResource: Serving resource '" + path + "' headers only"); } CacheEntry cacheEntry = resources.lookupCache(path); if (!cacheEntry.exists) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } else { // We're included // SRV.9.3 says we must throw a FNFE throw new FileNotFoundException( sm.getString("defaultServlet.missingResource", requestUri)); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } // If the resource is not a collection, and the resource path // ends with "/" or "\", return NOT FOUND if (cacheEntry.context == null) { if (path.endsWith("/") || (path.endsWith("\\"))) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } } boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST; // Check if the conditions specified in the optional If headers are // satisfied. if (cacheEntry.context == null) { // Checking If headers boolean included = (request.getAttribute( RequestDispatcher.INCLUDE_CONTEXT_PATH) != null); if (!included && !isError && !checkIfHeaders(request, response, cacheEntry.attributes)) { return; } } // Find content type. String contentType = cacheEntry.attributes.getMimeType(); if (contentType == null) { contentType = getServletContext().getMimeType(cacheEntry.name); cacheEntry.attributes.setMimeType(contentType); } ArrayList<Range> ranges = null; long contentLength = -1L; if (cacheEntry.context != null) { // Skip directory listings if we have been configured to // suppress them if (!listings) { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); return; } contentType = "text/html;charset=UTF-8"; } else { if (!isError) { if (useAcceptRanges) { // Accept ranges header response.setHeader("Accept-Ranges", "bytes"); } // Parse range specifier ranges = parseRange(request, response, cacheEntry.attributes); // ETag header response.setHeader("ETag", cacheEntry.attributes.getETag()); // Last-Modified header response.setHeader("Last-Modified", cacheEntry.attributes.getLastModifiedHttp()); } // Get content length contentLength = cacheEntry.attributes.getContentLength(); // Special case for zero length files, which would cause a // (silent) ISE when setting the output buffer size if (contentLength == 0L) { serveContent = false; } } ServletOutputStream ostream = null; PrintWriter writer = null; if (serveContent) { // Trying to retrieve the servlet output stream try { ostream = response.getOutputStream(); } catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } } } // Check to see if a Filter, Valve of wrapper has written some content. // If it has, disable range requests and setting of a content length // since neither can be done reliably. ServletResponse r = response; long contentWritten = 0; while (r instanceof ServletResponseWrapper) { r = ((ServletResponseWrapper) r).getResponse(); } if (r instanceof ResponseFacade) { contentWritten = ((ResponseFacade) r).getContentWritten(); } if (contentWritten > 0) { ranges = FULL; } if ( (cacheEntry.context != null) || isError || ( ((ranges == null) || (ranges.isEmpty())) && (request.getHeader("Range") == null) ) || (ranges == FULL) ) { // Set the appropriate output headers if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if ((cacheEntry.resource != null) && (contentLength >= 0) && (!serveContent || ostream != null)) { if (debug > 0) log("DefaultServlet.serveFile: contentLength=" + contentLength); // Don't set a content length if something else has already // written to the response. if (contentWritten == 0) { if (contentLength < Integer.MAX_VALUE) { response.setContentLength((int) contentLength); } else { // Set the content-length as String to be able to use a // long response.setHeader("content-length", "" + contentLength); } } } InputStream renderResult = null; if (cacheEntry.context != null) { if (serveContent) { // Serve the directory browser renderResult = render(getPathPrefix(request), cacheEntry); } } // Copy the input stream to our output stream (if requested) if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, contentLength, null)) copy(cacheEntry, renderResult, ostream); } else { copy(cacheEntry, renderResult, writer); } } } else { if ((ranges == null) || (ranges.isEmpty())) return; // Partial content response. response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); if (ranges.size() == 1) { Range range = ranges.get(0); response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; if (length < Integer.MAX_VALUE) { response.setContentLength((int) length); } else { // Set the content-length as String to be able to use a long response.setHeader("content-length", "" + length); } if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, range.end - range.start + 1, range)) copy(cacheEntry, ostream, range); } else { // we should not get here throw new IllegalStateException(); } } } else { response.setContentType("multipart/byteranges; boundary=" + mimeSeparation); if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { copy(cacheEntry, ostream, ranges.iterator(), contentType); } else { // we should not get here throw new IllegalStateException(); } } } } }
1
              
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException e) { // Unexpected exception throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); }
18
              
// in java/org/apache/jasper/compiler/Compiler.java
private ServletWriter setupContextWriter(String javaFileName) throws FileNotFoundException, JasperException { ServletWriter writer; // Setup the ServletWriter String javaEncoding = ctxt.getOptions().getJavaEncoding(); OutputStreamWriter osw = null; try { osw = new OutputStreamWriter( new FileOutputStream(javaFileName), javaEncoding); } catch (UnsupportedEncodingException ex) { errDispatcher.jspError("jsp.error.needAlternateJavaEncoding", javaEncoding); } writer = new ServletWriter(new PrintWriter(osw)); ctxt.setWriter(writer); return writer; }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile() throws FileNotFoundException, JasperException, Exception { compile(true); }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile(boolean compileClass) throws FileNotFoundException, JasperException, Exception { compile(compileClass, false); }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile(boolean compileClass, boolean jspcMode) throws FileNotFoundException, JasperException, Exception { if (errDispatcher == null) { this.errDispatcher = new ErrorDispatcher(jspcMode); } try { String[] smap = generateJava(); File javaFile = new File(ctxt.getServletJavaFileName()); Long jspLastModified = ctxt.getLastModified(ctxt.getJspFile()); javaFile.setLastModified(jspLastModified.longValue()); if (compileClass) { generateClass(smap); // Fix for bugzilla 41606 // Set JspServletWrapper.servletClassLastModifiedTime after successful compile String targetFileName = ctxt.getClassFileName(); if (targetFileName != null) { File targetFile = new File(targetFileName); if (targetFile.exists()) { targetFile.setLastModified(jspLastModified.longValue()); if (jsw != null) { jsw.setServletClassLastModifiedTime( jspLastModified.longValue()); } } } } } finally { if (tfp != null && ctxt.isPrototypeMode()) { tfp.removeProtoTypeFiles(null); } // Make sure these object which are only used during the // generation and compilation of the JSP page get // dereferenced so that they can be GC'd and reduce the // memory footprint. tfp = null; errDispatcher = null; pageInfo = null; // Only get rid of the pageNodes if in production. // In development mode, they are used for detailed // error messages. // http://issues.apache.org/bugzilla/show_bug.cgi?id=37062 if (!this.options.getDevelopment()) { pageNodes = null; } if (ctxt.getWriter() != null) { ctxt.getWriter().close(); ctxt.setWriter(null); } } }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parse(String inFileName) throws FileNotFoundException, JasperException, IOException { // If we're parsing a packaged tag file or a resource included by it // (using an include directive), ctxt.getTagFileJar() returns the // JAR file from which to read the tag file or included resource, // respectively. isTagFile = ctxt.isTagFile(); directiveOnly = false; return doParse(inFileName, null, ctxt.getTagFileJarResource()); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parseDirectives(String inFileName) throws FileNotFoundException, JasperException, IOException { // If we're parsing a packaged tag file or a resource included by it // (using an include directive), ctxt.getTagFileJar() returns the // JAR file from which to read the tag file or included resource, // respectively. isTagFile = ctxt.isTagFile(); directiveOnly = true; return doParse(inFileName, null, ctxt.getTagFileJarResource()); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parse(String inFileName, Node parent, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { // For files that are statically included, isTagfile and directiveOnly // remain unchanged. return doParse(inFileName, parent, jarResource); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parseTagFileDirectives(String inFileName, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { boolean isTagFileSave = isTagFile; boolean directiveOnlySave = directiveOnly; isTagFile = true; directiveOnly = true; Node.Nodes page = doParse(inFileName, null, jarResource); directiveOnly = directiveOnlySave; isTagFile = isTagFileSave; return page; }
// in java/org/apache/jasper/compiler/ParserController.java
private Node.Nodes doParse(String inFileName, Node parent, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { Node.Nodes parsedPage = null; isEncodingSpecifiedInProlog = false; isBomPresent = false; isDefaultPageEncoding = false; JarFile jarFile = (jarResource == null) ? null : jarResource.getJarFile(); String absFileName = resolveFileName(inFileName); String jspConfigPageEnc = getJspConfigPageEncoding(absFileName); // Figure out what type of JSP document and encoding type we are // dealing with determineSyntaxAndEncoding(absFileName, jarFile, jspConfigPageEnc); if (parent != null) { // Included resource, add to dependent list if (jarFile == null) { compiler.getPageInfo().addDependant(absFileName, ctxt.getLastModified(absFileName)); } else { String entry = absFileName.substring(1); compiler.getPageInfo().addDependant( jarResource.getEntry(entry).toString(), Long.valueOf(jarFile.getEntry(entry).getTime())); } } if ((isXml && isEncodingSpecifiedInProlog) || isBomPresent) { /* * Make sure the encoding explicitly specified in the XML * prolog (if any) matches that in the JSP config element * (if any), treating "UTF-16", "UTF-16BE", and "UTF-16LE" as * identical. */ if (jspConfigPageEnc != null && !jspConfigPageEnc.equals(sourceEnc) && (!jspConfigPageEnc.startsWith("UTF-16") || !sourceEnc.startsWith("UTF-16"))) { err.jspError("jsp.error.prolog_config_encoding_mismatch", sourceEnc, jspConfigPageEnc); } } // Dispatch to the appropriate parser if (isXml) { // JSP document (XML syntax) // InputStream for jspx page is created and properly closed in // JspDocumentParser. parsedPage = JspDocumentParser.parse(this, absFileName, jarFile, parent, isTagFile, directiveOnly, sourceEnc, jspConfigPageEnc, isEncodingSpecifiedInProlog, isBomPresent); } else { // Standard syntax InputStreamReader inStreamReader = null; try { inStreamReader = JspUtil.getReader(absFileName, sourceEnc, jarFile, ctxt, err, skip); JspReader jspReader = new JspReader(ctxt, absFileName, sourceEnc, inStreamReader, err); parsedPage = Parser.parse(this, jspReader, parent, isTagFile, directiveOnly, jarResource, sourceEnc, jspConfigPageEnc, isDefaultPageEncoding, isBomPresent); } finally { if (inStreamReader != null) { try { inStreamReader.close(); } catch (Exception any) { } } } } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } baseDirStack.pop(); return parsedPage; }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
private InputStream getResourceAsStream(String uri) throws FileNotFoundException { // Is uri absolute? if (uri.startsWith("file:")) { return new FileInputStream(new File(uri.substring(5))); } else { try { // see if file exists on the filesystem String real = ctxt.getRealPath(uri); if (real == null) { return ctxt.getResourceAsStream(uri); } else { return new FileInputStream(real); } } catch (FileNotFoundException ex) { // if file not found on filesystem, get the resource through // the context return ctxt.getResourceAsStream(uri); } } }
// in java/org/apache/jasper/compiler/JDTCompiler.java
Override protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception { long t1 = 0; if (log.isDebugEnabled()) { t1 = System.currentTimeMillis(); } final String sourceFile = ctxt.getServletJavaFileName(); final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath(); String packageName = ctxt.getServletPackageName(); final String targetClassName = ((packageName.length() != 0) ? (packageName + ".") : "") + ctxt.getServletClassName(); final ClassLoader classLoader = ctxt.getJspLoader(); String[] fileNames = new String[] {sourceFile}; String[] classNames = new String[] {targetClassName}; final ArrayList<JavacErrorDetail> problemList = new ArrayList<JavacErrorDetail>(); class CompilationUnit implements ICompilationUnit { private final String className; private final String sourceFile; CompilationUnit(String sourceFile, String className) { this.className = className; this.sourceFile = sourceFile; } @Override public char[] getFileName() { return sourceFile.toCharArray(); } @Override public char[] getContents() { char[] result = null; FileInputStream is = null; InputStreamReader isr = null; Reader reader = null; try { is = new FileInputStream(sourceFile); isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding()); reader = new BufferedReader(isr); char[] chars = new char[8192]; StringBuilder buf = new StringBuilder(); int count; while ((count = reader.read(chars, 0, chars.length)) > 0) { buf.append(chars, 0, count); } result = new char[buf.length()]; buf.getChars(0, result.length, result, 0); } catch (IOException e) { log.error("Compilation error", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) {/*Ignore*/} } if (isr != null) { try { isr.close(); } catch (IOException ioe) {/*Ignore*/} } if (is != null) { try { is.close(); } catch (IOException exc) {/*Ignore*/} } } return result; } @Override public char[] getMainTypeName() { int dot = className.lastIndexOf('.'); if (dot > 0) { return className.substring(dot + 1).toCharArray(); } return className.toCharArray(); } @Override public char[][] getPackageName() { StringTokenizer izer = new StringTokenizer(className, "."); char[][] result = new char[izer.countTokens()-1][]; for (int i = 0; i < result.length; i++) { String tok = izer.nextToken(); result[i] = tok.toCharArray(); } return result; } @SuppressWarnings("unused") // New method added to interface in // later JDT versions public boolean ignoreOptionalProblems() { return false; } }
// in java/org/apache/jasper/compiler/AntCompiler.java
Override protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception { long t1 = 0; if (log.isDebugEnabled()) { t1 = System.currentTimeMillis(); } String javaEncoding = ctxt.getOptions().getJavaEncoding(); String javaFileName = ctxt.getServletJavaFileName(); String classpath = ctxt.getClassPath(); String sep = System.getProperty("path.separator"); StringBuilder errorReport = new StringBuilder(); StringBuilder info=new StringBuilder(); info.append("Compile: javaFileName=" + javaFileName + "\n" ); info.append(" classpath=" + classpath + "\n" ); // Start capturing the System.err output for this thread SystemLogHandler.setThread(); // Initializing javac task getProject(); Javac javac = (Javac) project.createTask("javac"); // Initializing classpath Path path = new Path(project); path.setPath(System.getProperty("java.class.path")); info.append(" cp=" + System.getProperty("java.class.path") + "\n"); StringTokenizer tokenizer = new StringTokenizer(classpath, sep); while (tokenizer.hasMoreElements()) { String pathElement = tokenizer.nextToken(); File repository = new File(pathElement); path.setLocation(repository); info.append(" cp=" + repository + "\n"); } if( log.isDebugEnabled() ) log.debug( "Using classpath: " + System.getProperty("java.class.path") + sep + classpath); // Initializing sourcepath Path srcPath = new Path(project); srcPath.setLocation(options.getScratchDir()); info.append(" work dir=" + options.getScratchDir() + "\n"); // Initialize and set java extensions String exts = System.getProperty("java.ext.dirs"); if (exts != null) { Path extdirs = new Path(project); extdirs.setPath(exts); javac.setExtdirs(extdirs); info.append(" extension dir=" + exts + "\n"); } // Add endorsed directories if any are specified and we're forking // See Bugzilla 31257 if(ctxt.getOptions().getFork()) { String endorsed = System.getProperty("java.endorsed.dirs"); if(endorsed != null) { Javac.ImplementationSpecificArgument endorsedArg = javac.createCompilerArg(); endorsedArg.setLine("-J-Djava.endorsed.dirs=" + quotePathList(endorsed)); info.append(" endorsed dir=" + quotePathList(endorsed) + "\n"); } else { info.append(" no endorsed dirs specified\n"); } } // Configure the compiler object javac.setEncoding(javaEncoding); javac.setClasspath(path); javac.setDebug(ctxt.getOptions().getClassDebugInfo()); javac.setSrcdir(srcPath); javac.setTempdir(options.getScratchDir()); javac.setOptimize(! ctxt.getOptions().getClassDebugInfo() ); javac.setFork(ctxt.getOptions().getFork()); info.append(" srcDir=" + srcPath + "\n" ); // Set the Java compiler to use if (options.getCompiler() != null) { javac.setCompiler(options.getCompiler()); info.append(" compiler=" + options.getCompiler() + "\n"); } if (options.getCompilerTargetVM() != null) { javac.setTarget(options.getCompilerTargetVM()); info.append(" compilerTargetVM=" + options.getCompilerTargetVM() + "\n"); } if (options.getCompilerSourceVM() != null) { javac.setSource(options.getCompilerSourceVM()); info.append(" compilerSourceVM=" + options.getCompilerSourceVM() + "\n"); } // Build includes path PatternSet.NameEntry includes = javac.createInclude(); includes.setName(ctxt.getJavaPath()); info.append(" include="+ ctxt.getJavaPath() + "\n" ); BuildException be = null; try { if (ctxt.getOptions().getFork()) { javac.execute(); } else { synchronized(javacLock) { javac.execute(); } } } catch (BuildException e) { be = e; log.error(Localizer.getMessage("jsp.error.javac"), e); log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString()); } errorReport.append(logger.getReport()); // Stop capturing the System.err output for this thread String errorCapture = SystemLogHandler.unsetThread(); if (errorCapture != null) { errorReport.append(Constants.NEWLINE); errorReport.append(errorCapture); } if (!ctxt.keepGenerated()) { File javaFile = new File(javaFileName); javaFile.delete(); } if (be != null) { String errorReportString = errorReport.toString(); log.error(Localizer.getMessage("jsp.error.compilation", javaFileName, errorReportString)); JavacErrorDetail[] javacErrors = ErrorDispatcher.parseJavacErrors( errorReportString, javaFileName, pageNodes); if (javacErrors != null) { errDispatcher.javacError(javacErrors); } else { errDispatcher.javacError(errorReportString, be); } } if( log.isDebugEnabled() ) { long t2 = System.currentTimeMillis(); log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2-t1) + "ms"); } logger = null; project = null; if (ctxt.isPrototypeMode()) { return; } // JSR45 Support if (! options.isSmapSuppressed()) { SmapUtil.installSmap(smap); } }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile) throws ServletException, IOException, FileNotFoundException { Servlet servlet; try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if ((available > 0L) && (available < Long.MAX_VALUE)) { if (available > System.currentTimeMillis()) { response.setDateHeader("Retry-After", available); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, Localizer.getMessage("jsp.error.unavailable")); return; } // Wait period has expired. Reset. available = 0; } /* * (1) Compile */ if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; // The following sets reload to true, if necessary ctxt.compile(); } } else { if (compileException != null) { // Throw cached compilation exception throw compileException; } } /* * (2) (Re)load servlet class file */ servlet = getServlet(); // If a page is to be precompiled only, return. if (precompile) { return; } } catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; } catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } try { /* * (3) Handle limitation of number of loaded Jsps */ if (unloadAllowed) { synchronized(this) { if (unloadByCount) { if (unloadHandle == null) { unloadHandle = ctxt.getRuntimeContext().push(this); } else if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { ctxt.getRuntimeContext().makeYoungest(unloadHandle); lastUsageTime = System.currentTimeMillis(); } } else { if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { lastUsageTime = System.currentTimeMillis(); } } } } /* * (4) Service request */ if (servlet instanceof SingleThreadModel) { // sync on the wrapper so that the freshness // of the page is determined right before servicing synchronized (this) { servlet.service(request, response); } } else { servlet.service(request, response); } } catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); } catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } }
// in java/org/apache/jasper/JspCompilationContext.java
public void compile() throws JasperException, FileNotFoundException { createCompiler(); if (jspCompiler.isOutDated()) { if (isRemoved()) { throw new FileNotFoundException(jspUri); } try { jspCompiler.removeGeneratedFiles(); jspLoader = null; jspCompiler.compile(); jsw.setReload(true); jsw.setCompilationException(null); } catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; } catch (FileNotFoundException fnfe) { // Re-throw to let caller handle this - will result in a 404 throw fnfe; } catch (Exception ex) { JasperException je = new JasperException( Localizer.getMessage("jsp.error.unable.compile"), ex); // Cache compilation exception jsw.setCompilationException(je); throw je; } } }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public static FileMessageFactory getInstance(File f, boolean openForWrite) throws FileNotFoundException, IOException { return new FileMessageFactory(f, openForWrite); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
public synchronized FileMessageFactory getFactory(FileMessage msg) throws java.io.FileNotFoundException, java.io.IOException { File writeToFile = new File(getTempDir(), msg.getFileName()); FileMessageFactory factory = fileFactories.get(msg.getFileName()); if (factory == null) { factory = FileMessageFactory.getInstance(writeToFile, true); fileFactories.put(msg.getFileName(), factory); } return factory; }
(Lib) NameNotFoundException 13
              
// in java/org/apache/naming/NamingContext.java
Override public void unbind(Name name) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).unbind(name.getSuffix(1)); } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { bindings.remove(name.get(0)); } }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { return new NamingContextEnumeration(bindings.values().iterator()); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).list(name.getSuffix(1)); }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { return new NamingContextBindingsEnumeration(bindings.values().iterator(), this); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).listBindings(name.getSuffix(1)); }
// in java/org/apache/naming/NamingContext.java
Override public void destroySubcontext(Name name) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).destroySubcontext(name.getSuffix(1)); } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).close(); bindings.remove(name.get(0)); } else { throw new NotContextException (sm.getString("namingContext.contextExpected")); } } }
// in java/org/apache/naming/NamingContext.java
protected Object lookup(Name name, boolean resolveLinks) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { // If name is empty, a newly allocated naming context is returned return new NamingContext(env, this.name, bindings); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { // If the size of the name is greater that 1, then we go through a // number of subcontexts. if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).lookup(name.getSuffix(1)); } else { if ((resolveLinks) && (entry.type == NamingEntry.LINK_REF)) { String link = ((LinkRef) entry.value).getLinkName(); if (link.startsWith(".")) { // Link relative to this context return lookup(link.substring(1)); } else { return (new InitialContext(env)).lookup(link); } } else if (entry.type == NamingEntry.REFERENCE) { try { Object obj = NamingManager.getObjectInstance (entry.value, name, this, env); if(entry.value instanceof ResourceRef) { boolean singleton = Boolean.parseBoolean( (String) ((ResourceRef) entry.value).get( "singleton").getContent()); if (singleton) { entry.type = NamingEntry.ENTRY; entry.value = obj; } } return obj; } catch (NamingException e) { throw e; } catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); } } else { return entry.value; } } }
// in java/org/apache/naming/NamingContext.java
protected void bind(Name name, Object obj, boolean rebind) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (name.size() > 1) { if (entry == null) { throw new NameNotFoundException(sm.getString( "namingContext.nameNotBound", name, name.get(0))); } if (entry.type == NamingEntry.CONTEXT) { if (rebind) { ((Context) entry.value).rebind(name.getSuffix(1), obj); } else { ((Context) entry.value).bind(name.getSuffix(1), obj); } } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if ((!rebind) && (entry != null)) { throw new NameAlreadyBoundException (sm.getString("namingContext.alreadyBound", name.get(0))); } else { // Getting the type of the object and wrapping it within a new // NamingEntry Object toBind = NamingManager.getStateToBind(obj, name, this, env); if (toBind instanceof Context) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.CONTEXT); } else if (toBind instanceof LinkRef) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.LINK_REF); } else if (toBind instanceof Reference) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else if (toBind instanceof Referenceable) { toBind = ((Referenceable) toBind).getReference(); entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else { entry = new NamingEntry(name.get(0), toBind, NamingEntry.ENTRY); } bindings.put(name.get(0), entry); } } }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { if (name.isEmpty()) return new NamingContextEnumeration(list(entries).iterator()); Entry entry = treeLookup(name); if (entry == null) throw new NameNotFoundException (sm.getString("resources.notFound", name)); return new NamingContextEnumeration(list(entry).iterator()); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void unbind(String name) throws NamingException { File file = file(name); if (file == null) throw new NameNotFoundException( sm.getString("resources.notFound", name)); if (!file.delete()) throw new NamingException (sm.getString("resources.unbindFailed", name)); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void rename(String oldName, String newName) throws NamingException { File file = file(oldName); if (file == null) throw new NameNotFoundException (sm.getString("resources.notFound", oldName)); File newFile = new File(base, newName); if (!file.renameTo(newFile)) { throw new NamingException(sm.getString("resources.renameFail", oldName, newName)); } }
// in java/org/apache/naming/resources/FileDirContext.java
Override public NamingEnumeration<NameClassPair> list(String name) throws NamingException { File file = file(name); if (file == null) throw new NameNotFoundException (sm.getString("resources.notFound", name)); return new NamingContextEnumeration(list(file).iterator()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final Object lookup(String name) throws NamingException { // First check for aliases if (!aliases.isEmpty()) { AliasResult result = findAlias(name); if (result.dirContext != null) { return result.dirContext.lookup(result.aliasName); } } // Next do a standard lookup Object obj = doLookup(name); if (obj != null) return obj; // Check the alternate locations for (DirContext altDirContext : altDirContexts) { try { obj = altDirContext.lookup("/META-INF/resources" + name); if (obj != null) return obj; } catch ( NamingException ex) { // ignore } } // Really not found throw new NameNotFoundException( sm.getString("resources.notFound", name)); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final NamingEnumeration<Binding> listBindings(String name) throws NamingException { if (!aliases.isEmpty()) { AliasResult result = findAlias(name); if (result.dirContext != null) { return result.dirContext.listBindings(result.aliasName); } } // Next do a standard lookup List<NamingEntry> bindings = doListBindings(name); // Check the alternate locations List<NamingEntry> altBindings = null; for (DirContext altDirContext : altDirContexts) { if (altDirContext instanceof BaseDirContext) { altBindings = ((BaseDirContext) altDirContext).doListBindings( "/META-INF/resources" + name); } if (altBindings != null) { if (bindings == null) { bindings = altBindings; } else { bindings.addAll(altBindings); } } } if (bindings != null) { return new NamingContextBindingsEnumeration(bindings.iterator(), this); } // Really not found throw new NameNotFoundException( sm.getString("resources.notFound", name)); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final Attributes getAttributes(String name, String[] attrIds) throws NamingException { // First check for aliases if (!aliases.isEmpty()) { AliasResult result = findAlias(name); if (result.dirContext != null) { return result.dirContext.getAttributes( result.aliasName, attrIds); } } // Next do a standard lookup Attributes attrs = doGetAttributes(name, attrIds); if (attrs != null) return attrs; // Check the alternate locations for (DirContext altDirContext : altDirContexts) { if (altDirContext instanceof BaseDirContext) attrs = ((BaseDirContext) altDirContext).doGetAttributes( "/META-INF/resources" + name, attrIds); else { try { attrs = altDirContext.getAttributes(name, attrIds); } catch (NamingException ne) { // Ignore } } if (attrs != null) return attrs; } // Really not found throw new NameNotFoundException( sm.getString("resources.notFound", name)); }
0 0
(Domain) PropertyNotWritableException 11
              
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); throw new PropertyNotWritableException( "Legacy VariableResolver wrapped, not writable"); } if (!context.isPropertyResolved()) { elResolver.setValue(context, base, property, value); } }
// in java/org/apache/el/parser/SimpleNode.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { throw new PropertyNotWritableException(MessageFactory.get("error.syntax.set")); }
// in java/org/apache/el/ValueExpressionLiteral.java
Override public void setValue(ELContext context, Object value) { throw new PropertyNotWritableException(MessageFactory.get( "error.value.literal.write", this.value)); }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); throw new PropertyNotWritableException(); } } }
// in java/javax/el/ResourceBundleELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } }
// in java/javax/el/ArrayELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); checkBounds(base, idx); if (value != null && !base.getClass().getComponentType().isAssignableFrom( value.getClass())) { throw new ClassCastException(message(context, "objectNotAssignable", new Object[] {value.getClass().getName(), base.getClass().getComponentType().getName()})); } Array.set(base, idx, value); } }
// in java/javax/el/MapELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } try { @SuppressWarnings("unchecked") // Must be OK Map<Object, Object> map = ((Map<Object, Object>) base); map.put(property, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } } }
// in java/javax/el/BeanELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return; } context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } Method m = this.property(context, base, property).write(context); try { m.invoke(base, value); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/ListELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); @SuppressWarnings("unchecked") // Must be OK to cast to Object List<Object> list = (List<Object>) base; if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); try { list.set(idx, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); } } }
2
              
// in java/javax/el/MapELResolver.java
catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); }
// in java/javax/el/ListELResolver.java
catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); }
11
              
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); throw new PropertyNotWritableException( "Legacy VariableResolver wrapped, not writable"); } if (!context.isPropertyResolved()) { elResolver.setValue(context, base, property, value); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void setValue(ELContext context, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { try { this.target.setValue(context, value); } catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/el/ValueExpressionImpl.java
Override public void setValue(ELContext context, Object value) throws PropertyNotFoundException, PropertyNotWritableException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); this.getNode().setValue(ctx, value); }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); throw new PropertyNotWritableException(); } } }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); int scope = page.getAttributesScope(key); if (scope != 0) { page.setAttribute(key, value, scope); } else { page.setAttribute(key, value); } } } }
// in java/javax/el/ResourceBundleELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } }
// in java/javax/el/CompositeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { context.setPropertyResolved(false); int sz = this.size; for (int i = 0; i < sz; i++) { this.resolvers[i].setValue(context, base, property, value); if (context.isPropertyResolved()) { return; } } }
// in java/javax/el/ArrayELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); checkBounds(base, idx); if (value != null && !base.getClass().getComponentType().isAssignableFrom( value.getClass())) { throw new ClassCastException(message(context, "objectNotAssignable", new Object[] {value.getClass().getName(), base.getClass().getComponentType().getName()})); } Array.set(base, idx, value); } }
// in java/javax/el/MapELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } try { @SuppressWarnings("unchecked") // Must be OK Map<Object, Object> map = ((Map<Object, Object>) base); map.put(property, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } } }
// in java/javax/el/BeanELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return; } context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } Method m = this.property(context, base, property).write(context); try { m.invoke(base, value); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/ListELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); @SuppressWarnings("unchecked") // Must be OK to cast to Object List<Object> list = (List<Object>) base; if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); try { list.set(idx, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); } } }
(Lib) ArrayIndexOutOfBoundsException 11
              
// in java/org/apache/coyote/ajp/AjpMessage.java
private void validatePos(int posToTest) { if (posToTest > len + 4) { // Trying to read data beyond the end of the AJP message throw new ArrayIndexOutOfBoundsException(sm.getString( "ajpMessage.invalidPos", Integer.valueOf(posToTest))); } }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public void setLength(int size) { if ( size > buf.length ) throw new ArrayIndexOutOfBoundsException("Size is larger than existing buffer."); bufSize = size; }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public void trim(int length) { if ( (bufSize - length) < 0 ) throw new ArrayIndexOutOfBoundsException("Can't trim more bytes than are available. length:"+bufSize+" trim:"+length); bufSize -= length; }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static byte[] createDataPackage(byte[] data, int doff, int dlength, byte[] buffer, int bufoff) { if ( (buffer.length-bufoff) > getDataPackageLength(dlength) ) { throw new ArrayIndexOutOfBoundsException("Unable to create data package, buffer is too small."); } System.arraycopy(START_DATA, 0, buffer, bufoff, START_DATA.length); toBytes(data.length,buffer, bufoff+START_DATA.length); System.arraycopy(data, doff, buffer, bufoff+START_DATA.length + 4, dlength); System.arraycopy(END_DATA, 0, buffer, bufoff+START_DATA.length + 4 + data.length, END_DATA.length); return buffer; }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static int firstIndexOf(byte[] src, int srcOff, byte[] find){ int result = -1; if (find.length > src.length) return result; if (find.length == 0 || src.length == 0) return result; if (srcOff >= src.length ) throw new java.lang.ArrayIndexOutOfBoundsException(); boolean found = false; int srclen = src.length; int findlen = find.length; byte first = find[0]; int pos = srcOff; while (!found) { //find the first byte while (pos < srclen){ if (first == src[pos]) break; pos++; } if (pos >= srclen) return -1; //we found the first character //match the rest of the bytes - they have to match if ( (srclen - pos) < findlen) return -1; //assume it does exist found = true; for (int i = 1; ( (i < findlen) && found); i++) found = found && (find[i] == src[pos + i]
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
public static MemberImpl getMember(byte[] data, int offset, int length, MemberImpl member) { //package looks like //start package TRIBES_MBR_BEGIN.length //package length - 4 bytes //alive - 8 bytes //port - 4 bytes //secure port - 4 bytes //udp port - 4 bytes //host length - 1 byte //host - hl bytes //clen - 4 bytes //command - clen bytes //dlen - 4 bytes //domain - dlen bytes //uniqueId - 16 bytes //payload length - 4 bytes //payload plen bytes //end package TRIBES_MBR_END.length int pos = offset; if (XByteBuffer.firstIndexOf(data,offset,TRIBES_MBR_BEGIN)!=pos) { throw new IllegalArgumentException("Invalid package, should start with:"+org.apache.catalina.tribes.util.Arrays.toString(TRIBES_MBR_BEGIN)); } if ( length < (TRIBES_MBR_BEGIN.length+4) ) { throw new ArrayIndexOutOfBoundsException("Member package to small to validate."); } pos += TRIBES_MBR_BEGIN.length; int bodylength = XByteBuffer.toInt(data,pos); pos += 4; if ( length < (bodylength+4+TRIBES_MBR_BEGIN.length+TRIBES_MBR_END.length) ) { throw new ArrayIndexOutOfBoundsException("Not enough bytes in member package."); } int endpos = pos+bodylength; if (XByteBuffer.firstIndexOf(data,endpos,TRIBES_MBR_END)!=endpos) { throw new IllegalArgumentException("Invalid package, should end with:"+org.apache.catalina.tribes.util.Arrays.toString(TRIBES_MBR_END)); } byte[] alived = new byte[8]; System.arraycopy(data, pos, alived, 0, 8); pos += 8; byte[] portd = new byte[4]; System.arraycopy(data, pos, portd, 0, 4); pos += 4; byte[] sportd = new byte[4]; System.arraycopy(data, pos, sportd, 0, 4); pos += 4; byte[] uportd = new byte[4]; System.arraycopy(data, pos, uportd, 0, 4); pos += 4; byte hl = data[pos++]; byte[] addr = new byte[hl]; System.arraycopy(data, pos, addr, 0, hl); pos += hl; int cl = XByteBuffer.toInt(data, pos); pos += 4; byte[] command = new byte[cl]; System.arraycopy(data, pos, command, 0, command.length); pos += command.length; int dl = XByteBuffer.toInt(data, pos); pos += 4; byte[] domain = new byte[dl]; System.arraycopy(data, pos, domain, 0, domain.length); pos += domain.length; byte[] uniqueId = new byte[16]; System.arraycopy(data, pos, uniqueId, 0, 16); pos += 16; int pl = XByteBuffer.toInt(data, pos); pos += 4; byte[] payload = new byte[pl]; System.arraycopy(data, pos, payload, 0, payload.length); pos += payload.length; member.setHost(addr); member.setPort(XByteBuffer.toInt(portd, 0)); member.setSecurePort(XByteBuffer.toInt(sportd, 0)); member.setUdpPort(XByteBuffer.toInt(uportd, 0)); member.setMemberAliveTime(XByteBuffer.toLong(alived, 0)); member.setUniqueId(uniqueId); member.payload = payload; member.domain = domain; member.command = command; member.dataPkg = new byte[length]; System.arraycopy(data, offset, member.dataPkg, 0, length); return member; }
// in java/org/apache/catalina/tribes/util/UUIDGenerator.java
public static byte[] randomUUID(boolean secure, byte[] into, int offset) { if ( (offset+UUID_LENGTH)>into.length ) throw new ArrayIndexOutOfBoundsException("Unable to fit "+UUID_LENGTH+" bytes into the array. length:"+into.length+" required length:"+(offset+UUID_LENGTH)); Random r = (secure&&(secrand!=null))?secrand:rand; nextBytes(into,offset,UUID_LENGTH,r); into[6+offset] &= 0x0F; into[6+offset] |= (UUID_VERSION << 4); into[8+offset] &= 0x3F; //0011 1111 into[8+offset] |= 0x80; //1000 0000 return into; }
// in java/org/apache/catalina/tribes/util/Arrays.java
public static boolean contains(byte[] source, int srcoffset, byte[] key, int keyoffset, int length) { if ( srcoffset < 0 || srcoffset >= source.length) throw new ArrayIndexOutOfBoundsException("srcoffset is out of bounds."); if ( keyoffset < 0 || keyoffset >= key.length) throw new ArrayIndexOutOfBoundsException("keyoffset is out of bounds."); if ( length > (key.length-keyoffset) ) throw new ArrayIndexOutOfBoundsException("not enough data elements in the key, length is out of bounds."); //we don't have enough data to validate it if ( length > (source.length-srcoffset) ) return false; boolean match = true; int pos = keyoffset; for ( int i=srcoffset; match && i<length; i++ ) { match = (source[i] == key[pos++]); } return match; }
0 0
(Lib) SAXException 12
              
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private Node parseCustomAction( String qName, String localName, String uri, Attributes nonTaglibAttrs, Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs, Mark start, Node parent) throws SAXException { // Check if this is a user-defined (custom) tag TagLibraryInfo tagLibInfo = pageInfo.getTaglib(uri); if (tagLibInfo == null) { return null; } TagInfo tagInfo = tagLibInfo.getTag(localName); TagFileInfo tagFileInfo = tagLibInfo.getTagFile(localName); if (tagInfo == null && tagFileInfo == null) { throw new SAXException( Localizer.getMessage("jsp.error.xml.bad_tag", localName, uri)); } Class<?> tagHandlerClass = null; if (tagInfo != null) { String handlerClassName = tagInfo.getTagClassName(); try { tagHandlerClass = ctxt.getClassLoader().loadClass(handlerClassName); } catch (Exception e) { throw new SAXException( Localizer.getMessage("jsp.error.loadclass.taghandler", handlerClassName, qName), e); } } String prefix = getPrefix(qName); Node.CustomTag ret = null; if (tagInfo != null) { ret = new Node.CustomTag( qName, prefix, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, parent, tagInfo, tagHandlerClass); } else { ret = new Node.CustomTag( qName, prefix, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, parent, tagFileInfo); } return ret; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void checkScriptingBody(Node.ScriptingElement scriptingElem) throws SAXException { Node.Nodes body = scriptingElem.getBody(); if (body != null) { int size = body.size(); for (int i = 0; i < size; i++) { Node n = body.getNode(i); if (!(n instanceof Node.TemplateText)) { String elemType = SCRIPTLET_ACTION; if (scriptingElem instanceof Node.Declaration) elemType = DECLARATION_ACTION; if (scriptingElem instanceof Node.Expression) elemType = EXPRESSION_ACTION; String msg = Localizer.getMessage( "jsp.error.parse.xml.scripting.invalid.body", elemType); throw new SAXException(msg); } } } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void processIncludeDirective(String fname, Node parent) throws SAXException { if (fname == null) { return; } try { parserController.parse(fname, parent, null); } catch (FileNotFoundException fnfe) { throw new SAXParseException( Localizer.getMessage("jsp.error.file.not.found", fname), locator, fnfe); } catch (Exception e) { throw new SAXException(e); } }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { for (int i = 0; i < Constants.CACHED_DTD_PUBLIC_IDS.size(); i++) { String cachedDtdPublicId = Constants.CACHED_DTD_PUBLIC_IDS.get(i); if (cachedDtdPublicId.equals(publicId)) { String resourcePath = Constants.CACHED_DTD_RESOURCE_PATHS.get(i); InputStream input = this.getClass().getResourceAsStream( resourcePath); if (input == null) { throw new SAXException(Localizer.getMessage( "jsp.error.internal.filenotfound", resourcePath)); } InputSource isrc = new InputSource(input); return isrc; } } Log log = LogFactory.getLog(MyEntityResolver.class); if (log.isDebugEnabled()) log.debug("Resolve entity failed" + publicId + " " + systemId); log.error(Localizer.getMessage("jsp.error.parse.xml.invalidPublicId", publicId)); return null; }
// in java/org/apache/tomcat/util/digester/CallMethodRule.java
Override public void end(String namespace, String name) throws Exception { // Retrieve or construct the parameter values array Object parameters[] = null; if (paramCount > 0) { parameters = (Object[]) digester.popParams(); if (digester.log.isTraceEnabled()) { for (int i=0,size=parameters.length;i<size;i++) { digester.log.trace("[CallMethodRule](" + i + ")" + parameters[i]) ; } } // In the case where the parameter for the method // is taken from an attribute, and that attribute // isn't actually defined in the source XML file, // skip the method call if (paramCount == 1 && parameters[0] == null) { return; } } else if (paramTypes != null && paramTypes.length != 0) { // In the case where the parameter for the method // is taken from the body text, but there is no // body text included in the source XML file, // skip the method call if (bodyText == null) { return; } parameters = new Object[1]; parameters[0] = bodyText; if (paramTypes.length == 0) { paramTypes = new Class[1]; paramTypes[0] = "abc".getClass(); } } // Construct the parameter values array we will need // We only do the conversion if the param value is a String and // the specified paramType is not String. Object paramValues[] = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { // convert nulls and convert stringy parameters // for non-stringy param types if( parameters[i] == null || (parameters[i] instanceof String && !String.class.isAssignableFrom(paramTypes[i]))) { paramValues[i] = IntrospectionUtils.convert((String) parameters[i], paramTypes[i]); } else { paramValues[i] = parameters[i]; } } // Determine the target object for the method call Object target; if (targetOffset >= 0) { target = digester.peek(targetOffset); } else { target = digester.peek( digester.getCount() + targetOffset ); } if (target == null) { StringBuilder sb = new StringBuilder(); sb.append("[CallMethodRule]{"); sb.append(digester.match); sb.append("} Call target is null ("); sb.append("targetOffset="); sb.append(targetOffset); sb.append(",stackdepth="); sb.append(digester.getCount()); sb.append(")"); throw new org.xml.sax.SAXException(sb.toString()); } // Invoke the required method on the top object if (digester.log.isDebugEnabled()) { StringBuilder sb = new StringBuilder("[CallMethodRule]{"); sb.append(digester.match); sb.append("} Call "); sb.append(target.getClass().getName()); sb.append("."); sb.append(methodName); sb.append("("); for (int i = 0; i < paramValues.length; i++) { if (i > 0) { sb.append(","); } if (paramValues[i] == null) { sb.append("null"); } else { sb.append(paramValues[i].toString()); } sb.append("/"); if (paramTypes[i] == null) { sb.append("null"); } else { sb.append(paramTypes[i].getName()); } } sb.append(")"); digester.log.debug(sb.toString()); } Object result = IntrospectionUtils.callMethodN(target, methodName, paramValues, paramTypes); processMethodCallResult(result); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void characters(char[] ch, int start, int length) throws SAXException { try { String str = new String(ch, start, length); if (str.trim().length() > 0) { top.appendChild(doc.createTextNode(str)); } } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { try { if (depth == 0) { getDigester().getXMLReader().setContentHandler( oldContentHandler); getDigester().push(root); getDigester().endElement(namespaceURI, localName, qName); } top = top.getParentNode(); depth--; } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void processingInstruction(String target, String data) throws SAXException { try { top.appendChild(doc.createProcessingInstruction(target, data)); } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { try { Node previousTop = top; if ((localName == null) || (localName.length() == 0)) { top = doc.createElement(qName); } else { top = doc.createElementNS(namespaceURI, localName); } for (int i = 0; i < atts.getLength(); i++) { Attr attr = null; if ((atts.getLocalName(i) == null) || (atts.getLocalName(i).length() == 0)) { attr = doc.createAttribute(atts.getQName(i)); attr.setNodeValue(atts.getValue(i)); ((Element)top).setAttributeNode(attr); } else { attr = doc.createAttributeNS(atts.getURI(i), atts.getLocalName(i)); attr.setNodeValue(atts.getValue(i)); ((Element)top).setAttributeNodeNS(attr); } } previousTop.appendChild(top); depth++; } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void end(String namespace, String name) throws Exception { // Retrieve or construct the parameter values array Object parameters[] = null; if (paramCount > 0) { parameters = (Object[]) digester.popParams(); } else { parameters = new Object[0]; super.end(namespace, name); } ArrayList<?> multiParams = (ArrayList<?>) parameters[multiParamIndex]; // Construct the parameter values array we will need // We only do the conversion if the param value is a String and // the specified paramType is not String. Object paramValues[] = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { if (i != multiParamIndex) { // convert nulls and convert stringy parameters // for non-stringy param types if(parameters[i] == null || (parameters[i] instanceof String && !String.class.isAssignableFrom(paramTypes[i]))) { paramValues[i] = IntrospectionUtils.convert((String) parameters[i], paramTypes[i]); } else { paramValues[i] = parameters[i]; } } } // Determine the target object for the method call Object target; if (targetOffset >= 0) { target = digester.peek(targetOffset); } else { target = digester.peek(digester.getCount() + targetOffset); } if (target == null) { StringBuilder sb = new StringBuilder(); sb.append("[CallMethodRule]{"); sb.append(""); sb.append("} Call target is null ("); sb.append("targetOffset="); sb.append(targetOffset); sb.append(",stackdepth="); sb.append(digester.getCount()); sb.append(")"); throw new org.xml.sax.SAXException(sb.toString()); } if (multiParams == null) { paramValues[multiParamIndex] = null; IntrospectionUtils.callMethodN(target, methodName, paramValues, paramTypes); return; } for (int j = 0; j < multiParams.size(); j++) { Object param = multiParams.get(j); if(param == null || (param instanceof String && !String.class.isAssignableFrom(paramTypes[multiParamIndex]))) { paramValues[multiParamIndex] = IntrospectionUtils.convert((String) param, paramTypes[multiParamIndex]); } else { paramValues[multiParamIndex] = param; } IntrospectionUtils.callMethodN(target, methodName, paramValues, paramTypes); } }
// in java/org/apache/catalina/util/SchemaResolver.java
Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { if (publicId != null) { digester.setPublicId(publicId); } // Has this system identifier been registered? String entityURL = null; if (publicId != null) { entityURL = entityValidator.get(publicId); } // Redirect the schema location to a local destination String key = null; if (entityURL == null && systemId != null) { key = systemId.substring(systemId.lastIndexOf('/')+1); entityURL = entityValidator.get(key); } if (entityURL == null) { return (null); } try { return (new InputSource(entityURL)); } catch (Exception e) { throw new SAXException(e); } }
7
              
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { throw new SAXException( Localizer.getMessage("jsp.error.loadclass.taghandler", handlerClassName, qName), e); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { throw new SAXException(e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/catalina/util/SchemaResolver.java
catch (Exception e) { throw new SAXException(e); }
55
              
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void addInclude(Node parent, List<String> files) throws SAXException { if (files != null) { Iterator<String> iter = files.iterator(); while (iter.hasNext()) { String file = iter.next(); AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute("", "file", "file", "CDATA", file); // Create a dummy Include directive node Node includeDir = new Node.IncludeDirective(attrs, null, // XXX parent); processIncludeDirective(file, includeDir); } } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void startElement( String uri, String localName, String qName, Attributes attrs) throws SAXException { AttributesImpl taglibAttrs = null; AttributesImpl nonTaglibAttrs = null; AttributesImpl nonTaglibXmlnsAttrs = null; processChars(); checkPrefixes(uri, qName, attrs); if (directivesOnly && !(JSP_URI.equals(uri) && localName.startsWith(DIRECTIVE_ACTION))) { return; } String currentPrefix = getPrefix(current.getQName()); // jsp:text must not have any subelements if (JSP_URI.equals(uri) && TEXT_ACTION.equals(current.getLocalName()) && "jsp".equals(currentPrefix)) { throw new SAXParseException( Localizer.getMessage("jsp.error.text.has_subelement"), locator); } startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); if (attrs != null) { /* * Notice that due to a bug in the underlying SAX parser, the * attributes must be enumerated in descending order. */ boolean isTaglib = false; for (int i = attrs.getLength() - 1; i >= 0; i--) { isTaglib = false; String attrQName = attrs.getQName(i); if (!attrQName.startsWith("xmlns")) { if (nonTaglibAttrs == null) { nonTaglibAttrs = new AttributesImpl(); } nonTaglibAttrs.addAttribute( attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getValue(i)); } else { if (attrQName.startsWith("xmlns:jsp")) { isTaglib = true; } else { String attrUri = attrs.getValue(i); // TaglibInfo for this uri already established in // startPrefixMapping isTaglib = pageInfo.hasTaglib(attrUri); } if (isTaglib) { if (taglibAttrs == null) { taglibAttrs = new AttributesImpl(); } taglibAttrs.addAttribute( attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getValue(i)); } else { if (nonTaglibXmlnsAttrs == null) { nonTaglibXmlnsAttrs = new AttributesImpl(); } nonTaglibXmlnsAttrs.addAttribute( attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getValue(i)); } } } } Node node = null; if (tagDependentPending && JSP_URI.equals(uri) && localName.equals(BODY_ACTION)) { tagDependentPending = false; tagDependentNesting++; current = parseStandardAction( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark); return; } if (tagDependentPending && JSP_URI.equals(uri) && localName.equals(ATTRIBUTE_ACTION)) { current = parseStandardAction( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark); return; } if (tagDependentPending) { tagDependentPending = false; tagDependentNesting++; } if (tagDependentNesting > 0) { node = new Node.UninterpretedTag( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark, current); } else if (JSP_URI.equals(uri)) { node = parseStandardAction( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark); } else { node = parseCustomAction( qName, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark, current); if (node == null) { node = new Node.UninterpretedTag( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark, current); } else { // custom action String bodyType = getBodyType((Node.CustomTag) node); if (scriptlessBodyNode == null && bodyType.equalsIgnoreCase(TagInfo.BODY_CONTENT_SCRIPTLESS)) { scriptlessBodyNode = node; } else if (TagInfo.BODY_CONTENT_TAG_DEPENDENT.equalsIgnoreCase(bodyType)) { tagDependentPending = true; } } } current = node; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void processChars() throws SAXException { if (charBuffer == null || directivesOnly) { return; } /* * JSP.6.1.1: All textual nodes that have only white space are to be * dropped from the document, except for nodes in a jsp:text element, * and any leading and trailing white-space-only textual nodes in a * jsp:attribute whose 'trim' attribute is set to FALSE, which are to * be kept verbatim. * JSP.6.2.3 defines white space characters. */ boolean isAllSpace = true; if (!(current instanceof Node.JspText) && !(current instanceof Node.NamedAttribute)) { for (int i = 0; i < charBuffer.length(); i++) { if (!(charBuffer.charAt(i) == ' ' || charBuffer.charAt(i) == '\n' || charBuffer.charAt(i) == '\r' || charBuffer.charAt(i) == '\t')) { isAllSpace = false; break; } } } if (!isAllSpace && tagDependentPending) { tagDependentPending = false; tagDependentNesting++; } if (tagDependentNesting > 0) { if (charBuffer.length() > 0) { new Node.TemplateText(charBuffer.toString(), startMark, current); } startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); charBuffer = null; return; } if ((current instanceof Node.JspText) || (current instanceof Node.NamedAttribute) || !isAllSpace) { int line = startMark.getLineNumber(); int column = startMark.getColumnNumber(); CharArrayWriter ttext = new CharArrayWriter(); int lastCh = 0, elType = 0; for (int i = 0; i < charBuffer.length(); i++) { int ch = charBuffer.charAt(i); if (ch == '\n') { column = 1; line++; } else { column++; } if ((lastCh == '$' || lastCh == '#') && ch == '{') { elType = lastCh; if (ttext.size() > 0) { new Node.TemplateText( ttext.toString(), startMark, current); ttext = new CharArrayWriter(); //We subtract two from the column number to //account for the '[$,#]{' that we've already parsed startMark = new Mark(ctxt, path, line, column - 2); } // following "${" || "#{" to first unquoted "}" i++; boolean singleQ = false; boolean doubleQ = false; lastCh = 0; for (;; i++) { if (i >= charBuffer.length()) { throw new SAXParseException( Localizer.getMessage( "jsp.error.unterminated", (char) elType + "{"), locator); } ch = charBuffer.charAt(i); if (ch == '\n') { column = 1; line++; } else { column++; } if (lastCh == '\\' && (singleQ || doubleQ)) { ttext.write(ch); lastCh = 0; continue; } if (ch == '}') { new Node.ELExpression((char) elType, ttext.toString(), startMark, current); ttext = new CharArrayWriter(); startMark = new Mark(ctxt, path, line, column); break; } if (ch == '"') doubleQ = !doubleQ; else if (ch == '\'') singleQ = !singleQ; ttext.write(ch); lastCh = ch; } } else if (lastCh == '\\' && (ch == '$' || ch == '#')) { if (pageInfo.isELIgnored()) { ttext.write('\\'); } ttext.write(ch); ch = 0; // Not start of EL anymore } else { if (lastCh == '$' || lastCh == '#' || lastCh == '\\') { ttext.write(lastCh); } if (ch != '$' && ch != '#' && ch != '\\') { ttext.write(ch); } } lastCh = ch; } if (lastCh == '$' || lastCh == '#' || lastCh == '\\') { ttext.write(lastCh); } if (ttext.size() > 0) { new Node.TemplateText(ttext.toString(), startMark, current); } } startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); charBuffer = null; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void endElement(String uri, String localName, String qName) throws SAXException { processChars(); if (directivesOnly && !(JSP_URI.equals(uri) && localName.startsWith(DIRECTIVE_ACTION))) { return; } if (current instanceof Node.NamedAttribute) { boolean isTrim = ((Node.NamedAttribute)current).isTrim(); Node.Nodes subElems = ((Node.NamedAttribute)current).getBody(); for (int i = 0; subElems != null && i < subElems.size(); i++) { Node subElem = subElems.getNode(i); if (!(subElem instanceof Node.TemplateText)) { continue; } // Ignore any whitespace (including spaces, carriage returns, // line feeds, and tabs, that appear at the beginning and at // the end of the body of the <jsp:attribute> action, if the // action's 'trim' attribute is set to TRUE (default). // In addition, any textual nodes in the <jsp:attribute> that // have only white space are dropped from the document, with // the exception of leading and trailing white-space-only // textual nodes in a <jsp:attribute> whose 'trim' attribute // is set to FALSE, which must be kept verbatim. if (i == 0) { if (isTrim) { ((Node.TemplateText)subElem).ltrim(); } } else if (i == subElems.size() - 1) { if (isTrim) { ((Node.TemplateText)subElem).rtrim(); } } else { if (((Node.TemplateText)subElem).isAllSpace()) { subElems.remove(subElem); } } } } else if (current instanceof Node.ScriptingElement) { checkScriptingBody((Node.ScriptingElement)current); } if ( isTagDependent(current)) { tagDependentNesting--; } if (scriptlessBodyNode != null && current.equals(scriptlessBodyNode)) { scriptlessBodyNode = null; } if (current instanceof Node.CustomTag) { String bodyType = getBodyType((Node.CustomTag) current); if (TagInfo.BODY_CONTENT_EMPTY.equalsIgnoreCase(bodyType)) { // Children - if any - must be JSP attributes Node.Nodes children = current.getBody(); if (children != null && children.size() > 0) { for (int i = 0; i < children.size(); i++) { Node child = children.getNode(i); if (!(child instanceof Node.NamedAttribute)) { throw new SAXParseException(Localizer.getMessage( "jasper.error.emptybodycontent.nonempty", current.qName), locator); } } } } } if (current.getParent() != null) { current = current.getParent(); } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void comment(char[] buf, int offset, int len) throws SAXException { processChars(); // Flush char buffer and remove white spaces // ignore comments in the DTD if (!inDTD) { startMark = new Mark( ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); new Node.Comment(new String(buf, offset, len), startMark, current); } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void startCDATA() throws SAXException { processChars(); // Flush char buffer and remove white spaces startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void endCDATA() throws SAXException { processChars(); // Flush char buffer and remove white spaces }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void startEntity(String name) throws SAXException { // do nothing }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void endEntity(String name) throws SAXException { // do nothing }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void startDTD(String name, String publicId, String systemId) throws SAXException { if (!isValidating) { fatalError(new EnableDTDValidationException( "jsp.error.enable_dtd_validation", null)); } inDTD = true; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void endDTD() throws SAXException { inDTD = false; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void fatalError(SAXParseException e) throws SAXException { throw e; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void error(SAXParseException e) throws SAXException { throw e; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void startPrefixMapping(String prefix, String uri) throws SAXException { TagLibraryInfo taglibInfo; if (directivesOnly && !(JSP_URI.equals(uri))) { return; } try { taglibInfo = getTaglibInfo(prefix, uri); } catch (JasperException je) { throw new SAXParseException( Localizer.getMessage("jsp.error.could.not.add.taglibraries"), locator, je); } if (taglibInfo != null) { if (pageInfo.getTaglib(uri) == null) { pageInfo.addTaglib(uri, taglibInfo); } pageInfo.pushPrefixMapping(prefix, uri); } else { pageInfo.pushPrefixMapping(prefix, null); } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void endPrefixMapping(String prefix) throws SAXException { if (directivesOnly) { String uri = pageInfo.getURI(prefix); if (!JSP_URI.equals(uri)) { return; } } pageInfo.popPrefixMapping(prefix); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private Node parseStandardAction( String qName, String localName, Attributes nonTaglibAttrs, Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs, Mark start) throws SAXException { Node node = null; if (localName.equals(ROOT_ACTION)) { if (!(current instanceof Node.Root)) { throw new SAXParseException( Localizer.getMessage("jsp.error.nested_jsproot"), locator); } node = new Node.JspRoot( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); if (isTop) { pageInfo.setHasJspRoot(true); } } else if (localName.equals(PAGE_DIRECTIVE_ACTION)) { if (isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.istagfile", localName), locator); } node = new Node.PageDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); String imports = nonTaglibAttrs.getValue("import"); // There can only be one 'import' attribute per page directive if (imports != null) { ((Node.PageDirective)node).addImport(imports); } } else if (localName.equals(INCLUDE_DIRECTIVE_ACTION)) { node = new Node.IncludeDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); processIncludeDirective(nonTaglibAttrs.getValue("file"), node); } else if (localName.equals(DECLARATION_ACTION)) { if (scriptlessBodyNode != null) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException( Localizer.getMessage( "jsp.error.no.scriptlets", localName), locator); } node = new Node.Declaration( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(SCRIPTLET_ACTION)) { if (scriptlessBodyNode != null) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException( Localizer.getMessage( "jsp.error.no.scriptlets", localName), locator); } node = new Node.Scriptlet( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(EXPRESSION_ACTION)) { if (scriptlessBodyNode != null) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException( Localizer.getMessage( "jsp.error.no.scriptlets", localName), locator); } node = new Node.Expression( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(USE_BEAN_ACTION)) { node = new Node.UseBean( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(SET_PROPERTY_ACTION)) { node = new Node.SetProperty( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(GET_PROPERTY_ACTION)) { node = new Node.GetProperty( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(INCLUDE_ACTION)) { node = new Node.IncludeAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(FORWARD_ACTION)) { node = new Node.ForwardAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(PARAM_ACTION)) { node = new Node.ParamAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(PARAMS_ACTION)) { node = new Node.ParamsAction( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(PLUGIN_ACTION)) { node = new Node.PlugIn( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(TEXT_ACTION)) { node = new Node.JspText( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(BODY_ACTION)) { node = new Node.JspBody( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(ATTRIBUTE_ACTION)) { node = new Node.NamedAttribute( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(OUTPUT_ACTION)) { node = new Node.JspOutput( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(TAG_DIRECTIVE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.TagDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); String imports = nonTaglibAttrs.getValue("import"); // There can only be one 'import' attribute per tag directive if (imports != null) { ((Node.TagDirective)node).addImport(imports); } } else if (localName.equals(ATTRIBUTE_DIRECTIVE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.AttributeDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(VARIABLE_DIRECTIVE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.VariableDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(INVOKE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.InvokeAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(DOBODY_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.DoBodyAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(ELEMENT_ACTION)) { node = new Node.JspElement( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(FALLBACK_ACTION)) { node = new Node.FallBackAction( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else { throw new SAXParseException( Localizer.getMessage( "jsp.error.xml.badStandardAction", localName), locator); } return node; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private Node parseCustomAction( String qName, String localName, String uri, Attributes nonTaglibAttrs, Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs, Mark start, Node parent) throws SAXException { // Check if this is a user-defined (custom) tag TagLibraryInfo tagLibInfo = pageInfo.getTaglib(uri); if (tagLibInfo == null) { return null; } TagInfo tagInfo = tagLibInfo.getTag(localName); TagFileInfo tagFileInfo = tagLibInfo.getTagFile(localName); if (tagInfo == null && tagFileInfo == null) { throw new SAXException( Localizer.getMessage("jsp.error.xml.bad_tag", localName, uri)); } Class<?> tagHandlerClass = null; if (tagInfo != null) { String handlerClassName = tagInfo.getTagClassName(); try { tagHandlerClass = ctxt.getClassLoader().loadClass(handlerClassName); } catch (Exception e) { throw new SAXException( Localizer.getMessage("jsp.error.loadclass.taghandler", handlerClassName, qName), e); } } String prefix = getPrefix(qName); Node.CustomTag ret = null; if (tagInfo != null) { ret = new Node.CustomTag( qName, prefix, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, parent, tagInfo, tagHandlerClass); } else { ret = new Node.CustomTag( qName, prefix, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, parent, tagFileInfo); } return ret; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void checkScriptingBody(Node.ScriptingElement scriptingElem) throws SAXException { Node.Nodes body = scriptingElem.getBody(); if (body != null) { int size = body.size(); for (int i = 0; i < size; i++) { Node n = body.getNode(i); if (!(n instanceof Node.TemplateText)) { String elemType = SCRIPTLET_ACTION; if (scriptingElem instanceof Node.Declaration) elemType = DECLARATION_ACTION; if (scriptingElem instanceof Node.Expression) elemType = EXPRESSION_ACTION; String msg = Localizer.getMessage( "jsp.error.parse.xml.scripting.invalid.body", elemType); throw new SAXException(msg); } } } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void processIncludeDirective(String fname, Node parent) throws SAXException { if (fname == null) { return; } try { parserController.parse(fname, parent, null); } catch (FileNotFoundException fnfe) { throw new SAXParseException( Localizer.getMessage("jsp.error.file.not.found", fname), locator, fnfe); } catch (Exception e) { throw new SAXException(e); } }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { for (int i = 0; i < Constants.CACHED_DTD_PUBLIC_IDS.size(); i++) { String cachedDtdPublicId = Constants.CACHED_DTD_PUBLIC_IDS.get(i); if (cachedDtdPublicId.equals(publicId)) { String resourcePath = Constants.CACHED_DTD_RESOURCE_PATHS.get(i); InputStream input = this.getClass().getResourceAsStream( resourcePath); if (input == null) { throw new SAXException(Localizer.getMessage( "jsp.error.internal.filenotfound", resourcePath)); } InputSource isrc = new InputSource(input); return isrc; } } Log log = LogFactory.getLog(MyEntityResolver.class); if (log.isDebugEnabled()) log.debug("Resolve entity failed" + publicId + " " + systemId); log.error(Localizer.getMessage("jsp.error.parse.xml.invalidPublicId", publicId)); return null; }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
Override public void warning(SAXParseException ex) throws SAXException { Log log = LogFactory.getLog(MyErrorHandler.class); if (log.isDebugEnabled()) log.debug("ParserUtils: warning ", ex); // We ignore warnings }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
Override public void error(SAXParseException ex) throws SAXException { throw ex; }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
Override public void fatalError(SAXParseException ex) throws SAXException { throw ex; }
// in java/org/apache/tomcat/util/digester/Digester.java
public XMLReader getXMLReader() throws SAXException { if (reader == null){ reader = getParser().getXMLReader(); } reader.setDTDHandler(this); reader.setContentHandler(this); if (entityResolver == null){ reader.setEntityResolver(this); } else { reader.setEntityResolver(entityResolver); } reader.setErrorHandler(this); return reader; }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void characters(char buffer[], int start, int length) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("characters(" + new String(buffer, start, length) + ")"); } bodyText.append(buffer, start, length); }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void endDocument() throws SAXException { if (saxLog.isDebugEnabled()) { if (getCount() > 1) { saxLog.debug("endDocument(): " + getCount() + " elements left"); } else { saxLog.debug("endDocument()"); } } while (getCount() > 1) { pop(); } // Fire "finish" events for all defined rules Iterator<Rule> rules = getRules().rules().iterator(); while (rules.hasNext()) { Rule rule = rules.next(); try { rule.finish(); } catch (Exception e) { log.error("Finish event threw exception", e); throw createSAXException(e); } catch (Error e) { log.error("Finish event threw error", e); throw e; } } // Perform final cleanup clear(); }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { boolean debug = log.isDebugEnabled(); if (debug) { if (saxLog.isDebugEnabled()) { saxLog.debug("endElement(" + namespaceURI + "," + localName + "," + qName + ")"); } log.debug(" match='" + match + "'"); log.debug(" bodyText='" + bodyText + "'"); } // Parse system properties bodyText = updateBodyText(bodyText); // the actual element name is either in localName or qName, depending // on whether the parser is namespace aware String name = localName; if ((name == null) || (name.length() < 1)) { name = qName; } // Fire "body" events for all relevant rules List<Rule> rules = matches.pop(); if ((rules != null) && (rules.size() > 0)) { String bodyText = this.bodyText.toString(); for (int i = 0; i < rules.size(); i++) { try { Rule rule = rules.get(i); if (debug) { log.debug(" Fire body() for " + rule); } rule.body(namespaceURI, name, bodyText); } catch (Exception e) { log.error("Body event threw exception", e); throw createSAXException(e); } catch (Error e) { log.error("Body event threw error", e); throw e; } } } else { if (debug) { log.debug(" No rules found matching '" + match + "'."); } if (rulesValidation) { log.warn(" No rules found matching '" + match + "'."); } } // Recover the body text from the surrounding element bodyText = bodyTexts.pop(); if (debug) { log.debug(" Popping body text '" + bodyText.toString() + "'"); } // Fire "end" events for all relevant rules in reverse order if (rules != null) { for (int i = 0; i < rules.size(); i++) { int j = (rules.size() - i) - 1; try { Rule rule = rules.get(j); if (debug) { log.debug(" Fire end() for " + rule); } rule.end(namespaceURI, name); } catch (Exception e) { log.error("End event threw exception", e); throw createSAXException(e); } catch (Error e) { log.error("End event threw error", e); throw e; } } } // Recover the previous match expression int slash = match.lastIndexOf('/'); if (slash >= 0) { match = match.substring(0, slash); } else { match = ""; } }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void endPrefixMapping(String prefix) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("endPrefixMapping(" + prefix + ")"); } // Deregister this prefix mapping ArrayStack<String> stack = namespaces.get(prefix); if (stack == null) { return; } try { stack.pop(); if (stack.empty()) namespaces.remove(prefix); } catch (EmptyStackException e) { throw createSAXException("endPrefixMapping popped too many times"); } }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void ignorableWhitespace(char buffer[], int start, int len) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("ignorableWhitespace(" + new String(buffer, start, len) + ")"); } // No processing required }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void processingInstruction(String target, String data) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("processingInstruction('" + target + "','" + data + "')"); } // No processing is required }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void skippedEntity(String name) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("skippedEntity(" + name + ")"); } // No processing required }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void startDocument() throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("startDocument()"); } // ensure that the digester is properly configured, as // the digester could be used as a SAX ContentHandler // rather than via the parse() methods. configure(); }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void startElement(String namespaceURI, String localName, String qName, Attributes list) throws SAXException { boolean debug = log.isDebugEnabled(); if (saxLog.isDebugEnabled()) { saxLog.debug("startElement(" + namespaceURI + "," + localName + "," + qName + ")"); } // Parse system properties list = updateAttributes(list); // Save the body text accumulated for our surrounding element bodyTexts.push(bodyText); if (debug) { log.debug(" Pushing body text '" + bodyText.toString() + "'"); } bodyText = new StringBuilder(); // the actual element name is either in localName or qName, depending // on whether the parser is namespace aware String name = localName; if ((name == null) || (name.length() < 1)) { name = qName; } // Compute the current matching rule StringBuilder sb = new StringBuilder(match); if (match.length() > 0) { sb.append('/'); } sb.append(name); match = sb.toString(); if (debug) { log.debug(" New match='" + match + "'"); } // Fire "begin" events for all relevant rules List<Rule> rules = getRules().match(namespaceURI, match); matches.push(rules); if ((rules != null) && (rules.size() > 0)) { for (int i = 0; i < rules.size(); i++) { try { Rule rule = rules.get(i); if (debug) { log.debug(" Fire begin() for " + rule); } rule.begin(namespaceURI, name, list); } catch (Exception e) { log.error("Begin event threw exception", e); throw createSAXException(e); } catch (Error e) { log.error("Begin event threw error", e); throw e; } } } else { if (debug) { log.debug(" No rules found matching '" + match + "'."); } } }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void startPrefixMapping(String prefix, String namespaceURI) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("startPrefixMapping(" + prefix + "," + namespaceURI + ")"); } // Register this prefix mapping ArrayStack<String> stack = namespaces.get(prefix); if (stack == null) { stack = new ArrayStack<String>(); namespaces.put(prefix, stack); } stack.push(namespaceURI); }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("resolveEntity('" + publicId + "', '" + systemId + "')"); } if (publicId != null) this.publicId = publicId; // Has this system identifier been registered? String entityURL = null; if (publicId != null) { entityURL = entityValidator.get(publicId); } if (entityURL == null) { if (systemId == null) { // cannot resolve if (log.isDebugEnabled()) { log.debug(" Cannot resolve entity: '" + publicId + "'"); } return (null); } else { // try to resolve using system ID if (log.isDebugEnabled()) { log.debug(" Trying to resolve using system ID '" + systemId + "'"); } entityURL = systemId; } } // Return an input source to our alternative URL if (log.isDebugEnabled()) { log.debug(" Resolving to alternate DTD '" + entityURL + "'"); } try { return (new InputSource(entityURL)); } catch (Exception e) { throw createSAXException(e); } }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void error(SAXParseException exception) throws SAXException { log.error("Parse Error at line " + exception.getLineNumber() + " column " + exception.getColumnNumber() + ": " + exception.getMessage(), exception); if (errorHandler != null) { errorHandler.error(exception); } }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void fatalError(SAXParseException exception) throws SAXException { log.error("Parse Fatal Error at line " + exception.getLineNumber() + " column " + exception.getColumnNumber() + ": " + exception.getMessage(), exception); if (errorHandler != null) { errorHandler.fatalError(exception); } }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void warning(SAXParseException exception) throws SAXException { if (errorHandler != null) { log.warn("Parse Warning Error at line " + exception.getLineNumber() + " column " + exception.getColumnNumber() + ": " + exception.getMessage(), exception); errorHandler.warning(exception); } }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(File file) throws IOException, SAXException { configure(); InputSource input = new InputSource(new FileInputStream(file)); input.setSystemId("file://" + file.getAbsolutePath()); getXMLReader().parse(input); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(InputSource input) throws IOException, SAXException { configure(); getXMLReader().parse(input); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(InputStream input) throws IOException, SAXException { configure(); InputSource is = new InputSource(input); getXMLReader().parse(is); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(Reader reader) throws IOException, SAXException { configure(); InputSource is = new InputSource(reader); getXMLReader().parse(is); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(String uri) throws IOException, SAXException { configure(); InputSource is = new InputSource(uri); getXMLReader().parse(is); return (root); }
// in java/org/apache/tomcat/util/digester/XercesParser.java
public static SAXParser newSAXParser(Properties properties) throws ParserConfigurationException, SAXException, SAXNotSupportedException { SAXParserFactory factory = (SAXParserFactory)properties.get("SAXParserFactory"); if (versionNumber == null){ versionNumber = getXercesVersion(); version = new Float( versionNumber ).floatValue(); } // Note: 2.2 is completely broken (with XML Schema). if (version > 2.1) { configureXerces(factory); return factory.newSAXParser(); } else { SAXParser parser = factory.newSAXParser(); configureOldXerces(parser,properties); return parser; } }
// in java/org/apache/tomcat/util/digester/ParserFeatureSetterFactory.java
public static SAXParser newSAXParser(Properties properties) throws ParserConfigurationException, SAXException, SAXNotRecognizedException, SAXNotSupportedException { if (isXercesUsed){ return XercesParser.newSAXParser(properties); } else { return GenericParser.newSAXParser(properties); } }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void characters(char[] ch, int start, int length) throws SAXException { try { String str = new String(ch, start, length); if (str.trim().length() > 0) { top.appendChild(doc.createTextNode(str)); } } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { try { if (depth == 0) { getDigester().getXMLReader().setContentHandler( oldContentHandler); getDigester().push(root); getDigester().endElement(namespaceURI, localName, qName); } top = top.getParentNode(); depth--; } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void processingInstruction(String target, String data) throws SAXException { try { top.appendChild(doc.createProcessingInstruction(target, data)); } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { try { Node previousTop = top; if ((localName == null) || (localName.length() == 0)) { top = doc.createElement(qName); } else { top = doc.createElementNS(namespaceURI, localName); } for (int i = 0; i < atts.getLength(); i++) { Attr attr = null; if ((atts.getLocalName(i) == null) || (atts.getLocalName(i).length() == 0)) { attr = doc.createAttribute(atts.getQName(i)); attr.setNodeValue(atts.getValue(i)); ((Element)top).setAttributeNode(attr); } else { attr = doc.createAttributeNS(atts.getURI(i), atts.getLocalName(i)); attr.setNodeValue(atts.getValue(i)); ((Element)top).setAttributeNodeNS(attr); } } previousTop.appendChild(top); depth++; } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/digester/GenericParser.java
public static SAXParser newSAXParser(Properties properties) throws ParserConfigurationException, SAXException, SAXNotRecognizedException{ SAXParserFactory factory = (SAXParserFactory)properties.get("SAXParserFactory"); SAXParser parser = factory.newSAXParser(); String schemaLocation = (String)properties.get("schemaLocation"); String schemaLanguage = (String)properties.get("schemaLanguage"); try{ if (schemaLocation != null) { parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage); parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation); } } catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); } return parser; }
// in java/org/apache/catalina/startup/XmlErrorHandler.java
Override public void error(SAXParseException exception) throws SAXException { // Collect non-fatal errors errors.add(exception); }
// in java/org/apache/catalina/startup/XmlErrorHandler.java
Override public void fatalError(SAXParseException exception) throws SAXException { // Re-throw fatal errors throw exception; }
// in java/org/apache/catalina/startup/XmlErrorHandler.java
Override public void warning(SAXParseException exception) throws SAXException { // Collect warnings warnings.add(exception); }
// in java/org/apache/catalina/util/SchemaResolver.java
Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { if (publicId != null) { digester.setPublicId(publicId); } // Has this system identifier been registered? String entityURL = null; if (publicId != null) { entityURL = entityValidator.get(publicId); } // Redirect the schema location to a local destination String key = null; if (entityURL == null && systemId != null) { key = systemId.substring(systemId.lastIndexOf('/')+1); entityURL = entityValidator.get(key); } if (entityURL == null) { return (null); } try { return (new InputSource(entityURL)); } catch (Exception e) { throw new SAXException(e); } }
(Domain) Error 10
              
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Throwable t) { throw new Error(t.getMessage()); } bufsize += 2048; available = bufsize; tokenBegin = 0; }
// in java/org/apache/el/parser/SimpleCharStream.java
protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Throwable t) { throw new Error(t.getMessage()); } bufsize += 2048; available = bufsize; tokenBegin = 0; }
// in java/org/apache/el/parser/ELParser.java
final public AstCompositeExpression CompositeExpression() throws ParseException { /*@bgen(jjtree) CompositeExpression */ AstCompositeExpression jjtn000 = new AstCompositeExpression(JJTCOMPOSITEEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { label_1: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LITERAL_EXPRESSION: case START_DYNAMIC_EXPRESSION: case START_DEFERRED_EXPRESSION: ; break; default: jj_la1[0] = jj_gen; break label_1; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case START_DEFERRED_EXPRESSION: DeferredExpression(); break; case START_DYNAMIC_EXPRESSION: DynamicExpression(); break; case LITERAL_EXPRESSION: LiteralExpression(); break; default: jj_la1[1] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } jj_consume_token(0); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; {if (true) return jjtn000;} } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } throw new Error("Missing return statement in function"); }
// in java/org/apache/catalina/startup/Catalina.java
public void load() { long t1 = System.nanoTime(); initDirs(); // Before digester - it may be needed initNaming(); // Create and execute our Digester Digester digester = createStartDigester(); InputSource inputSource = null; InputStream inputStream = null; File file = null; try { file = configFile(); inputStream = new FileInputStream(file); inputSource = new InputSource(file.toURI().toURL().toString()); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", file), e); } } if (inputStream == null) { try { inputStream = getClass().getClassLoader() .getResourceAsStream(getConfigFile()); inputSource = new InputSource (getClass().getClassLoader() .getResource(getConfigFile()).toString()); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", getConfigFile()), e); } } } // This should be included in catalina.jar // Alternative: don't bother with xml, just create it manually. if( inputStream==null ) { try { inputStream = getClass().getClassLoader() .getResourceAsStream("server-embed.xml"); inputSource = new InputSource (getClass().getClassLoader() .getResource("server-embed.xml").toString()); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", "server-embed.xml"), e); } } } if (inputStream == null || inputSource == null) { if (file == null) { log.warn(sm.getString("catalina.configFail", getConfigFile() + "] or [server-embed.xml]")); } else { log.warn(sm.getString("catalina.configFail", file.getAbsolutePath())); if (file.exists() && !file.canRead()) { log.warn("Permissions incorrect, read permission is not allowed on the file."); } } return; } try { inputSource.setByteStream(inputStream); digester.push(this); digester.parse(inputSource); } catch (SAXParseException spe) { log.warn("Catalina.start using " + getConfigFile() + ": " + spe.getMessage()); return; } catch (Exception e) { log.warn("Catalina.start using " + getConfigFile() + ": " , e); return; } finally { try { inputStream.close(); } catch (IOException e) { // Ignore } } getServer().setCatalina(this); getServer().setCatalinaHome(Bootstrap.getCatalinaHomeFile()); getServer().setCatalinaBase(Bootstrap.getCatalinaBaseFile()); // Stream redirection initStreams(); // Start the new server try { getServer().init(); } catch (LifecycleException e) { if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) { throw new java.lang.Error(e); } else { log.error("Catalina.start", e); } } long t2 = System.nanoTime(); if(log.isInfoEnabled()) { log.info("Initialization processed in " + ((t2 - t1) / 1000000) + " ms"); } }
// in java/org/apache/catalina/security/SecurityListener.java
protected void checkOsUser() { String userName = System.getProperty("user.name"); if (userName != null) { String userNameLC = userName.toLowerCase(); if (checkedOsUsers.contains(userNameLC)) { // Have to throw Error to force start process to be aborted throw new Error(sm.getString( "SecurityListener.checkUserWarning", userName)); } } }
// in java/org/apache/catalina/security/SecurityListener.java
protected void checkUmask() { String prop = System.getProperty(UMASK_PROPERTY_NAME); Integer umask = null; if (prop != null) { try { umask = Integer.valueOf(prop, 8); } catch (NumberFormatException nfe) { log.warn(sm.getString("SecurityListener.checkUmaskParseFail", prop)); } } if (umask == null) { if (Constants.CRLF.equals(Constants.LINE_SEP)) { // Probably running on Windows so no umask if (log.isDebugEnabled()) { log.debug(sm.getString("SecurityListener.checkUmaskSkip")); } return; } else { if (minimumUmask.intValue() > 0) { log.warn(sm.getString( "SecurityListener.checkUmaskNone", UMASK_PROPERTY_NAME, getMinimumUmask())); } return; } } if ((umask.intValue() & minimumUmask.intValue()) != minimumUmask.intValue()) { throw new Error(sm.getString("SecurityListener.checkUmaskFail", String.format(UMASK_FORMAT, umask), getMinimumUmask())); } }
// in java/javax/servlet/jsp/tagext/BodyContent.java
public void clearBody() { try { this.clear(); } catch (IOException ex) { // TODO -- clean this one up. throw new Error("internal error!;"); } }
4
              
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
// in java/org/apache/el/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) { throw new java.lang.Error(e); } else { log.error("Catalina.start", e); } }
// in java/javax/servlet/jsp/tagext/BodyContent.java
catch (IOException ex) { // TODO -- clean this one up. throw new Error("internal error!;"); }
0
(Lib) MalformedURLException 9
              
// in java/org/apache/jasper/servlet/JspCServletContext.java
Override public URL getResource(String path) throws MalformedURLException { if (!path.startsWith("/")) throw new MalformedURLException("Path '" + path + "' does not start with '/'"); URL url = new URL(myResourceBaseURL, path.substring(1)); InputStream is = null; try { is = url.openStream(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); url = null; } finally { if (is != null) { try { is.close(); } catch (Throwable t2) { ExceptionUtils.handleThrowable(t2); } } } return url; }
// in java/org/apache/tomcat/util/net/URL.java
public void normalize() throws MalformedURLException { // Special case for null path if (path == null) { if (query != null) file = "?" + query; else file = ""; return; } // Create a place for the normalized path String normalized = path; if (normalized.equals("/.")) { path = "/"; if (query != null) file = path + "?" + query; else file = path; return; } // Normalize the slashes and add leading slash if necessary if (normalized.indexOf('\\') >= 0) normalized = normalized.replace('\\', '/'); if (!normalized.startsWith("/")) normalized = "/" + normalized; // Resolve occurrences of "//" in the normalized path while (true) { int index = normalized.indexOf("//"); if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 1); } // Resolve occurrences of "/./" in the normalized path while (true) { int index = normalized.indexOf("/./"); if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 2); } // Resolve occurrences of "/../" in the normalized path while (true) { int index = normalized.indexOf("/../"); if (index < 0) break; if (index == 0) throw new MalformedURLException ("Invalid relative URL reference"); int index2 = normalized.lastIndexOf('/', index - 1); normalized = normalized.substring(0, index2) + normalized.substring(index + 3); } // Resolve occurrences of "/." at the end of the normalized path if (normalized.endsWith("/.")) normalized = normalized.substring(0, normalized.length() - 1); // Resolve occurrences of "/.." at the end of the normalized path if (normalized.endsWith("/..")) { int index = normalized.length() - 3; int index2 = normalized.lastIndexOf('/', index - 1); if (index2 < 0) throw new MalformedURLException ("Invalid relative URL reference"); normalized = normalized.substring(0, index2 + 1); } // Return the normalized path that we have completed path = normalized; if (query != null) file = path + "?" + query; else file = path; }
// in java/org/apache/tomcat/util/net/URL.java
private void parse(String spec, int start, int limit) throws MalformedURLException { // Trim the query string (if any) off the tail end int question = spec.lastIndexOf('?', limit - 1); if ((question >= 0) && (question < limit)) { query = spec.substring(question + 1, limit); limit = question; } else { query = null; } // Parse the authority section if (spec.indexOf("//", start) == start) { int pathStart = spec.indexOf("/", start + 2); if ((pathStart >= 0) && (pathStart < limit)) { authority = spec.substring(start + 2, pathStart); start = pathStart; } else { authority = spec.substring(start + 2, limit); start = limit; } if (authority.length() > 0) { int at = authority.indexOf('@'); if( at >= 0 ) { userInfo = authority.substring(0,at); } int ipv6 = authority.indexOf('[',at+1); int hStart = at+1; if( ipv6 >= 0 ) { hStart = ipv6; ipv6 = authority.indexOf(']', ipv6); if( ipv6 < 0 ) { throw new MalformedURLException( "Closing ']' not found in IPV6 address: " + authority); } else { at = ipv6-1; } } int colon = authority.indexOf(':', at+1); if (colon >= 0) { try { port = Integer.parseInt(authority.substring(colon + 1)); } catch (NumberFormatException e) { throw new MalformedURLException(e.toString()); } host = authority.substring(hStart, colon); } else { host = authority.substring(hStart); port = -1; } } } // Parse the path section if (spec.indexOf("/", start) == start) { // Absolute path path = spec.substring(start, limit); if (query != null) file = path + "?" + query; else file = path; return; } // Resolve relative path against our context's file if (path == null) { if (query != null) file = "?" + query; else file = null; return; } if (!path.startsWith("/")) throw new MalformedURLException ("Base path does not start with '/'"); if (!path.endsWith("/")) path += "/../"; path += spec.substring(start, limit); if (query != null) file = path + "?" + query; else file = path; return; }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public URL getResource(String path) throws MalformedURLException { if (path == null || !path.startsWith("/") && GET_RESOURCE_REQUIRE_SLASH) throw new MalformedURLException(sm.getString( "applicationContext.requestDispatcher.iae", path)); String normPath = RequestUtil.normalize(path); if (normPath == null) return (null); DirContext resources = context.getResources(); if (resources != null) { String fullPath = context.getPath() + normPath; String hostName = context.getParent().getName(); try { resources.lookup(normPath); return new URL ("jndi", "", 0, getJNDIUri(hostName, fullPath), new DirContextURLStreamHandler(resources)); } catch (NamingException e) { // Ignore } catch (Exception e) { // Unexpected log(sm.getString("applicationContext.lookup.error", path, getContextPath()), e); } } return (null); }
2
              
// in java/org/apache/tomcat/util/net/URL.java
catch (Exception e) { throw new MalformedURLException(e.toString()); }
// in java/org/apache/tomcat/util/net/URL.java
catch (NumberFormatException e) { throw new MalformedURLException(e.toString()); }
17
              
// in java/org/apache/jasper/compiler/Mark.java
public URL getURL() throws MalformedURLException { return ctxt.getResource(getFile()); }
// in java/org/apache/jasper/servlet/JspCServletContext.java
Override public URL getResource(String path) throws MalformedURLException { if (!path.startsWith("/")) throw new MalformedURLException("Path '" + path + "' does not start with '/'"); URL url = new URL(myResourceBaseURL, path.substring(1)); InputStream is = null; try { is = url.openStream(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); url = null; } finally { if (is != null) { try { is.close(); } catch (Throwable t2) { ExceptionUtils.handleThrowable(t2); } } } return url; }
// in java/org/apache/jasper/JspCompilationContext.java
public URL getResource(String res) throws MalformedURLException { URL result = null; if (res.startsWith("/META-INF/")) { // This is a tag file packaged in a jar that is being compiled JarResource jarResource = tagFileJarUrls.get(res); if (jarResource == null) { jarResource = tagJarResource; } if (jarResource != null) { result = jarResource.getEntry(res.substring(1)); } else { // May not be in a JAR in some IDE environments result = context.getResource(canonicalURI(res)); } } else if (res.startsWith("jar:jndi:")) { // This is a tag file packaged in a jar that is being checked // for a dependency result = new URL(res); } else { result = context.getResource(canonicalURI(res)); } return result; }
// in java/org/apache/tomcat/util/net/URL.java
public void normalize() throws MalformedURLException { // Special case for null path if (path == null) { if (query != null) file = "?" + query; else file = ""; return; } // Create a place for the normalized path String normalized = path; if (normalized.equals("/.")) { path = "/"; if (query != null) file = path + "?" + query; else file = path; return; } // Normalize the slashes and add leading slash if necessary if (normalized.indexOf('\\') >= 0) normalized = normalized.replace('\\', '/'); if (!normalized.startsWith("/")) normalized = "/" + normalized; // Resolve occurrences of "//" in the normalized path while (true) { int index = normalized.indexOf("//"); if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 1); } // Resolve occurrences of "/./" in the normalized path while (true) { int index = normalized.indexOf("/./"); if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 2); } // Resolve occurrences of "/../" in the normalized path while (true) { int index = normalized.indexOf("/../"); if (index < 0) break; if (index == 0) throw new MalformedURLException ("Invalid relative URL reference"); int index2 = normalized.lastIndexOf('/', index - 1); normalized = normalized.substring(0, index2) + normalized.substring(index + 3); } // Resolve occurrences of "/." at the end of the normalized path if (normalized.endsWith("/.")) normalized = normalized.substring(0, normalized.length() - 1); // Resolve occurrences of "/.." at the end of the normalized path if (normalized.endsWith("/..")) { int index = normalized.length() - 3; int index2 = normalized.lastIndexOf('/', index - 1); if (index2 < 0) throw new MalformedURLException ("Invalid relative URL reference"); normalized = normalized.substring(0, index2 + 1); } // Return the normalized path that we have completed path = normalized; if (query != null) file = path + "?" + query; else file = path; }
// in java/org/apache/tomcat/util/net/URL.java
private void parse(String spec, int start, int limit) throws MalformedURLException { // Trim the query string (if any) off the tail end int question = spec.lastIndexOf('?', limit - 1); if ((question >= 0) && (question < limit)) { query = spec.substring(question + 1, limit); limit = question; } else { query = null; } // Parse the authority section if (spec.indexOf("//", start) == start) { int pathStart = spec.indexOf("/", start + 2); if ((pathStart >= 0) && (pathStart < limit)) { authority = spec.substring(start + 2, pathStart); start = pathStart; } else { authority = spec.substring(start + 2, limit); start = limit; } if (authority.length() > 0) { int at = authority.indexOf('@'); if( at >= 0 ) { userInfo = authority.substring(0,at); } int ipv6 = authority.indexOf('[',at+1); int hStart = at+1; if( ipv6 >= 0 ) { hStart = ipv6; ipv6 = authority.indexOf(']', ipv6); if( ipv6 < 0 ) { throw new MalformedURLException( "Closing ']' not found in IPV6 address: " + authority); } else { at = ipv6-1; } } int colon = authority.indexOf(':', at+1); if (colon >= 0) { try { port = Integer.parseInt(authority.substring(colon + 1)); } catch (NumberFormatException e) { throw new MalformedURLException(e.toString()); } host = authority.substring(hStart, colon); } else { host = authority.substring(hStart); port = -1; } } } // Parse the path section if (spec.indexOf("/", start) == start) { // Absolute path path = spec.substring(start, limit); if (query != null) file = path + "?" + query; else file = path; return; } // Resolve relative path against our context's file if (path == null) { if (query != null) file = "?" + query; else file = null; return; } if (!path.startsWith("/")) throw new MalformedURLException ("Base path does not start with '/'"); if (!path.endsWith("/")) path += "/../"; path += spec.substring(start, limit); if (query != null) file = path + "?" + query; else file = path; return; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
protected URL getURL(File file, boolean encoded) throws MalformedURLException { File realFile = file; try { realFile = realFile.getCanonicalFile(); } catch (IOException e) { // Ignore } if(encoded) { return getURI(realFile); } return realFile.toURI().toURL(); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
protected URL getURI(File file) throws MalformedURLException { File realFile = file; try { realFile = realFile.getCanonicalFile(); } catch (IOException e) { // Ignore } return realFile.toURI().toURL(); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
public static MBeanServerConnection createJMXConnection(String url, String host, String port, String username, String password) throws MalformedURLException, IOException { String urlForJMX; if (url != null) urlForJMX = url; else urlForJMX = JMX_SERVICE_PREFIX + host + ":" + port + JMX_SERVICE_SUFFIX; Map<String, String[]> environment = null; if (username != null && password != null) { String[] credentials = new String[2]; credentials[0] = username; credentials[1] = password; environment = new HashMap<String, String[]>(); environment.put(JMXConnector.CREDENTIALS, credentials); } return JMXConnectorFactory.connect(new JMXServiceURL(urlForJMX), environment).getMBeanServerConnection(); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
protected MBeanServerConnection getJMXConnection() throws MalformedURLException, IOException { MBeanServerConnection jmxServerConnection = null; if (isUseRef()) { Object pref = null ; if(getProject() != null) { pref = getProject().getReference(getRef()); if (pref != null) { try { jmxServerConnection = (MBeanServerConnection) pref; } catch (ClassCastException cce) { getProject().log( "Wrong object reference " + getRef() + " - " + pref.getClass()); return null; } } } if (jmxServerConnection == null) { jmxServerConnection = accessJMXConnection(getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), getRef()); } } else { jmxServerConnection = accessJMXConnection(getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), null); } return jmxServerConnection; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorEqualsCondition.java
protected MBeanServerConnection getJMXConnection() throws MalformedURLException, IOException { return JMXAccessorTask.accessJMXConnection( getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), ref); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorCondition.java
protected MBeanServerConnection getJMXConnection() throws MalformedURLException, IOException { return JMXAccessorTask.accessJMXConnection( getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), ref); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public URL getResource(String path) throws MalformedURLException { if (path == null || !path.startsWith("/") && GET_RESOURCE_REQUIRE_SLASH) throw new MalformedURLException(sm.getString( "applicationContext.requestDispatcher.iae", path)); String normPath = RequestUtil.normalize(path); if (normPath == null) return (null); DirContext resources = context.getResources(); if (resources != null) { String fullPath = context.getPath() + normPath; String hostName = context.getParent().getName(); try { resources.lookup(normPath); return new URL ("jndi", "", 0, getJNDIUri(hostName, fullPath), new DirContextURLStreamHandler(resources)); } catch (NamingException e) { // Ignore } catch (Exception e) { // Unexpected log(sm.getString("applicationContext.lookup.error", path, getContextPath()), e); } } return (null); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
Override public URL getResource(String path) throws MalformedURLException { if (Globals.IS_SECURITY_ENABLED) { try { return (URL) invokeMethod(context, "getResource", new Object[]{path}); } catch(Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof MalformedURLException){ throw (MalformedURLException)t; } return null; } } else { return context.getResource(path); } }
(Lib) AttributeNotFoundException 6
              
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
Method getGetter(String aname, BaseModelMBean mbean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); // Look up the actual operation to be used if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname + " for " + resource); String getMethod = attrInfo.getGetMethod(); if (getMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " get method name"); Object object = null; NoSuchMethodException exception = null; try { object = mbean; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find getter method " + getMethod); return m; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getSetter(String aname, BaseModelMBean bean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname); // Look up the actual operation to be used String setMethod = attrInfo.getSetMethod(); if (setMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " set method name"); String argType=attrInfo.getType(); Class<?> signature[] = new Class[] { BaseModelMBean.getAttributeClass( argType ) }; Object object = null; NoSuchMethodException exception = null; try { object = bean; m = object.getClass().getMethod(setMethod, signature); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(setMethod, signature); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find setter method " + setMethod + " " + resource); return m; }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("auth".equals(name)) { return (cr.getAuth()); } else if ("description".equals(name)) { return (cr.getDescription()); } else if ("name".equals(name)) { return (cr.getName()); } else if ("scope".equals(name)) { return (cr.getScope()); } else if ("type".equals(name)) { return (cr.getType()); } else { value = (String) cr.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink cl = null; try { cl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("global".equals(name)) { return (cl.getGlobal()); } else if ("description".equals(name)) { return (cl.getDescription()); } else if ("name".equals(name)) { return (cl.getName()); } else if ("type".equals(name)) { return (cl.getType()); } else { value = (String) cl.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
0 11
              
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
Method getGetter(String aname, BaseModelMBean mbean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); // Look up the actual operation to be used if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname + " for " + resource); String getMethod = attrInfo.getGetMethod(); if (getMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " get method name"); Object object = null; NoSuchMethodException exception = null; try { object = mbean; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find getter method " + getMethod); return m; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getSetter(String aname, BaseModelMBean bean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname); // Look up the actual operation to be used String setMethod = attrInfo.getSetMethod(); if (setMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " set method name"); String argType=attrInfo.getType(); Class<?> signature[] = new Class[] { BaseModelMBean.getAttributeClass( argType ) }; Object object = null; NoSuchMethodException exception = null; try { object = bean; m = object.getClass().getMethod(setMethod, signature); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(setMethod, signature); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find setter method " + setMethod + " " + resource); return m; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).getAttribute(name); } Method m=managedBean.getGetter(name, this, resource); Object result = null; try { Class<?> declaring = m.getDeclaringClass(); // workaround for catalina weird mbeans - the declaring class is BaseModelMBean. // but this is the catalina class. if( declaring.isAssignableFrom(this.getClass()) ) { result = m.invoke(this, NO_ARGS_PARAM ); } else { result = m.invoke(resource, NO_ARGS_PARAM ); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if( log.isDebugEnabled() ) log.debug("Setting attribute " + this + " " + attribute ); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { try { ((DynamicMBean)resource).setAttribute(attribute); } catch (InvalidAttributeValueException e) { throw new MBeanException(e); } return; } // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); Object oldValue=null; //if( getAttMap.get(name) != null ) // oldValue=getAttribute( name ); Method m=managedBean.getSetter(name,this,resource); try { if( m.getDeclaringClass().isAssignableFrom( this.getClass()) ) { m.invoke(this, new Object[] { value }); } else { m.invoke(resource, new Object[] { value }); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } try { sendAttributeChangeNotification(new Attribute( name, oldValue), attribute); } catch(Exception ex) { log.error("Error sending notification " + name, ex); } //attributes.put( name, value ); // if( source != null ) { // // this mbean is associated with a source - maybe we want to persist // source.updateField(oname, name, value); // } }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); Object result = null; try { Connector connector = (Connector) getManagedResource(); result = IntrospectionUtils.getProperty(connector, name); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return result; }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); try { Connector connector = (Connector) getManagedResource(); IntrospectionUtils.setProperty(connector, name, String.valueOf(value)); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("auth".equals(name)) { return (cr.getAuth()); } else if ("description".equals(name)) { return (cr.getDescription()); } else if ("name".equals(name)) { return (cr.getName()); } else if ("scope".equals(name)) { return (cr.getScope()); } else if ("type".equals(name)) { return (cr.getType()); } else { value = (String) cr.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("auth".equals(name)) { cr.setAuth((String)value); } else if ("description".equals(name)) { cr.setDescription((String)value); } else if ("name".equals(name)) { cr.setName((String)value); } else if ("scope".equals(name)) { cr.setScope((String)value); } else if ("type".equals(name)) { cr.setType((String)value); } else { cr.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = cr.getNamingResources(); nr.removeResource(cr.getName()); nr.addResource(cr); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink cl = null; try { cl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("global".equals(name)) { return (cl.getGlobal()); } else if ("description".equals(name)) { return (cl.getDescription()); } else if ("name".equals(name)) { return (cl.getName()); } else if ("type".equals(name)) { return (cl.getType()); } else { value = (String) cl.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink crl = null; try { crl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("global".equals(name)) { crl.setGlobal((String)value); } else if ("description".equals(name)) { crl.setDescription((String)value); } else if ("name".equals(name)) { crl.setName((String)value); } else if ("type".equals(name)) { crl.setType((String)value); } else { crl.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = crl.getNamingResources(); nr.removeResourceLink(crl.getName()); nr.addResourceLink(crl); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { super.setAttribute(attribute); ContextEnvironment ce = null; try { ce = (ContextEnvironment) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = ce.getNamingResources(); nr.removeEnvironment(ce.getName()); nr.addEnvironment(ce); }
(Lib) CloneNotSupportedException 6
              
// in java/org/apache/catalina/connector/CoyoteOutputStream.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/CoyoteWriter.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
0 7
              
// in java/org/apache/tomcat/util/bcel/classfile/Constant.java
Override public Object clone() throws CloneNotSupportedException { return super.clone(); }
// in java/org/apache/catalina/connector/CoyoteOutputStream.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/CoyoteWriter.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
(Domain) JspELException 6
              
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public MethodInfo getMethodInfo(ELContext context) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.getMethodInfo(context); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public Object invoke(ELContext context, Object[] params) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.invoke(context, params); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Class<?> getType(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getType(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public boolean isReadOnly(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.isReadOnly(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void setValue(ELContext context, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { try { this.target.setValue(context, value); } catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Object getValue(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getValue(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
6
              
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
0
(Domain) JspPropertyNotFoundException 6
              
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public MethodInfo getMethodInfo(ELContext context) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.getMethodInfo(context); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public Object invoke(ELContext context, Object[] params) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.invoke(context, params); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Class<?> getType(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getType(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public boolean isReadOnly(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.isReadOnly(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void setValue(ELContext context, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { try { this.target.setValue(context, value); } catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Object getValue(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getValue(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
6
              
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
0
(Domain) MethodNotFoundException 6
              
// in java/org/apache/el/parser/AstIdentifier.java
private final MethodExpression getMethodExpression(EvaluationContext ctx) throws ELException { Object obj = null; // case A: ValueExpression exists, getValue which must // be a MethodExpression VariableMapper varMapper = ctx.getVariableMapper(); ValueExpression ve = null; if (varMapper != null) { ve = varMapper.resolveVariable(this.image); if (ve != null) { obj = ve.getValue(ctx); } } // case B: evaluate the identity against the ELResolver, again, must be // a MethodExpression to be able to invoke if (ve == null) { ctx.setPropertyResolved(false); obj = ctx.getELResolver().getValue(ctx, null, this.image); } // finally provide helpful hints if (obj instanceof MethodExpression) { return (MethodExpression) obj; } else if (obj == null) { throw new MethodNotFoundException("Identity '" + this.image + "' was null and was unable to invoke"); } else { throw new ELException( "Identity '" + this.image + "' does not reference a MethodExpression instance, returned type: " + obj.getClass().getName()); } }
// in java/javax/el/BeanELResolver.java
Override public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { if (context == null) { throw new NullPointerException(); } if (base == null || method == null) { return null; } ExpressionFactory factory = ExpressionFactory.newInstance(); String methodName = (String) factory.coerceToType(method, String.class); // Find the matching method Method matchingMethod = null; Class<?> clazz = base.getClass(); if (paramTypes != null) { try { matchingMethod = getMethod(clazz, clazz.getMethod(methodName, paramTypes)); } catch (NoSuchMethodException e) { throw new MethodNotFoundException(e); } } else { int paramCount = 0; if (params != null) { paramCount = params.length; } Method[] methods = clazz.getMethods(); for (Method m : methods) { if (methodName.equals(m.getName())) { if (m.getParameterTypes().length == paramCount) { // Same number of parameters - use the first match matchingMethod = getMethod(clazz, m); break; } if (m.isVarArgs() && paramCount > m.getParameterTypes().length - 2) { matchingMethod = getMethod(clazz, m); } } } if (matchingMethod == null) { throw new MethodNotFoundException( "Unable to find method [" + methodName + "] with [" + paramCount + "] parameters"); } } Class<?>[] parameterTypes = matchingMethod.getParameterTypes(); Object[] parameters = null; if (parameterTypes.length > 0) { parameters = new Object[parameterTypes.length]; @SuppressWarnings("null") // params.length >= parameterTypes.length int paramCount = params.length; if (matchingMethod.isVarArgs()) { int varArgIndex = parameterTypes.length - 1; // First argCount-1 parameters are standard for (int i = 0; (i < varArgIndex); i++) { parameters[i] = factory.coerceToType(params[i], parameterTypes[i]); } // Last parameter is the varargs Class<?> varArgClass = parameterTypes[varArgIndex].getComponentType(); final Object varargs = Array.newInstance( varArgClass, (paramCount - varArgIndex)); for (int i = (varArgIndex); i < paramCount; i++) { Array.set(varargs, i - varArgIndex, factory.coerceToType(params[i], varArgClass)); } parameters[varArgIndex] = varargs; } else { parameters = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { parameters[i] = factory.coerceToType(params[i], parameterTypes[i]); } } }
1
              
// in java/javax/el/BeanELResolver.java
catch (NoSuchMethodException e) { throw new MethodNotFoundException(e); }
4
              
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public MethodInfo getMethodInfo(ELContext context) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.getMethodInfo(context); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public Object invoke(ELContext context, Object[] params) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.invoke(context, params); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/el/MethodExpressionImpl.java
Override public MethodInfo getMethodInfo(ELContext context) throws PropertyNotFoundException, MethodNotFoundException, ELException { Node n = this.getNode(); EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return n.getMethodInfo(ctx, this.paramTypes); }
// in java/org/apache/el/MethodExpressionImpl.java
Override public Object invoke(ELContext context, Object[] params) throws PropertyNotFoundException, MethodNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return this.getNode().invoke(ctx, this.paramTypes, params); }
(Lib) RejectedExecutionException 6
              
// in java/org/apache/tomcat/util/threads/TaskQueue.java
public boolean force(Runnable o) { if ( parent.isShutdown() ) throw new RejectedExecutionException("Executor not running, can't force a command into the queue"); return super.offer(o); //forces the item onto the queue, to be used if the task is rejected }
// in java/org/apache/tomcat/util/threads/TaskQueue.java
public boolean force(Runnable o, long timeout, TimeUnit unit) throws InterruptedException { if ( parent.isShutdown() ) throw new RejectedExecutionException("Executor not running, can't force a command into the queue"); return super.offer(o,timeout,unit); //forces the item onto the queue, to be used if the task is rejected }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
public void execute(Runnable command, long timeout, TimeUnit unit) { submittedCount.incrementAndGet(); try { super.execute(command); } catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } } }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
Override public void rejectedExecution(Runnable r, java.util.concurrent.ThreadPoolExecutor executor) { throw new RejectedExecutionException(); }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
Override public void execute(Runnable command) { if ( executor != null ) { try { executor.execute(command); } catch (RejectedExecutionException rx) { //there could have been contention around the queue if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException("Work queue full."); } } else throw new IllegalStateException("StandardThreadPool not started."); }
3
              
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
catch (RejectedExecutionException rx) { //there could have been contention around the queue if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException("Work queue full."); }
0
(Lib) SocketTimeoutException 6
              
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
protected boolean fill() throws IOException { int nRead = 0; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.EAGAIN) { return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } else { if (buf.length - end < 4500) { // In this case, the request header was really large, so we allocate a // brand new one; the old one will get GCed when subsequent requests // clear all references buf = new byte[buf.length]; end = 0; } pos = end; lastValid = pos; bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.ETIMEDOUT || (-nRead) == Status.TIMEUP) { throw new SocketTimeoutException(sm.getString("iib.failedread")); } else if (nRead == 0) { // APR_STATUS_IS_EOF, since native 1.1.22 return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } return (nRead > 0); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int write(ByteBuffer buf, NioChannel socket, long writeTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int written = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) && buf.hasRemaining()) { if (keycount > 0) { //only write if we were registered for a write int cnt = socket.write(buf); //write the data if (cnt == -1) throw new EOFException(); written += cnt; if (cnt > 0) { time = System.currentTimeMillis(); //reset our timeout timer continue; //we successfully wrote, try again without a selector } } try { if ( att.getWriteLatch()==null || att.getWriteLatch().getCount()==0) att.startWriteLatch(1); poller.add(att,SelectionKey.OP_WRITE,reference); if (writeTimeout < 0) { att.awaitWriteLatch(Long.MAX_VALUE,TimeUnit.MILLISECONDS); } else { att.awaitWriteLatch(writeTimeout,TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getWriteLatch()!=null && att.getWriteLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetWriteLatch(); } if (writeTimeout > 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= writeTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_WRITE); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return written; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int read(ByteBuffer buf, NioChannel socket, long readTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int read = 0; boolean timedout = false; int keycount = 1; //assume we can read long time = System.currentTimeMillis(); //start the timeout timer try { while(!timedout) { if (keycount > 0) { //only read if we were registered for a read read = socket.read(buf); if (read == -1) throw new EOFException(); if (read > 0) break; } try { if ( att.getReadLatch()==null || att.getReadLatch().getCount()==0) att.startReadLatch(1); poller.add(att,SelectionKey.OP_READ, reference); if (readTimeout < 0) { att.awaitReadLatch(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } else { att.awaitReadLatch(readTimeout, TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getReadLatch()!=null && att.getReadLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetReadLatch(); } if (readTimeout >= 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= readTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_READ); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return read; }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int write(ByteBuffer buf, NioChannel socket, Selector selector, long writeTimeout, boolean block) throws IOException { if ( SHARED && block ) { return blockingSelector.write(buf,socket,writeTimeout); } SelectionKey key = null; int written = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) && buf.hasRemaining() ) { int cnt = 0; if ( keycount > 0 ) { //only write if we were registered for a write cnt = socket.write(buf); //write the data if (cnt == -1) throw new EOFException(); written += cnt; if (cnt > 0) { time = System.currentTimeMillis(); //reset our timeout timer continue; //we successfully wrote, try again without a selector } if (cnt==0 && (!block)) break; //don't block } if ( selector != null ) { //register OP_WRITE to the selector if (key==null) key = socket.getIOChannel().register(selector, SelectionKey.OP_WRITE); else key.interestOps(SelectionKey.OP_WRITE); keycount = selector.select(writeTimeout); } if (writeTimeout > 0 && (selector == null || keycount == 0) ) timedout = (System.currentTimeMillis()-time)>=writeTimeout; }//while if ( timedout ) throw new SocketTimeoutException(); } finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } } return written; }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int read(ByteBuffer buf, NioChannel socket, Selector selector, long readTimeout, boolean block) throws IOException { if ( SHARED && block ) { return blockingSelector.read(buf,socket,readTimeout); } SelectionKey key = null; int read = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) ) { int cnt = 0; if ( keycount > 0 ) { //only read if we were registered for a read cnt = socket.read(buf); if (cnt == -1) throw new EOFException(); read += cnt; if (cnt > 0) continue; //read some more if (cnt==0 && (read>0 || (!block) ) ) break; //we are done reading } if ( selector != null ) {//perform a blocking read //register OP_WRITE to the selector if (key==null) key = socket.getIOChannel().register(selector, SelectionKey.OP_READ); else key.interestOps(SelectionKey.OP_READ); keycount = selector.select(readTimeout); } if (readTimeout > 0 && (selector == null || keycount == 0) ) timedout = (System.currentTimeMillis()-time)>=readTimeout; }//while if ( timedout ) throw new SocketTimeoutException(); } finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } } return read; }
0 0
(Lib) EmptyStackException 5
              
// in java/org/apache/tomcat/util/digester/Digester.java
public Object pop(String stackName) { Object result = null; ArrayStack<Object> namedStack = stacksByName.get(stackName); if (namedStack == null) { if (log.isDebugEnabled()) { log.debug("Stack '" + stackName + "' is empty"); } throw new EmptyStackException(); } else { result = namedStack.pop(); } return result; }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object peek(String stackName) { Object result = null; ArrayStack<Object> namedStack = stacksByName.get(stackName); if (namedStack == null ) { if (log.isDebugEnabled()) { log.debug("Stack '" + stackName + "' is empty"); } throw new EmptyStackException(); } else { result = namedStack.peek(); } return result; }
// in java/org/apache/tomcat/util/digester/ArrayStack.java
public E peek() throws EmptyStackException { int n = size(); if (n <= 0) { throw new EmptyStackException(); } else { return get(n - 1); } }
// in java/org/apache/tomcat/util/digester/ArrayStack.java
public E peek(int n) throws EmptyStackException { int m = (size() - n) - 1; if (m < 0) { throw new EmptyStackException(); } else { return get(m); } }
// in java/org/apache/tomcat/util/digester/ArrayStack.java
public E pop() throws EmptyStackException { int n = size(); if (n <= 0) { throw new EmptyStackException(); } else { return remove(n - 1); } }
0 3
              
// in java/org/apache/tomcat/util/digester/ArrayStack.java
public E peek() throws EmptyStackException { int n = size(); if (n <= 0) { throw new EmptyStackException(); } else { return get(n - 1); } }
// in java/org/apache/tomcat/util/digester/ArrayStack.java
public E peek(int n) throws EmptyStackException { int m = (size() - n) - 1; if (m < 0) { throw new EmptyStackException(); } else { return get(m); } }
// in java/org/apache/tomcat/util/digester/ArrayStack.java
public E pop() throws EmptyStackException { int n = size(); if (n <= 0) { throw new EmptyStackException(); } else { return remove(n - 1); } }
(Domain) MalformedStreamException 5
              
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public boolean readBoundary() throws MalformedStreamException { byte[] marker = new byte[2]; boolean nextChunk = false; head += boundaryLength; try { marker[0] = readByte(); if (marker[0] == LF) { // Work around IE5 Mac bug with input type=image. // Because the boundary delimiter, not including the trailing // CRLF, must not appear within any file (RFC 2046, section // 5.1.1), we know the missing CR is due to a buggy browser // rather than a file containing something similar to a // boundary. return true; } marker[1] = readByte(); if (arrayequals(marker, STREAM_TERMINATOR, 2)) { nextChunk = false; } else if (arrayequals(marker, FIELD_SEPARATOR, 2)) { nextChunk = true; } else { throw new MalformedStreamException( "Unexpected characters follow a boundary"); } } catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); } return nextChunk; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public String readHeaders() throws MalformedStreamException { int i = 0; byte b; // to support multi-byte characters ByteArrayOutputStream baos = new ByteArrayOutputStream(); int size = 0; while (i < HEADER_SEPARATOR.length) { try { b = readByte(); } catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); } if (++size > HEADER_PART_SIZE_MAX) { throw new MalformedStreamException( "Header section has more than " + HEADER_PART_SIZE_MAX + " bytes (maybe it is not properly terminated)"); } if (b == HEADER_SEPARATOR[i]) { i++; } else { i = 0; } baos.write(b); } String headers = null; if (headerEncoding != null) { try { headers = baos.toString(headerEncoding); } catch (UnsupportedEncodingException e) { // Fall back to platform default if specified encoding is not // supported. headers = baos.toString(); } } else { headers = baos.toString(); } return headers; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
private int makeAvailable() throws IOException { if (pos != -1) { return 0; } // Move the data to the beginning of the buffer. total += tail - head - pad; System.arraycopy(buffer, tail - pad, buffer, 0, pad); // Refill buffer with new data. head = 0; tail = pad; for (;;) { int bytesRead = input.read(buffer, tail, bufSize - tail); if (bytesRead == -1) { // The last pad amount is left in the buffer. // Boundary can't be in there so signal an error // condition. final String msg = "Stream ended unexpectedly"; throw new MalformedStreamException(msg); } if (notifier != null) { notifier.noteBytesRead(bytesRead); } tail += bytesRead; findSeparator(); int av = available(); if (av > 0 || pos != -1) { return av; } } }
2
              
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); }
4
              
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public boolean readBoundary() throws MalformedStreamException { byte[] marker = new byte[2]; boolean nextChunk = false; head += boundaryLength; try { marker[0] = readByte(); if (marker[0] == LF) { // Work around IE5 Mac bug with input type=image. // Because the boundary delimiter, not including the trailing // CRLF, must not appear within any file (RFC 2046, section // 5.1.1), we know the missing CR is due to a buggy browser // rather than a file containing something similar to a // boundary. return true; } marker[1] = readByte(); if (arrayequals(marker, STREAM_TERMINATOR, 2)) { nextChunk = false; } else if (arrayequals(marker, FIELD_SEPARATOR, 2)) { nextChunk = true; } else { throw new MalformedStreamException( "Unexpected characters follow a boundary"); } } catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); } return nextChunk; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public String readHeaders() throws MalformedStreamException { int i = 0; byte b; // to support multi-byte characters ByteArrayOutputStream baos = new ByteArrayOutputStream(); int size = 0; while (i < HEADER_SEPARATOR.length) { try { b = readByte(); } catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); } if (++size > HEADER_PART_SIZE_MAX) { throw new MalformedStreamException( "Header section has more than " + HEADER_PART_SIZE_MAX + " bytes (maybe it is not properly terminated)"); } if (b == HEADER_SEPARATOR[i]) { i++; } else { i = 0; } baos.write(b); } String headers = null; if (headerEncoding != null) { try { headers = baos.toString(headerEncoding); } catch (UnsupportedEncodingException e) { // Fall back to platform default if specified encoding is not // supported. headers = baos.toString(); } } else { headers = baos.toString(); } return headers; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public int readBodyData(OutputStream output) throws MalformedStreamException, IOException { final InputStream istream = newInputStream(); return (int) Streams.copy(istream, output, false); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public int discardBodyData() throws MalformedStreamException, IOException { return readBodyData(null); }
(Lib) NumberFormatException 5
              
// in java/org/apache/tomcat/util/buf/Ascii.java
public static long parseLong(byte[] b, int off, int len) throws NumberFormatException { int c; if (b == null || len <= 0 || !isDigit(c = b[off++])) { throw new NumberFormatException(); } long n = c - '0'; long m; while (--len > 0) { if (!isDigit(c = b[off++])) { throw new NumberFormatException(); } m = n * 10 + c - '0'; if (m < n) { // Overflow throw new NumberFormatException(); } else { n = m; } } return n; }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { if (filterConfig.getInitParameter(INTERNAL_PROXIES_PARAMETER) != null) { setInternalProxies(filterConfig.getInitParameter(INTERNAL_PROXIES_PARAMETER)); } if (filterConfig.getInitParameter(PROTOCOL_HEADER_PARAMETER) != null) { setProtocolHeader(filterConfig.getInitParameter(PROTOCOL_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER) != null) { setProtocolHeaderHttpsValue(filterConfig.getInitParameter(PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER)); } if (filterConfig.getInitParameter(PORT_HEADER_PARAMETER) != null) { setPortHeader(filterConfig.getInitParameter(PORT_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(CHANGE_LOCAL_PORT_PARAMETER) != null) { setChangeLocalPort(Boolean.parseBoolean(filterConfig.getInitParameter(CHANGE_LOCAL_PORT_PARAMETER))); } if (filterConfig.getInitParameter(PROXIES_HEADER_PARAMETER) != null) { setProxiesHeader(filterConfig.getInitParameter(PROXIES_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(REMOTE_IP_HEADER_PARAMETER) != null) { setRemoteIpHeader(filterConfig.getInitParameter(REMOTE_IP_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(TRUSTED_PROXIES_PARAMETER) != null) { setTrustedProxies(filterConfig.getInitParameter(TRUSTED_PROXIES_PARAMETER)); } if (filterConfig.getInitParameter(HTTP_SERVER_PORT_PARAMETER) != null) { try { setHttpServerPort(Integer.parseInt(filterConfig.getInitParameter(HTTP_SERVER_PORT_PARAMETER))); } catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTP_SERVER_PORT_PARAMETER + " : " + e.getMessage()); } } if (filterConfig.getInitParameter(HTTPS_SERVER_PORT_PARAMETER) != null) { try { setHttpsServerPort(Integer.parseInt(filterConfig.getInitParameter(HTTPS_SERVER_PORT_PARAMETER))); } catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTPS_SERVER_PORT_PARAMETER + " : " + e.getMessage()); } } }
2
              
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTP_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTPS_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
2
              
// in java/org/apache/tomcat/util/buf/Ascii.java
public static long parseLong(byte[] b, int off, int len) throws NumberFormatException { int c; if (b == null || len <= 0 || !isDigit(c = b[off++])) { throw new NumberFormatException(); } long n = c - '0'; long m; while (--len > 0) { if (!isDigit(c = b[off++])) { throw new NumberFormatException(); } m = n * 10 + c - '0'; if (m < n) { // Overflow throw new NumberFormatException(); } else { n = m; } } return n; }
// in java/org/apache/catalina/util/Extension.java
private boolean isNewer(String first, String second) throws NumberFormatException { if ((first == null) || (second == null)) return (false); if (first.equals(second)) return (true); StringTokenizer fTok = new StringTokenizer(first, ".", true); StringTokenizer sTok = new StringTokenizer(second, ".", true); int fVersion = 0; int sVersion = 0; while (fTok.hasMoreTokens() || sTok.hasMoreTokens()) { if (fTok.hasMoreTokens()) fVersion = Integer.parseInt(fTok.nextToken()); else fVersion = 0; if (sTok.hasMoreTokens()) sVersion = Integer.parseInt(sTok.nextToken()); else sVersion = 0; if (fVersion < sVersion) return (false); else if (fVersion > sVersion) return (true); if (fTok.hasMoreTokens()) // Swallow the periods fTok.nextToken(); if (sTok.hasMoreTokens()) sTok.nextToken(); } return (true); // Exact match }
(Domain) SSIStopProcessingException 5
              
// in java/org/apache/catalina/ssi/SSISet.java
Override public long process(SSIMediator ssiMediator, String commandName, String[] paramNames, String[] paramValues, PrintWriter writer) throws SSIStopProcessingException { long lastModified = 0; String errorMessage = ssiMediator.getConfigErrMsg(); String variableName = null; for (int i = 0; i < paramNames.length; i++) { String paramName = paramNames[i]; String paramValue = paramValues[i]; if (paramName.equalsIgnoreCase("var")) { variableName = paramValue; } else if (paramName.equalsIgnoreCase("value")) { if (variableName != null) { String substitutedValue = ssiMediator .substituteVariables(paramValue); ssiMediator.setVariableValue(variableName, substitutedValue); lastModified = System.currentTimeMillis(); } else { ssiMediator.log("#set--no variable specified"); writer.write(errorMessage); throw new SSIStopProcessingException(); } } else { ssiMediator.log("#set--Invalid attribute: " + paramName); writer.write(errorMessage); throw new SSIStopProcessingException(); } } return lastModified; }
// in java/org/apache/catalina/ssi/SSIConditional.java
Override public long process(SSIMediator ssiMediator, String commandName, String[] paramNames, String[] paramValues, PrintWriter writer) throws SSIStopProcessingException { // Assume anything using conditionals was modified by it long lastModified = System.currentTimeMillis(); // Retrieve the current state information SSIConditionalState state = ssiMediator.getConditionalState(); if ("if".equalsIgnoreCase(commandName)) { // Do nothing if we are nested in a false branch // except count it if (state.processConditionalCommandsOnly) { state.nestingCount++; return lastModified; } state.nestingCount = 0; // Evaluate the expression if (evaluateArguments(paramNames, paramValues, ssiMediator)) { // No more branches can be taken for this if block state.branchTaken = true; } else { // Do not process this branch state.processConditionalCommandsOnly = true; state.branchTaken = false; } } else if ("elif".equalsIgnoreCase(commandName)) { // No need to even execute if we are nested in // a false branch if (state.nestingCount > 0) return lastModified; // If a branch was already taken in this if block // then disable output and return if (state.branchTaken) { state.processConditionalCommandsOnly = true; return lastModified; } // Evaluate the expression if (evaluateArguments(paramNames, paramValues, ssiMediator)) { // Turn back on output and mark the branch state.processConditionalCommandsOnly = false; state.branchTaken = true; } else { // Do not process this branch state.processConditionalCommandsOnly = true; state.branchTaken = false; } } else if ("else".equalsIgnoreCase(commandName)) { // No need to even execute if we are nested in // a false branch if (state.nestingCount > 0) return lastModified; // If we've already taken another branch then // disable output otherwise enable it. state.processConditionalCommandsOnly = state.branchTaken; // And in any case, it's safe to say a branch // has been taken. state.branchTaken = true; } else if ("endif".equalsIgnoreCase(commandName)) { // If we are nested inside a false branch then pop out // one level on the nesting count if (state.nestingCount > 0) { state.nestingCount--; return lastModified; } // Turn output back on state.processConditionalCommandsOnly = false; // Reset the branch status for any outer if blocks, // since clearly we took a branch to have gotten here // in the first place. state.branchTaken = true; } else { throw new SSIStopProcessingException(); //throw new SsiCommandException( "Not a conditional command:" + // cmdName ); } return lastModified; }
// in java/org/apache/catalina/ssi/SSIConditional.java
private boolean evaluateArguments(String[] names, String[] values, SSIMediator ssiMediator) throws SSIStopProcessingException { String expr = getExpression(names, values); if (expr == null) { throw new SSIStopProcessingException(); //throw new SsiCommandException( "No expression specified." ); } try { ExpressionParseTree tree = new ExpressionParseTree(expr, ssiMediator); return tree.evaluateTree(); } catch (ParseException e) { //throw new SsiCommandException( "Error parsing expression." ); throw new SSIStopProcessingException(); } }
1
              
// in java/org/apache/catalina/ssi/SSIConditional.java
catch (ParseException e) { //throw new SsiCommandException( "Error parsing expression." ); throw new SSIStopProcessingException(); }
3
              
// in java/org/apache/catalina/ssi/SSISet.java
Override public long process(SSIMediator ssiMediator, String commandName, String[] paramNames, String[] paramValues, PrintWriter writer) throws SSIStopProcessingException { long lastModified = 0; String errorMessage = ssiMediator.getConfigErrMsg(); String variableName = null; for (int i = 0; i < paramNames.length; i++) { String paramName = paramNames[i]; String paramValue = paramValues[i]; if (paramName.equalsIgnoreCase("var")) { variableName = paramValue; } else if (paramName.equalsIgnoreCase("value")) { if (variableName != null) { String substitutedValue = ssiMediator .substituteVariables(paramValue); ssiMediator.setVariableValue(variableName, substitutedValue); lastModified = System.currentTimeMillis(); } else { ssiMediator.log("#set--no variable specified"); writer.write(errorMessage); throw new SSIStopProcessingException(); } } else { ssiMediator.log("#set--Invalid attribute: " + paramName); writer.write(errorMessage); throw new SSIStopProcessingException(); } } return lastModified; }
// in java/org/apache/catalina/ssi/SSIConditional.java
Override public long process(SSIMediator ssiMediator, String commandName, String[] paramNames, String[] paramValues, PrintWriter writer) throws SSIStopProcessingException { // Assume anything using conditionals was modified by it long lastModified = System.currentTimeMillis(); // Retrieve the current state information SSIConditionalState state = ssiMediator.getConditionalState(); if ("if".equalsIgnoreCase(commandName)) { // Do nothing if we are nested in a false branch // except count it if (state.processConditionalCommandsOnly) { state.nestingCount++; return lastModified; } state.nestingCount = 0; // Evaluate the expression if (evaluateArguments(paramNames, paramValues, ssiMediator)) { // No more branches can be taken for this if block state.branchTaken = true; } else { // Do not process this branch state.processConditionalCommandsOnly = true; state.branchTaken = false; } } else if ("elif".equalsIgnoreCase(commandName)) { // No need to even execute if we are nested in // a false branch if (state.nestingCount > 0) return lastModified; // If a branch was already taken in this if block // then disable output and return if (state.branchTaken) { state.processConditionalCommandsOnly = true; return lastModified; } // Evaluate the expression if (evaluateArguments(paramNames, paramValues, ssiMediator)) { // Turn back on output and mark the branch state.processConditionalCommandsOnly = false; state.branchTaken = true; } else { // Do not process this branch state.processConditionalCommandsOnly = true; state.branchTaken = false; } } else if ("else".equalsIgnoreCase(commandName)) { // No need to even execute if we are nested in // a false branch if (state.nestingCount > 0) return lastModified; // If we've already taken another branch then // disable output otherwise enable it. state.processConditionalCommandsOnly = state.branchTaken; // And in any case, it's safe to say a branch // has been taken. state.branchTaken = true; } else if ("endif".equalsIgnoreCase(commandName)) { // If we are nested inside a false branch then pop out // one level on the nesting count if (state.nestingCount > 0) { state.nestingCount--; return lastModified; } // Turn output back on state.processConditionalCommandsOnly = false; // Reset the branch status for any outer if blocks, // since clearly we took a branch to have gotten here // in the first place. state.branchTaken = true; } else { throw new SSIStopProcessingException(); //throw new SsiCommandException( "Not a conditional command:" + // cmdName ); } return lastModified; }
// in java/org/apache/catalina/ssi/SSIConditional.java
private boolean evaluateArguments(String[] names, String[] values, SSIMediator ssiMediator) throws SSIStopProcessingException { String expr = getExpression(names, values); if (expr == null) { throw new SSIStopProcessingException(); //throw new SsiCommandException( "No expression specified." ); } try { ExpressionParseTree tree = new ExpressionParseTree(expr, ssiMediator); return tree.evaluateTree(); } catch (ParseException e) { //throw new SsiCommandException( "Error parsing expression." ); throw new SSIStopProcessingException(); } }
(Lib) IndexOutOfBoundsException 4
              
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void write(char[] cbuf, int off, int len) throws IOException { if (writer != null) { writer.write(cbuf, off, len); } else { ensureOpen(); if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } if (len >= bufferSize - nextChar) reAllocBuff (len); System.arraycopy(cbuf, off, cb, nextChar, len); nextChar+=len; } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void write(char cbuf[], int off, int len) throws IOException { ensureOpen(); if (bufferSize == 0) { initOut(); out.write(cbuf, off, len); return; } if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } if (len >= bufferSize) { /* If the request length exceeds the size of the output buffer, flush the buffer and then write the data directly. In this way buffered streams will cascade harmlessly. */ if (autoFlush) flushBuffer(); else bufferOverflow(); initOut(); out.write(cbuf, off, len); return; } int b = off, t = off + len; while (b < t) { int d = min(bufferSize - nextChar, t - b); System.arraycopy(cbuf, b, cb, nextChar, d); b += d; nextChar += d; if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); } }
// in java/org/apache/tomcat/util/http/fileupload/ByteArrayOutputStream.java
Override public void write(byte[] b, int off, int len) { if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } synchronized (this) { int newcount = count + len; int remaining = len; int inBufferPos = count - filledBufferSum; while (remaining > 0) { int part = Math.min(remaining, currentBuffer.length - inBufferPos); System.arraycopy(b, off + len - remaining, currentBuffer, inBufferPos, part); remaining -= part; if (remaining > 0) { needNewBuffer(newcount); inBufferPos = 0; } } count = newcount; } }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public boolean append(byte[] b, int off, int len) { if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return false; } int newcount = bufSize + len; if (newcount > buf.length) { expand(newcount); } System.arraycopy(b, off, buf, bufSize, len); bufSize = newcount; if ( discard ) { if (bufSize > START_DATA.length && (firstIndexOf(buf, 0, START_DATA) == -1)) { bufSize = 0; log.error("Discarded the package, invalid header"); return false; } } return true; }
0 0
(Lib) LoginException 4
              
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
Override public boolean login() throws LoginException { // Set up our CallbackHandler requests if (callbackHandler == null) throw new LoginException("No CallbackHandler specified"); Callback callbacks[] = new Callback[9]; callbacks[0] = new NameCallback("Username: "); callbacks[1] = new PasswordCallback("Password: ", false); callbacks[2] = new TextInputCallback("nonce"); callbacks[3] = new TextInputCallback("nc"); callbacks[4] = new TextInputCallback("cnonce"); callbacks[5] = new TextInputCallback("qop"); callbacks[6] = new TextInputCallback("realmName"); callbacks[7] = new TextInputCallback("md5a2"); callbacks[8] = new TextInputCallback("authMethod"); // Interact with the user to retrieve the username and password String username = null; String password = null; String nonce = null; String nc = null; String cnonce = null; String qop = null; String realmName = null; String md5a2 = null; String authMethod = null; try { callbackHandler.handle(callbacks); username = ((NameCallback) callbacks[0]).getName(); password = new String(((PasswordCallback) callbacks[1]).getPassword()); nonce = ((TextInputCallback) callbacks[2]).getText(); nc = ((TextInputCallback) callbacks[3]).getText(); cnonce = ((TextInputCallback) callbacks[4]).getText(); qop = ((TextInputCallback) callbacks[5]).getText(); realmName = ((TextInputCallback) callbacks[6]).getText(); md5a2 = ((TextInputCallback) callbacks[7]).getText(); authMethod = ((TextInputCallback) callbacks[8]).getText(); } catch (IOException e) { throw new LoginException(e.toString()); } catch (UnsupportedCallbackException e) { throw new LoginException(e.toString()); } // Validate the username and password we have received if (authMethod == null) { // BASIC or FORM principal = super.authenticate(username, password); } else if (authMethod.equals(HttpServletRequest.DIGEST_AUTH)) { principal = super.authenticate(username, password, nonce, nc, cnonce, qop, realmName, md5a2); } else if (authMethod.equals(HttpServletRequest.CLIENT_CERT_AUTH)) { principal = super.getPrincipal(username); } else { throw new LoginException("Unknown authentication method"); } log.debug("login " + username + " " + principal); // Report results based on success or failure if (principal != null) { return (true); } else { throw new FailedLoginException("Username or password is incorrect"); } }
2
              
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (IOException e) { throw new LoginException(e.toString()); }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (UnsupportedCallbackException e) { throw new LoginException(e.toString()); }
4
              
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
Override public boolean abort() throws LoginException { // If our authentication was not successful, just return false if (principal == null) return (false); // Clean up if overall authentication failed if (committed) logout(); else { committed = false; principal = null; } log.debug("Abort"); return (true); }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
Override public boolean commit() throws LoginException { log.debug("commit " + principal); // If authentication was not successful, just return false if (principal == null) return (false); // Add our Principal to the Subject if needed if (!subject.getPrincipals().contains(principal)) { subject.getPrincipals().add(principal); // Add the roles as additional subjects as per the contract with the // JAASRealm if (principal instanceof GenericPrincipal) { String roles[] = ((GenericPrincipal) principal).getRoles(); for (int i = 0; i < roles.length; i++) { subject.getPrincipals().add( new GenericPrincipal(null, roles[i], null)); } } } committed = true; return (true); }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
Override public boolean login() throws LoginException { // Set up our CallbackHandler requests if (callbackHandler == null) throw new LoginException("No CallbackHandler specified"); Callback callbacks[] = new Callback[9]; callbacks[0] = new NameCallback("Username: "); callbacks[1] = new PasswordCallback("Password: ", false); callbacks[2] = new TextInputCallback("nonce"); callbacks[3] = new TextInputCallback("nc"); callbacks[4] = new TextInputCallback("cnonce"); callbacks[5] = new TextInputCallback("qop"); callbacks[6] = new TextInputCallback("realmName"); callbacks[7] = new TextInputCallback("md5a2"); callbacks[8] = new TextInputCallback("authMethod"); // Interact with the user to retrieve the username and password String username = null; String password = null; String nonce = null; String nc = null; String cnonce = null; String qop = null; String realmName = null; String md5a2 = null; String authMethod = null; try { callbackHandler.handle(callbacks); username = ((NameCallback) callbacks[0]).getName(); password = new String(((PasswordCallback) callbacks[1]).getPassword()); nonce = ((TextInputCallback) callbacks[2]).getText(); nc = ((TextInputCallback) callbacks[3]).getText(); cnonce = ((TextInputCallback) callbacks[4]).getText(); qop = ((TextInputCallback) callbacks[5]).getText(); realmName = ((TextInputCallback) callbacks[6]).getText(); md5a2 = ((TextInputCallback) callbacks[7]).getText(); authMethod = ((TextInputCallback) callbacks[8]).getText(); } catch (IOException e) { throw new LoginException(e.toString()); } catch (UnsupportedCallbackException e) { throw new LoginException(e.toString()); } // Validate the username and password we have received if (authMethod == null) { // BASIC or FORM principal = super.authenticate(username, password); } else if (authMethod.equals(HttpServletRequest.DIGEST_AUTH)) { principal = super.authenticate(username, password, nonce, nc, cnonce, qop, realmName, md5a2); } else if (authMethod.equals(HttpServletRequest.CLIENT_CERT_AUTH)) { principal = super.getPrincipal(username); } else { throw new LoginException("Unknown authentication method"); } log.debug("login " + username + " " + principal); // Report results based on success or failure if (principal != null) { return (true); } else { throw new FailedLoginException("Username or password is incorrect"); } }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
Override public boolean logout() throws LoginException { subject.getPrincipals().remove(principal); committed = false; principal = null; return (true); }
(Lib) ReflectionException 4
              
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
Method getGetter(String aname, BaseModelMBean mbean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); // Look up the actual operation to be used if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname + " for " + resource); String getMethod = attrInfo.getGetMethod(); if (getMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " get method name"); Object object = null; NoSuchMethodException exception = null; try { object = mbean; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find getter method " + getMethod); return m; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getSetter(String aname, BaseModelMBean bean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname); // Look up the actual operation to be used String setMethod = attrInfo.getSetMethod(); if (setMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " set method name"); String argType=attrInfo.getType(); Class<?> signature[] = new Class[] { BaseModelMBean.getAttributeClass( argType ) }; Object object = null; NoSuchMethodException exception = null; try { object = bean; m = object.getClass().getMethod(setMethod, signature); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(setMethod, signature); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find setter method " + setMethod + " " + resource); return m; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getInvoke(String aname, Object[] params, String[] signature, BaseModelMBean bean, Object resource) throws MBeanException, ReflectionException { Method method = null; if (params == null) params = new Object[0]; if (signature == null) signature = new String[0]; if (params.length != signature.length) throw new RuntimeOperationsException( new IllegalArgumentException( "Inconsistent arguments and signature"), "Inconsistent arguments and signature"); // Acquire the ModelMBeanOperationInfo information for // the requested operation OperationInfo opInfo = operations.get(aname); if (opInfo == null) throw new MBeanException(new ServiceNotFoundException( "Cannot find operation " + aname), "Cannot find operation " + aname); // Prepare the signature required by Java reflection APIs // FIXME - should we use the signature from opInfo? Class<?> types[] = new Class[signature.length]; for (int i = 0; i < signature.length; i++) { types[i] = BaseModelMBean.getAttributeClass(signature[i]); } // Locate the method to be invoked, either in this MBean itself // or in the corresponding managed resource // FIXME - Accessible methods in superinterfaces? Object object = null; Exception exception = null; try { object = bean; method = object.getClass().getMethod(aname, types); } catch (NoSuchMethodException e) { exception = e; } try { if ((method == null) && (resource != null)) { object = resource; method = object.getClass().getMethod(aname, types); } } catch (NoSuchMethodException e) { exception = e; } if (method == null) { throw new ReflectionException(exception, "Cannot find method " + aname + " with this signature"); } return method; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
static Class<?> getAttributeClass(String signature) throws ReflectionException { if (signature.equals(Boolean.TYPE.getName())) return Boolean.TYPE; else if (signature.equals(Byte.TYPE.getName())) return Byte.TYPE; else if (signature.equals(Character.TYPE.getName())) return Character.TYPE; else if (signature.equals(Double.TYPE.getName())) return Double.TYPE; else if (signature.equals(Float.TYPE.getName())) return Float.TYPE; else if (signature.equals(Integer.TYPE.getName())) return Integer.TYPE; else if (signature.equals(Long.TYPE.getName())) return Long.TYPE; else if (signature.equals(Short.TYPE.getName())) return Short.TYPE; else { try { ClassLoader cl=Thread.currentThread().getContextClassLoader(); if( cl!=null ) return cl.loadClass(signature); } catch( ClassNotFoundException e ) { } try { return Class.forName(signature); } catch (ClassNotFoundException e) { throw new ReflectionException (e, "Cannot find Class for " + signature); } } }
1
              
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (ClassNotFoundException e) { throw new ReflectionException (e, "Cannot find Class for " + signature); }
14
              
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
Method getGetter(String aname, BaseModelMBean mbean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); // Look up the actual operation to be used if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname + " for " + resource); String getMethod = attrInfo.getGetMethod(); if (getMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " get method name"); Object object = null; NoSuchMethodException exception = null; try { object = mbean; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find getter method " + getMethod); return m; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getSetter(String aname, BaseModelMBean bean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname); // Look up the actual operation to be used String setMethod = attrInfo.getSetMethod(); if (setMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " set method name"); String argType=attrInfo.getType(); Class<?> signature[] = new Class[] { BaseModelMBean.getAttributeClass( argType ) }; Object object = null; NoSuchMethodException exception = null; try { object = bean; m = object.getClass().getMethod(setMethod, signature); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(setMethod, signature); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find setter method " + setMethod + " " + resource); return m; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getInvoke(String aname, Object[] params, String[] signature, BaseModelMBean bean, Object resource) throws MBeanException, ReflectionException { Method method = null; if (params == null) params = new Object[0]; if (signature == null) signature = new String[0]; if (params.length != signature.length) throw new RuntimeOperationsException( new IllegalArgumentException( "Inconsistent arguments and signature"), "Inconsistent arguments and signature"); // Acquire the ModelMBeanOperationInfo information for // the requested operation OperationInfo opInfo = operations.get(aname); if (opInfo == null) throw new MBeanException(new ServiceNotFoundException( "Cannot find operation " + aname), "Cannot find operation " + aname); // Prepare the signature required by Java reflection APIs // FIXME - should we use the signature from opInfo? Class<?> types[] = new Class[signature.length]; for (int i = 0; i < signature.length; i++) { types[i] = BaseModelMBean.getAttributeClass(signature[i]); } // Locate the method to be invoked, either in this MBean itself // or in the corresponding managed resource // FIXME - Accessible methods in superinterfaces? Object object = null; Exception exception = null; try { object = bean; method = object.getClass().getMethod(aname, types); } catch (NoSuchMethodException e) { exception = e; } try { if ((method == null) && (resource != null)) { object = resource; method = object.getClass().getMethod(aname, types); } } catch (NoSuchMethodException e) { exception = e; } if (method == null) { throw new ReflectionException(exception, "Cannot find method " + aname + " with this signature"); } return method; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).getAttribute(name); } Method m=managedBean.getGetter(name, this, resource); Object result = null; try { Class<?> declaring = m.getDeclaringClass(); // workaround for catalina weird mbeans - the declaring class is BaseModelMBean. // but this is the catalina class. if( declaring.isAssignableFrom(this.getClass()) ) { result = m.invoke(this, NO_ARGS_PARAM ); } else { result = m.invoke(resource, NO_ARGS_PARAM ); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object invoke(String name, Object params[], String signature[]) throws MBeanException, ReflectionException { if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).invoke(name, params, signature); } // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Method name is null"), "Method name is null"); if( log.isDebugEnabled()) log.debug("Invoke " + name); Method method= managedBean.getInvoke(name, params, signature, this, resource); // Invoke the selected method on the appropriate object Object result = null; try { if( method.getDeclaringClass().isAssignableFrom( this.getClass()) ) { result = method.invoke(this, params ); } else { result = method.invoke(resource, params); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
static Class<?> getAttributeClass(String signature) throws ReflectionException { if (signature.equals(Boolean.TYPE.getName())) return Boolean.TYPE; else if (signature.equals(Byte.TYPE.getName())) return Byte.TYPE; else if (signature.equals(Character.TYPE.getName())) return Character.TYPE; else if (signature.equals(Double.TYPE.getName())) return Double.TYPE; else if (signature.equals(Float.TYPE.getName())) return Float.TYPE; else if (signature.equals(Integer.TYPE.getName())) return Integer.TYPE; else if (signature.equals(Long.TYPE.getName())) return Long.TYPE; else if (signature.equals(Short.TYPE.getName())) return Short.TYPE; else { try { ClassLoader cl=Thread.currentThread().getContextClassLoader(); if( cl!=null ) return cl.loadClass(signature); } catch( ClassNotFoundException e ) { } try { return Class.forName(signature); } catch (ClassNotFoundException e) { throw new ReflectionException (e, "Cannot find Class for " + signature); } } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if( log.isDebugEnabled() ) log.debug("Setting attribute " + this + " " + attribute ); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { try { ((DynamicMBean)resource).setAttribute(attribute); } catch (InvalidAttributeValueException e) { throw new MBeanException(e); } return; } // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); Object oldValue=null; //if( getAttMap.get(name) != null ) // oldValue=getAttribute( name ); Method m=managedBean.getSetter(name,this,resource); try { if( m.getDeclaringClass().isAssignableFrom( this.getClass()) ) { m.invoke(this, new Object[] { value }); } else { m.invoke(resource, new Object[] { value }); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } try { sendAttributeChangeNotification(new Attribute( name, oldValue), attribute); } catch(Exception ex) { log.error("Error sending notification " + name, ex); } //attributes.put( name, value ); // if( source != null ) { // // this mbean is associated with a source - maybe we want to persist // source.updateField(oname, name, value); // } }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); Object result = null; try { Connector connector = (Connector) getManagedResource(); result = IntrospectionUtils.getProperty(connector, name); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return result; }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); try { Connector connector = (Connector) getManagedResource(); IntrospectionUtils.setProperty(connector, name, String.valueOf(value)); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("auth".equals(name)) { return (cr.getAuth()); } else if ("description".equals(name)) { return (cr.getDescription()); } else if ("name".equals(name)) { return (cr.getName()); } else if ("scope".equals(name)) { return (cr.getScope()); } else if ("type".equals(name)) { return (cr.getType()); } else { value = (String) cr.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("auth".equals(name)) { cr.setAuth((String)value); } else if ("description".equals(name)) { cr.setDescription((String)value); } else if ("name".equals(name)) { cr.setName((String)value); } else if ("scope".equals(name)) { cr.setScope((String)value); } else if ("type".equals(name)) { cr.setType((String)value); } else { cr.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = cr.getNamingResources(); nr.removeResource(cr.getName()); nr.addResource(cr); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink cl = null; try { cl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("global".equals(name)) { return (cl.getGlobal()); } else if ("description".equals(name)) { return (cl.getDescription()); } else if ("name".equals(name)) { return (cl.getName()); } else if ("type".equals(name)) { return (cl.getType()); } else { value = (String) cl.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink crl = null; try { crl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("global".equals(name)) { crl.setGlobal((String)value); } else if ("description".equals(name)) { crl.setDescription((String)value); } else if ("name".equals(name)) { crl.setName((String)value); } else if ("type".equals(name)) { crl.setType((String)value); } else { crl.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = crl.getNamingResources(); nr.removeResourceLink(crl.getName()); nr.addResourceLink(crl); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { super.setAttribute(attribute); ContextEnvironment ce = null; try { ce = (ContextEnvironment) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = ce.getNamingResources(); nr.removeEnvironment(ce.getName()); nr.addEnvironment(ce); }
(Lib) SQLException 4
              
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
public Object unwrap(Class<?> iface) throws SQLException { if (iface == DataSource.class) { return ds; } else { throw new SQLException("Not a wrapper of "+iface.getName()); } }
// in java/org/apache/catalina/realm/JDBCRealm.java
protected Connection open() throws SQLException { // Do nothing if there is a database connection already open if (dbConnection != null) return (dbConnection); // Instantiate our database driver if necessary if (driver == null) { try { Class<?> clazz = Class.forName(driverName); driver = (Driver) clazz.newInstance(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); } } // Open a new connection Properties props = new Properties(); if (connectionName != null) props.put("user", connectionName); if (connectionPassword != null) props.put("password", connectionPassword); dbConnection = driver.connect(connectionURL, props); if (dbConnection == null) { throw new SQLException(sm.getString( "jdbcRealm.open.invalidurl",driverName, connectionURL)); } dbConnection.setAutoCommit(false); return (dbConnection); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
protected void open() throws SQLException { // Do nothing if there is a database connection already open if (conn != null) { return ; } // Instantiate our database driver if necessary if (driver == null) { try { Class<?> clazz = Class.forName(driverName); driver = (Driver) clazz.newInstance(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); } } // Open a new connection Properties props = new Properties(); if (connectionName != null) { props.put("user", connectionName); } if (connectionPassword != null) { props.put("password", connectionPassword); } conn = driver.connect(connectionURL, props); conn.setAutoCommit(true); String logPattern = pattern; if (logPattern.equals("common")) { ps = conn.prepareStatement ("INSERT INTO " + tableName + " (" + remoteHostField + ", " + userField + ", " + timestampField +", " + queryField + ", " + statusField + ", " + bytesField + ") VALUES(?, ?, ?, ?, ?, ?)"); } else if (logPattern.equals("combined")) { ps = conn.prepareStatement ("INSERT INTO " + tableName + " (" + remoteHostField + ", " + userField + ", " + timestampField + ", " + queryField + ", " + statusField + ", " + bytesField + ", " + virtualHostField + ", " + methodField + ", " + refererField + ", " + userAgentField + ") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); } }
2
              
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
10
              
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
public Object unwrap(Class<?> iface) throws SQLException { if (iface == DataSource.class) { return ds; } else { throw new SQLException("Not a wrapper of "+iface.getName()); } }
// in java/org/apache/catalina/loader/JdbcLeakPrevention.java
public List<String> clearJdbcDriverRegistrations() throws SQLException { List<String> driverNames = new ArrayList<String>(); /* * DriverManager.getDrivers() has a nasty side-effect of registering * drivers that are visible to this class loader but haven't yet been * loaded. Therefore, the first call to this method a) gets the list * of originally loaded drivers and b) triggers the unwanted * side-effect. The second call gets the complete list of drivers * ensuring that both original drivers and any loaded as a result of the * side-effects are all de-registered. */ HashSet<Driver> originalDrivers = new HashSet<Driver>(); Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { originalDrivers.add(drivers.nextElement()); } drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); // Only unload the drivers this web app loaded if (driver.getClass().getClassLoader() != this.getClass().getClassLoader()) { continue; } // Only report drivers that were originally registered. Skip any // that were registered as a side-effect of this code. if (originalDrivers.contains(driver)) { driverNames.add(driver.getClass().getCanonicalName()); } DriverManager.deregisterDriver(driver); } return driverNames; }
// in java/org/apache/catalina/realm/DataSourceRealm.java
private PreparedStatement credentials(Connection dbConnection, String username) throws SQLException { PreparedStatement credentials = dbConnection.prepareStatement(preparedCredentials); credentials.setString(1, username); return (credentials); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
private PreparedStatement roles(Connection dbConnection, String username) throws SQLException { PreparedStatement roles = dbConnection.prepareStatement(preparedRoles); roles.setString(1, username); return (roles); }
// in java/org/apache/catalina/realm/JDBCRealm.java
protected PreparedStatement credentials(Connection dbConnection, String username) throws SQLException { if (preparedCredentials == null) { StringBuilder sb = new StringBuilder("SELECT "); sb.append(userCredCol); sb.append(" FROM "); sb.append(userTable); sb.append(" WHERE "); sb.append(userNameCol); sb.append(" = ?"); if(containerLog.isDebugEnabled()) { containerLog.debug("credentials query: " + sb.toString()); } preparedCredentials = dbConnection.prepareStatement(sb.toString()); } if (username == null) { preparedCredentials.setNull(1,java.sql.Types.VARCHAR); } else { preparedCredentials.setString(1, username); } return (preparedCredentials); }
// in java/org/apache/catalina/realm/JDBCRealm.java
protected Connection open() throws SQLException { // Do nothing if there is a database connection already open if (dbConnection != null) return (dbConnection); // Instantiate our database driver if necessary if (driver == null) { try { Class<?> clazz = Class.forName(driverName); driver = (Driver) clazz.newInstance(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); } } // Open a new connection Properties props = new Properties(); if (connectionName != null) props.put("user", connectionName); if (connectionPassword != null) props.put("password", connectionPassword); dbConnection = driver.connect(connectionURL, props); if (dbConnection == null) { throw new SQLException(sm.getString( "jdbcRealm.open.invalidurl",driverName, connectionURL)); } dbConnection.setAutoCommit(false); return (dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
protected synchronized PreparedStatement roles(Connection dbConnection, String username) throws SQLException { if (preparedRoles == null) { StringBuilder sb = new StringBuilder("SELECT "); sb.append(roleNameCol); sb.append(" FROM "); sb.append(userRoleTable); sb.append(" WHERE "); sb.append(userNameCol); sb.append(" = ?"); preparedRoles = dbConnection.prepareStatement(sb.toString()); } preparedRoles.setString(1, username); return (preparedRoles); }
// in java/org/apache/catalina/session/JDBCStore.java
private void remove(String id, Connection _conn) throws SQLException { if (preparedRemoveSql == null) { String removeSql = "DELETE FROM " + sessionTable + " WHERE " + sessionIdCol + " = ? AND " + sessionAppCol + " = ?"; preparedRemoveSql = _conn.prepareStatement(removeSql); } preparedRemoveSql.setString(1, id); preparedRemoveSql.setString(2, getName()); preparedRemoveSql.execute(); }
// in java/org/apache/catalina/session/JDBCStore.java
protected Connection open() throws SQLException { // Do nothing if there is a database connection already open if (dbConnection != null) return (dbConnection); if (dataSourceName != null && dataSource == null) { Context initCtx; try { initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); this.dataSource = (DataSource) envCtx.lookup(this.dataSourceName); } catch (NamingException e) { manager.getContainer().getLogger().error( sm.getString(getStoreName() + ".wrongDataSource", this.dataSourceName), e); } } if (dataSource != null) { return dataSource.getConnection(); } // Instantiate our database driver if necessary if (driver == null) { try { Class<?> clazz = Class.forName(driverName); driver = (Driver) clazz.newInstance(); } catch (ClassNotFoundException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); } catch (InstantiationException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); } catch (IllegalAccessException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); } } // Open a new connection Properties props = new Properties(); if (connectionName != null) props.put("user", connectionName); if (connectionPassword != null) props.put("password", connectionPassword); dbConnection = driver.connect(connectionURL, props); dbConnection.setAutoCommit(true); return (dbConnection); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
protected void open() throws SQLException { // Do nothing if there is a database connection already open if (conn != null) { return ; } // Instantiate our database driver if necessary if (driver == null) { try { Class<?> clazz = Class.forName(driverName); driver = (Driver) clazz.newInstance(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); } } // Open a new connection Properties props = new Properties(); if (connectionName != null) { props.put("user", connectionName); } if (connectionPassword != null) { props.put("password", connectionPassword); } conn = driver.connect(connectionURL, props); conn.setAutoCommit(true); String logPattern = pattern; if (logPattern.equals("common")) { ps = conn.prepareStatement ("INSERT INTO " + tableName + " (" + remoteHostField + ", " + userField + ", " + timestampField +", " + queryField + ", " + statusField + ", " + bytesField + ") VALUES(?, ?, ?, ?, ?, ?)"); } else if (logPattern.equals("combined")) { ps = conn.prepareStatement ("INSERT INTO " + tableName + " (" + remoteHostField + ", " + userField + ", " + timestampField + ", " + queryField + ", " + statusField + ", " + bytesField + ", " + virtualHostField + ", " + methodField + ", " + refererField + ", " + userAgentField + ") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); } }
(Lib) SecurityException 4
              
// in java/org/apache/catalina/loader/WebappClassLoader.java
protected Class<?> findClassInternal(String name) throws ClassNotFoundException { if (!validate(name)) throw new ClassNotFoundException(name); String tempPath = name.replace('.', '/'); String classPath = tempPath + ".class"; ResourceEntry entry = null; if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, classPath); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, classPath); } if (entry == null) throw new ClassNotFoundException(name); Class<?> clazz = entry.loadedClass; if (clazz != null) return clazz; synchronized (this) { clazz = entry.loadedClass; if (clazz != null) return clazz; if (entry.binaryContent == null) throw new ClassNotFoundException(name); // Looking up the package String packageName = null; int pos = name.lastIndexOf('.'); if (pos != -1) packageName = name.substring(0, pos); Package pkg = null; if (packageName != null) { pkg = getPackage(packageName); // Define the package (if null) if (pkg == null) { try { if (entry.manifest == null) { definePackage(packageName, null, null, null, null, null, null, null); } else { definePackage(packageName, entry.manifest, entry.codeBase); } } catch (IllegalArgumentException e) { // Ignore: normal error due to dual definition of package } pkg = getPackage(packageName); } } if (securityManager != null) { // Checking sealing if (pkg != null) { boolean sealCheck = true; if (pkg.isSealed()) { sealCheck = pkg.isSealed(entry.codeBase); } else { sealCheck = (entry.manifest == null) || !isPackageSealed(packageName, entry.manifest); } if (!sealCheck) throw new SecurityException ("Sealing violation loading " + name + " : Package " + packageName + " is sealed."); } } try { clazz = defineClass(name, entry.binaryContent, 0, entry.binaryContent.length, new CodeSource(entry.codeBase, entry.certificates)); } catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); } entry.loadedClass = clazz; entry.binaryContent = null; entry.source = null; entry.codeBase = null; entry.manifest = null; entry.certificates = null; } return clazz; }
// in java/org/apache/catalina/connector/Request.java
Override public void setAttribute(String name, Object value) { // Name cannot be null if (name == null) { throw new IllegalArgumentException (sm.getString("coyoteRequest.setAttribute.namenull")); } // Null value is the same as removeAttribute() if (value == null) { removeAttribute(name); return; } // Special attributes SpecialAttributeAdapter adapter = specialAttributes.get(name); if (adapter != null) { adapter.set(this, name, value); return; } // Add or replace the specified attribute // Check for read only attribute // requests are per thread so synchronization unnecessary if (readOnlyAttributes.containsKey(name)) { return; } // Do the security check before any updates are made if (Globals.IS_SECURITY_ENABLED && name.equals(Globals.SENDFILE_FILENAME_ATTR)) { // Use the canonical file name to avoid any possible symlink and // relative path issues String canonicalPath; try { canonicalPath = new File(value.toString()).getCanonicalPath(); } catch (IOException e) { throw new SecurityException(sm.getString( "coyoteRequest.sendfileNotCanonical", value), e); } // Sendfile is performed in Tomcat's security context so need to // check if the web app is permitted to access the file while still // in the web app's security context System.getSecurityManager().checkRead(canonicalPath); // Update the value so the canonical path is used value = canonicalPath; } Object oldValue = attributes.put(name, value); // Pass special attributes to the native layer if (name.startsWith("org.apache.tomcat.")) { coyoteRequest.setAttribute(name, value); } // Notify interested application event listeners notifyAttributeAssigned(name, value, oldValue); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
private void checkAccess(Class<?> clazz) { if (privileged) { return; } if (Filter.class.isAssignableFrom(clazz)) { checkAccess(clazz, restrictedFilters); } else if (Servlet.class.isAssignableFrom(clazz)) { if (ContainerServlet.class.isAssignableFrom(clazz)) { throw new SecurityException("Restricted (ContainerServlet) " + clazz); } checkAccess(clazz, restrictedServlets); } else { checkAccess(clazz, restrictedListeners); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
private void checkAccess(Class<?> clazz, Properties restricted) { while (clazz != null) { if ("restricted".equals(restricted.getProperty(clazz.getName()))) { throw new SecurityException("Restricted " + clazz); } clazz = clazz.getSuperclass(); } }
1
              
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { throw new SecurityException(sm.getString( "coyoteRequest.sendfileNotCanonical", value), e); }
3
              
// in java/org/apache/juli/ClassLoaderLogManager.java
Override public void readConfiguration() throws IOException, SecurityException { checkAccess(); readConfiguration(Thread.currentThread().getContextClassLoader()); }
// in java/org/apache/juli/ClassLoaderLogManager.java
Override public void readConfiguration(InputStream is) throws IOException, SecurityException { checkAccess(); reset(); readConfiguration(is, Thread.currentThread().getContextClassLoader()); }
// in java/org/apache/juli/ClassLoaderLogManager.java
Override public void reset() throws SecurityException { Thread thread = Thread.currentThread(); if (thread.getClass().getName().startsWith( "java.util.logging.LogManager$")) { // Ignore the call from java.util.logging.LogManager.Cleaner, // because we have our own shutdown hook return; } ClassLoader classLoader = thread.getContextClassLoader(); ClassLoaderLogInfo clLogInfo = getClassLoaderInfo(classLoader); resetLoggers(clLogInfo); super.reset(); }
(Lib) TokenMgrError 4
              
// in java/org/apache/tomcat/util/http/parser/HttpParserTokenManager.java
public void SwitchTo(int lexState) { if (lexState >= 2 || lexState < 0) throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); else curLexState = lexState; }
// in java/org/apache/tomcat/util/http/parser/HttpParserTokenManager.java
public Token getNextToken() { Token matchedToken; int curPos = 0; EOFLoop : for (;;) { try { curChar = input_stream.BeginToken(); } catch(java.io.IOException e) { jjmatchedKind = 0; matchedToken = jjFillToken(); return matchedToken; } switch(curLexState) { case 0: jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_0(); break; case 1: jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_1(); break; } if (jjmatchedKind != 0x7fffffff) { if (jjmatchedPos + 1 < curPos) input_stream.backup(curPos - jjmatchedPos - 1); matchedToken = jjFillToken(); if (jjnewLexState[jjmatchedKind] != -1) curLexState = jjnewLexState[jjmatchedKind]; return matchedToken; } int error_line = input_stream.getEndLine(); int error_column = input_stream.getEndColumn(); String error_after = null; boolean EOFSeen = false; try { input_stream.readChar(); input_stream.backup(1); } catch (java.io.IOException e1) { EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; } if (!EOFSeen) { input_stream.backup(1); error_after = curPos <= 1 ? "" : input_stream.GetImage(); } throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); } }
// in java/org/apache/el/parser/ELParserTokenManager.java
public void SwitchTo(int lexState) { if (lexState >= 2 || lexState < 0) throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); else curLexState = lexState; }
// in java/org/apache/el/parser/ELParserTokenManager.java
public Token getNextToken() { Token matchedToken; int curPos = 0; EOFLoop : for (;;) { try { curChar = input_stream.BeginToken(); } catch(java.io.IOException e) { jjmatchedKind = 0; matchedToken = jjFillToken(); return matchedToken; } switch(curLexState) { case 0: jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_0(); break; case 1: try { input_stream.backup(0); while (curChar <= 32 && (0x100002600L & (1L << curChar)) != 0L) curChar = input_stream.BeginToken(); } catch (java.io.IOException e1) { continue EOFLoop; } jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_1(); if (jjmatchedPos == 0 && jjmatchedKind > 56) { jjmatchedKind = 56; } break; } if (jjmatchedKind != 0x7fffffff) { if (jjmatchedPos + 1 < curPos) input_stream.backup(curPos - jjmatchedPos - 1); if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) { matchedToken = jjFillToken(); if (jjnewLexState[jjmatchedKind] != -1) curLexState = jjnewLexState[jjmatchedKind]; return matchedToken; } else { if (jjnewLexState[jjmatchedKind] != -1) curLexState = jjnewLexState[jjmatchedKind]; continue EOFLoop; } } int error_line = input_stream.getEndLine(); int error_column = input_stream.getEndColumn(); String error_after = null; boolean EOFSeen = false; try { input_stream.readChar(); input_stream.backup(1); } catch (java.io.IOException e1) { EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; } if (!EOFSeen) { input_stream.backup(1); error_after = curPos <= 1 ? "" : input_stream.GetImage(); } throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); } }
0 0
(Domain) UnavailableException 4
              
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
Override public void init() throws ServletException { // Ensure that our ContainerServlet properties have been set if ((wrapper == null) || (context == null)) throw new UnavailableException (sm.getString("hostManagerServlet.noWrapper")); // Set our properties from the initialization parameters String value = null; try { value = getServletConfig().getInitParameter("debug"); debug = Integer.parseInt(value); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } }
// in java/org/apache/catalina/manager/ManagerServlet.java
Override public void init() throws ServletException { // Ensure that our ContainerServlet properties have been set if ((wrapper == null) || (context == null)) throw new UnavailableException( sm.getString("managerServlet.noWrapper")); // Set our properties from the initialization parameters String value = null; try { value = getServletConfig().getInitParameter("debug"); debug = Integer.parseInt(value); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } // Acquire global JNDI resources if available Server server = ((Engine)host.getParent()).getService().getServer(); if (server != null) { global = server.getGlobalNamingContext(); } // Calculate the directory into which we will be deploying applications versioned = (File) getServletContext().getAttribute (ServletContext.TEMPDIR); // Identify the appBase of the owning Host of this Context // (if any) deployed = ((Host) context.getParent()).getAppBaseFile(); configBase = new File(context.getCatalinaBase(), "conf"); Container container = context; Container host = null; Container engine = null; while (container != null) { if (container instanceof Host) host = container; if (container instanceof Engine) engine = container; container = container.getParent(); } if (engine != null) { configBase = new File(configBase, engine.getName()); } if (host != null) { configBase = new File(configBase, host.getName()); } // Note: The directory must exist for this to work. // Log debugging messages as necessary if (debug >= 1) { log("init: Associated with Deployer '" + oname + "'"); if (global != null) { log("init: Global resources are available"); } } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override public void init() throws ServletException { if (getServletConfig().getInitParameter("debug") != null) debug = Integer.parseInt(getServletConfig().getInitParameter("debug")); if (getServletConfig().getInitParameter("input") != null) input = Integer.parseInt(getServletConfig().getInitParameter("input")); if (getServletConfig().getInitParameter("output") != null) output = Integer.parseInt(getServletConfig().getInitParameter("output")); listings = Boolean.parseBoolean(getServletConfig().getInitParameter("listings")); if (getServletConfig().getInitParameter("readonly") != null) readOnly = Boolean.parseBoolean(getServletConfig().getInitParameter("readonly")); if (getServletConfig().getInitParameter("sendfileSize") != null) sendfileSize = Integer.parseInt(getServletConfig().getInitParameter("sendfileSize")) * 1024; fileEncoding = getServletConfig().getInitParameter("fileEncoding"); globalXsltFile = getServletConfig().getInitParameter("globalXsltFile"); contextXsltFile = getServletConfig().getInitParameter("contextXsltFile"); localXsltFile = getServletConfig().getInitParameter("localXsltFile"); readmeFile = getServletConfig().getInitParameter("readmeFile"); if (getServletConfig().getInitParameter("useAcceptRanges") != null) useAcceptRanges = Boolean.parseBoolean(getServletConfig().getInitParameter("useAcceptRanges")); // Sanity check on the specified buffer sizes if (input < 256) input = 256; if (output < 256) output = 256; if (debug > 0) { log("DefaultServlet.init: input buffer size=" + input + ", output buffer size=" + output); } // Load the proxy dir context. resources = (ProxyDirContext) getServletContext() .getAttribute(Globals.RESOURCES_ATTR); if (resources == null) { try { resources = (ProxyDirContext) new InitialContext() .lookup(RESOURCES_JNDI_NAME); } catch (NamingException e) { // Failed throw new ServletException("No resources", e); } } if (resources == null) { throw new UnavailableException("No resources"); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override public void init() throws ServletException { super.init(); if (getServletConfig().getInitParameter("secret") != null) secret = getServletConfig().getInitParameter("secret"); if (getServletConfig().getInitParameter("maxDepth") != null) maxDepth = Integer.parseInt( getServletConfig().getInitParameter("maxDepth")); if (getServletConfig().getInitParameter("allowSpecialPaths") != null) allowSpecialPaths = Boolean.parseBoolean( getServletConfig().getInitParameter("allowSpecialPaths")); // Load the MD5 helper used to calculate signatures. try { md5Helper = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new UnavailableException("No MD5"); } }
1
              
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NoSuchAlgorithmException e) { throw new UnavailableException("No MD5"); }
0
(Domain) FileUploadException 3
              
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
Override public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { // Save the length of the file size = outputFile.length(); /* * The uploaded file is being stored on disk * in a temporary location so move it to the * desired file. */ if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream( new FileInputStream(outputFile)); out = new BufferedOutputStream( new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } if (out != null) { try { out.close(); } catch (IOException e) { // ignore } } } } } else { /* * For whatever reason we cannot write the * file to disk. */ throw new FileUploadException( "Cannot write uploaded file to disk!"); } } }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
public List<FileItem> parseRequest(RequestContext ctx) throws FileUploadException { List<FileItem> items = new ArrayList<FileItem>(); boolean successful = false; try { FileItemIterator iter = getItemIterator(ctx); FileItemFactory fac = getFileItemFactory(); if (fac == null) { throw new NullPointerException( "No FileItemFactory has been set."); } while (iter.hasNext()) { final FileItemStream item = iter.next(); // Don't use getName() here to prevent an InvalidFileNameException. final String fileName = ((org.apache.tomcat.util.http.fileupload.FileUploadBase.FileItemIteratorImpl.FileItemStreamImpl) item).name; FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), fileName); items.add(fileItem); try { Streams.copy(item.openStream(), fileItem.getOutputStream(), true); } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); } if (fileItem instanceof FileItemHeadersSupport) { final FileItemHeaders fih = item.getHeaders(); ((FileItemHeadersSupport) fileItem).setHeaders(fih); } } successful = true; return items; } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new FileUploadException(e.getMessage(), e); } finally { if (!successful) { for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) { FileItem fileItem = iterator.next(); try { fileItem.delete(); } catch (Exception e) { // ignore it } } } } }
1
              
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new FileUploadException(e.getMessage(), e); }
7
              
// in java/org/apache/tomcat/util/http/fileupload/servlet/ServletFileUpload.java
public List<FileItem> parseRequest(HttpServletRequest request) throws FileUploadException { return parseRequest(new ServletRequestContext(request)); }
// in java/org/apache/tomcat/util/http/fileupload/servlet/ServletFileUpload.java
public FileItemIterator getItemIterator(HttpServletRequest request) throws FileUploadException, IOException { return super.getItemIterator(new ServletRequestContext(request)); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
public FileItemIterator getItemIterator(RequestContext ctx) throws FileUploadException, IOException { return new FileItemIteratorImpl(ctx); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
public List<FileItem> parseRequest(RequestContext ctx) throws FileUploadException { List<FileItem> items = new ArrayList<FileItem>(); boolean successful = false; try { FileItemIterator iter = getItemIterator(ctx); FileItemFactory fac = getFileItemFactory(); if (fac == null) { throw new NullPointerException( "No FileItemFactory has been set."); } while (iter.hasNext()) { final FileItemStream item = iter.next(); // Don't use getName() here to prevent an InvalidFileNameException. final String fileName = ((org.apache.tomcat.util.http.fileupload.FileUploadBase.FileItemIteratorImpl.FileItemStreamImpl) item).name; FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), fileName); items.add(fileItem); try { Streams.copy(item.openStream(), fileItem.getOutputStream(), true); } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); } if (fileItem instanceof FileItemHeadersSupport) { final FileItemHeaders fih = item.getHeaders(); ((FileItemHeadersSupport) fileItem).setHeaders(fih); } } successful = true; return items; } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new FileUploadException(e.getMessage(), e); } finally { if (!successful) { for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) { FileItem fileItem = iterator.next(); try { fileItem.delete(); } catch (Exception e) { // ignore it } } } } }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public boolean hasNext() throws FileUploadException, IOException { if (eof) { return false; } if (itemValid) { return true; } return findNextItem(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public FileItemStream next() throws FileUploadException, IOException { if (eof || (!itemValid && !hasNext())) { throw new NoSuchElementException(); } itemValid = false; return currentItem; }
(Domain) FileUploadIOException 3
              
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override protected void raiseError(long pSizeMax, long pCount) throws IOException { itemStream.close(true); FileSizeLimitExceededException e = new FileSizeLimitExceededException( "The field " + fieldName + " exceeds its maximum permitted " + " size of " + pSizeMax + " bytes.", pCount, pSizeMax); e.setFieldName(fieldName); e.setFileName(name); throw new FileUploadIOException(e); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override protected void raiseError(long pSizeMax, long pCount) throws IOException { FileUploadException ex = new SizeLimitExceededException( "the request was rejected because" + " its size (" + pCount + ") exceeds the configured maximum" + " (" + pSizeMax + ")", pCount, pSizeMax); throw new FileUploadIOException(ex); }
0 0
(Lib) NameAlreadyBoundException 3
              
// in java/org/apache/naming/NamingContext.java
protected void bind(Name name, Object obj, boolean rebind) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (name.size() > 1) { if (entry == null) { throw new NameNotFoundException(sm.getString( "namingContext.nameNotBound", name, name.get(0))); } if (entry.type == NamingEntry.CONTEXT) { if (rebind) { ((Context) entry.value).rebind(name.getSuffix(1), obj); } else { ((Context) entry.value).bind(name.getSuffix(1), obj); } } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if ((!rebind) && (entry != null)) { throw new NameAlreadyBoundException (sm.getString("namingContext.alreadyBound", name.get(0))); } else { // Getting the type of the object and wrapping it within a new // NamingEntry Object toBind = NamingManager.getStateToBind(obj, name, this, env); if (toBind instanceof Context) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.CONTEXT); } else if (toBind instanceof LinkRef) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.LINK_REF); } else if (toBind instanceof Reference) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else if (toBind instanceof Referenceable) { toBind = ((Referenceable) toBind).getReference(); entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else { entry = new NamingEntry(name.get(0), toBind, NamingEntry.ENTRY); } bindings.put(name.get(0), entry); } } }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void bind(String name, Object obj, Attributes attrs) throws NamingException { // Note: No custom attributes allowed File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException (sm.getString("resources.alreadyBound", name)); rebind(name, obj, attrs); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException (sm.getString("resources.alreadyBound", name)); if (!file.mkdir()) throw new NamingException (sm.getString("resources.bindFailed", name)); return (DirContext) lookup(name); }
0 0
(Lib) NoSuchElementException 3
              
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public FileItemStream next() throws FileUploadException, IOException { if (eof || (!itemValid && !hasNext())) { throw new NoSuchElementException(); } itemValid = false; return currentItem; }
// in java/org/apache/catalina/core/ApplicationHttpRequest.java
Override public String nextElement() { if (pos != last) { for (int i = pos + 1; i <= last; i++) { if (getAttribute(specials[i]) != null) { pos = i; return (specials[i]); } } } String result = next; if (next != null) { next = findNext(); } else { throw new NoSuchElementException(); } return result; }
// in java/javax/el/CompositeELResolver.java
Override public FeatureDescriptor next() { if (!hasNext()) throw new NoSuchElementException(); FeatureDescriptor result = this.next; this.next = null; return result; }
0 0
(Domain) RemoteProcessException 3
              
// in java/org/apache/catalina/tribes/group/GroupChannel.java
Override public void messageReceived(ChannelMessage msg) { if ( msg == null ) return; try { if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("GroupChannel - Received msg:" + new UniqueId(msg.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " from "+msg.getAddress().getName()); } Serializable fwd = null; if ( (msg.getOptions() & SEND_OPTIONS_BYTE_MESSAGE) == SEND_OPTIONS_BYTE_MESSAGE ) { fwd = new ByteMessage(msg.getMessage().getBytes()); } else { try { fwd = XByteBuffer.deserialize(msg.getMessage().getBytesDirect(), 0, msg.getMessage().getLength()); }catch (Exception sx) { log.error("Unable to deserialize message:"+msg,sx); return; } } if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("GroupChannel - Receive Message:" + new UniqueId(msg.getUniqueId()) + " is " +fwd); } //get the actual member with the correct alive time Member source = msg.getAddress(); boolean rx = false; boolean delivered = false; for ( int i=0; i<channelListeners.size(); i++ ) { ChannelListener channelListener = (ChannelListener)channelListeners.get(i); if (channelListener != null && channelListener.accept(fwd, source)) { channelListener.messageReceived(fwd, source); delivered = true; //if the message was accepted by an RPC channel, that channel //is responsible for returning the reply, otherwise we send an absence reply if ( channelListener instanceof RpcChannel ) rx = true; } }//for if ((!rx) && (fwd instanceof RpcMessage)) { //if we have a message that requires a response, //but none was given, send back an immediate one sendNoRpcChannelReply((RpcMessage)fwd,source); } if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("GroupChannel delivered["+delivered+"] id:"+new UniqueId(msg.getUniqueId())); } } catch ( Exception x ) { //this could be the channel listener throwing an exception, we should log it //as a warning. if ( log.isWarnEnabled() ) log.warn("Error receiving message:",x); throw new RemoteProcessException("Exception:"+x.getMessage(),x); } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
protected void waitForAck() throws java.io.IOException { try { boolean ackReceived = false; boolean failAckReceived = false; ackbuf.clear(); int bytesRead = 0; int i = soIn.read(); while ((i != -1) && (bytesRead < Constants.ACK_COMMAND.length)) { bytesRead++; byte d = (byte)i; ackbuf.append(d); if (ackbuf.doesPackageExist() ) { byte[] ackcmd = ackbuf.extractDataPackage(true).getBytes(); ackReceived = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.ACK_DATA); failAckReceived = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA); ackReceived = ackReceived || failAckReceived; break; } i = soIn.read(); } if (!ackReceived) { if (i == -1) throw new IOException(sm.getString("IDataSender.ack.eof",getAddress(), new Integer(socket.getLocalPort()))); else throw new IOException(sm.getString("IDataSender.ack.wrong",getAddress(), new Integer(socket.getLocalPort()))); } else if ( failAckReceived && getThrowOnFailedAck()) { throw new RemoteProcessException("Received a failed ack:org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA"); } } catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; } finally { ackbuf.clear(); } }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
protected boolean read() throws IOException { //if there is no message here, we are done if ( current == null ) return true; int read = isUdpBased()?dataChannel.read(readbuf) : socketChannel.read(readbuf); //end of stream if ( read == -1 ) throw new IOException("Unable to receive an ack message. EOF on socket channel has been reached."); //no data read else if ( read == 0 ) return false; readbuf.flip(); ackbuf.append(readbuf,read); readbuf.clear(); if (ackbuf.doesPackageExist() ) { byte[] ackcmd = ackbuf.extractDataPackage(true).getBytes(); boolean ack = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.ACK_DATA); boolean fack = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA); if ( fack && getThrowOnFailedAck() ) throw new RemoteProcessException("Received a failed ack:org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA"); return ack || fack; } else { return false; } }
1
              
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { //this could be the channel listener throwing an exception, we should log it //as a warning. if ( log.isWarnEnabled() ) log.warn("Error receiving message:",x); throw new RemoteProcessException("Exception:"+x.getMessage(),x); }
0
(Lib) RuntimeErrorException 3
              
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).getAttribute(name); } Method m=managedBean.getGetter(name, this, resource); Object result = null; try { Class<?> declaring = m.getDeclaringClass(); // workaround for catalina weird mbeans - the declaring class is BaseModelMBean. // but this is the catalina class. if( declaring.isAssignableFrom(this.getClass()) ) { result = m.invoke(this, NO_ARGS_PARAM ); } else { result = m.invoke(resource, NO_ARGS_PARAM ); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object invoke(String name, Object params[], String signature[]) throws MBeanException, ReflectionException { if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).invoke(name, params, signature); } // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Method name is null"), "Method name is null"); if( log.isDebugEnabled()) log.debug("Invoke " + name); Method method= managedBean.getInvoke(name, params, signature, this, resource); // Invoke the selected method on the appropriate object Object result = null; try { if( method.getDeclaringClass().isAssignableFrom( this.getClass()) ) { result = method.invoke(this, params ); } else { result = method.invoke(resource, params); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if( log.isDebugEnabled() ) log.debug("Setting attribute " + this + " " + attribute ); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { try { ((DynamicMBean)resource).setAttribute(attribute); } catch (InvalidAttributeValueException e) { throw new MBeanException(e); } return; } // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); Object oldValue=null; //if( getAttMap.get(name) != null ) // oldValue=getAttribute( name ); Method m=managedBean.getSetter(name,this,resource); try { if( m.getDeclaringClass().isAssignableFrom( this.getClass()) ) { m.invoke(this, new Object[] { value }); } else { m.invoke(resource, new Object[] { value }); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } try { sendAttributeChangeNotification(new Attribute( name, oldValue), attribute); } catch(Exception ex) { log.error("Error sending notification " + name, ex); } //attributes.put( name, value ); // if( source != null ) { // // this mbean is associated with a source - maybe we want to persist // source.updateField(oname, name, value); // } }
3
              
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
0
(Lib) UTFDataFormatException 3
              
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
private void expectedByte(int position, int count) throws UTFDataFormatException { throw new UTFDataFormatException( Localizer.getMessage("jsp.error.xml.expectedByte", Integer.toString(position), Integer.toString(count))); }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
private void invalidByte(int position, int count) throws UTFDataFormatException { throw new UTFDataFormatException( Localizer.getMessage("jsp.error.xml.invalidByte", Integer.toString(position), Integer.toString(count))); }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
private void invalidSurrogate(int uuuuu) throws UTFDataFormatException { throw new UTFDataFormatException( Localizer.getMessage("jsp.error.xml.invalidHighSurrogate", Integer.toHexString(uuuuu))); }
0 3
              
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
private void expectedByte(int position, int count) throws UTFDataFormatException { throw new UTFDataFormatException( Localizer.getMessage("jsp.error.xml.expectedByte", Integer.toString(position), Integer.toString(count))); }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
private void invalidByte(int position, int count) throws UTFDataFormatException { throw new UTFDataFormatException( Localizer.getMessage("jsp.error.xml.invalidByte", Integer.toString(position), Integer.toString(count))); }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
private void invalidSurrogate(int uuuuu) throws UTFDataFormatException { throw new UTFDataFormatException( Localizer.getMessage("jsp.error.xml.invalidHighSurrogate", Integer.toHexString(uuuuu))); }
(Lib) UnsatisfiedLinkError 3
              
// in java/org/apache/tomcat/jni/Library.java
public static boolean initialize(String libraryName) throws Exception { if (_instance == null) { if (libraryName == null) _instance = new Library(); else _instance = new Library(libraryName); TCN_MAJOR_VERSION = version(0x01); TCN_MINOR_VERSION = version(0x02); TCN_PATCH_VERSION = version(0x03); TCN_IS_DEV_VERSION = version(0x04); APR_MAJOR_VERSION = version(0x11); APR_MINOR_VERSION = version(0x12); APR_PATCH_VERSION = version(0x13); APR_IS_DEV_VERSION = version(0x14); APR_SIZEOF_VOIDP = size(1); APR_PATH_MAX = size(2); APRMAXHOSTLEN = size(3); APR_MAX_IOVEC_SIZE = size(4); APR_MAX_SECS_TO_LINGER = size(5); APR_MMAP_THRESHOLD = size(6); APR_MMAP_LIMIT = size(7); APR_HAVE_IPV6 = has(0); APR_HAS_SHARED_MEMORY = has(1); APR_HAS_THREADS = has(2); APR_HAS_SENDFILE = has(3); APR_HAS_MMAP = has(4); APR_HAS_FORK = has(5); APR_HAS_RANDOM = has(6); APR_HAS_OTHER_CHILD = has(7); APR_HAS_DSO = has(8); APR_HAS_SO_ACCEPTFILTER = has(9); APR_HAS_UNICODE_FS = has(10); APR_HAS_PROC_INVOKED = has(11); APR_HAS_USER = has(12); APR_HAS_LARGE_FILES = has(13); APR_HAS_XTHREAD_FILES = has(14); APR_HAS_OS_UUID = has(15); APR_IS_BIGENDIAN = has(16); APR_FILES_AS_SOCKETS = has(17); APR_CHARSET_EBCDIC = has(18); APR_TCP_NODELAY_INHERITED = has(19); APR_O_NONBLOCK_INHERITED = has(20); if (APR_MAJOR_VERSION < 1) { throw new UnsatisfiedLinkError("Unsupported APR Version (" + aprVersionString() + ")"); } if (!APR_HAS_THREADS) { throw new UnsatisfiedLinkError("Missing APR_HAS_THREADS"); } } return initialize(); }
0 0
(Lib) ClassCastException 2
              
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data, int offset, int length, ClassLoader[] cls) throws IOException, ClassNotFoundException, ClassCastException { invokecount.addAndGet(1); Object message = null; if ( cls == null ) cls = new ClassLoader[0]; if (data != null && length > 0) { InputStream instream = new ByteArrayInputStream(data,offset,length); ObjectInputStream stream = null; stream = (cls.length>0)? new ReplicationStream(instream,cls):new ObjectInputStream(instream); message = stream.readObject(); instream.close(); stream.close(); } if ( message == null ) { return null; } else if (message instanceof Serializable) return (Serializable) message; else { throw new ClassCastException("Message has the wrong class. It should implement Serializable, instead it is:"+message.getClass().getName()); } }
// in java/javax/el/ArrayELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); checkBounds(base, idx); if (value != null && !base.getClass().getComponentType().isAssignableFrom( value.getClass())) { throw new ClassCastException(message(context, "objectNotAssignable", new Object[] {value.getClass().getName(), base.getClass().getComponentType().getName()})); } Array.set(base, idx, value); } }
0 6
              
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data) throws IOException, ClassNotFoundException, ClassCastException { return deserialize(data,0,data.length); }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data, int offset, int length) throws IOException, ClassNotFoundException, ClassCastException { return deserialize(data,offset,length,null); }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data, int offset, int length, ClassLoader[] cls) throws IOException, ClassNotFoundException, ClassCastException { invokecount.addAndGet(1); Object message = null; if ( cls == null ) cls = new ClassLoader[0]; if (data != null && length > 0) { InputStream instream = new ByteArrayInputStream(data,offset,length); ObjectInputStream stream = null; stream = (cls.length>0)? new ReplicationStream(instream,cls):new ObjectInputStream(instream); message = stream.readObject(); instream.close(); stream.close(); } if ( message == null ) { return null; } else if (message instanceof Serializable) return (Serializable) message; else { throw new ClassCastException("Message has the wrong class. It should implement Serializable, instead it is:"+message.getClass().getName()); } }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
Filter getFilter() throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { // Return the existing filter instance, if any if (this.filter != null) return (this.filter); // Identify the class loader we will be using String filterClass = filterDef.getFilterClass(); this.filter = (Filter) getInstanceManager().newInstance(filterClass); initFilter(); return (this.filter); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
void setFilterDef(FilterDef filterDef) throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { this.filterDef = filterDef; if (filterDef == null) { // Release any previously allocated filter instance if (this.filter != null){ if (Globals.IS_SECURITY_ENABLED) { try{ SecurityUtil.doAsPrivilege("destroy", filter); } catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); } SecurityUtil.remove(filter); } else { filter.destroy(); } if (!context.getIgnoreAnnotations()) { try { ((StandardContext) context).getInstanceManager().destroyInstance(this.filter); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); } } } this.filter = null; } else { // Allocate a new filter instance if necessary if (filterDef.getFilter() == null) { getFilter(); } } }
(Domain) ClientAbortException 2
              
// in java/org/apache/catalina/connector/OutputBuffer.java
protected void doFlush(boolean realFlush) throws IOException { if (suspended) { return; } // Flush the convertor if one is in use if (gotEnc && conv != null) { conv.flushBuffer(); } try { doFlush = true; if (initial) { coyoteResponse.sendHeaders(); initial = false; } if (bb.getLength() > 0) { bb.flushBuffer(); } } finally { doFlush = false; } if (realFlush) { coyoteResponse.action(ActionCode.CLIENT_FLUSH, coyoteResponse); // If some exception occurred earlier, or if some IOE occurred // here, notify the servlet with an IOE if (coyoteResponse.isExceptionPresent()) { throw new ClientAbortException (coyoteResponse.getErrorException()); } } }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void realWriteBytes(byte buf[], int off, int cnt) throws IOException { if (closed) { return; } if (coyoteResponse == null) { return; } // If we really have something to write if (cnt > 0) { // real write to the adapter outputChunk.setBytes(buf, off, cnt); try { coyoteResponse.doWrite(outputChunk); } catch (IOException e) { // An IOException on a write is almost always due to // the remote client aborting the request. Wrap this // so that it can be handled better by the error dispatcher. throw new ClientAbortException(e); } } }
1
              
// in java/org/apache/catalina/connector/OutputBuffer.java
catch (IOException e) { // An IOException on a write is almost always due to // the remote client aborting the request. Wrap this // so that it can be handled better by the error dispatcher. throw new ClientAbortException(e); }
0
(Lib) InvalidNameException 2
              
// in java/org/apache/catalina/realm/JNDIRealm.java
protected String getDistinguishedName(DirContext context, String base, SearchResult result) throws NamingException { // Get the entry's distinguished name. For relative results, this means // we need to composite a name with the base name, the context name, and // the result name. For non-relative names, use the returned name. if (result.isRelative()) { if (containerLog.isTraceEnabled()) { containerLog.trace(" search returned relative name: " + result.getName()); } NameParser parser = context.getNameParser(""); Name contextName = parser.parse(context.getNameInNamespace()); Name baseName = parser.parse(base); // Bugzilla 32269 Name entryName = parser.parse(new CompositeName(result.getName()).get(0)); Name name = contextName.addAll(baseName); name = name.addAll(entryName); return name.toString(); } else { String absoluteName = result.getName(); if (containerLog.isTraceEnabled()) containerLog.trace(" search returned absolute name: " + result.getName()); try { // Normalize the name by running it through the name parser. NameParser parser = context.getNameParser(""); URI userNameUri = new URI(absoluteName); String pathComponent = userNameUri.getPath(); // Should not ever have an empty path component, since that is /{DN} if (pathComponent.length() < 1 ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); } Name name = parser.parse(pathComponent.substring(1)); return name.toString(); } catch ( URISyntaxException e ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); } } }
1
              
// in java/org/apache/catalina/realm/JNDIRealm.java
catch ( URISyntaxException e ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); }
1
              
// in java/org/apache/naming/resources/WARDirContext.java
private Name getEscapedJndiName(String name) throws InvalidNameException { return new CompositeName(name.replace("'", "\\'").replace("\"", "")); }
(Domain) JspMethodNotFoundException 2
              
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public MethodInfo getMethodInfo(ELContext context) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.getMethodInfo(context); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public Object invoke(ELContext context, Object[] params) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.invoke(context, params); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
2
              
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
0
(Lib) NotContextException 2
              
// in java/org/apache/naming/NamingContext.java
Override public void destroySubcontext(Name name) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).destroySubcontext(name.getSuffix(1)); } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).close(); bindings.remove(name.get(0)); } else { throw new NotContextException (sm.getString("namingContext.contextExpected")); } } }
// in java/org/apache/naming/NamingContext.java
Override public NameParser getNameParser(Name name) throws NamingException { while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) return nameParser; if (name.size() > 1) { Object obj = bindings.get(name.get(0)); if (obj instanceof Context) { return ((Context) obj).getNameParser(name.getSuffix(1)); } else { throw new NotContextException (sm.getString("namingContext.contextExpected")); } } return nameParser; }
0 0
(Lib) ServiceException 2 1
              
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
catch (Exception e) { throw new ServiceException(e); }
2
              
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
private Remote getProxyPortClass(Object[] args) throws ServiceException { Class<?> serviceendpointClass = (Class<?>) args[0]; if (this.portComponentRef == null) return service.getPort(serviceendpointClass); QName portname = this.portComponentRef.get(serviceendpointClass.getName()); if (portname != null) { return service.getPort(portname, serviceendpointClass); } else { return service.getPort(serviceendpointClass); } }
(Lib) SocketException 2
              
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
protected void handShake() throws IOException { if( ssl.getWantClientAuth() ) { log.debug(sm.getString("jsseSupport.noCertWant")); } else { ssl.setNeedClientAuth(true); } if (ssl.getEnabledCipherSuites().length == 0) { // Handshake is never going to be successful. // Assume this is because handshakes are disabled log.warn(sm.getString("jsseSupport.serverRenegDisabled")); session.invalidate(); ssl.close(); return; } InputStream in = ssl.getInputStream(); int oldTimeout = ssl.getSoTimeout(); ssl.setSoTimeout(1000); byte[] b = new byte[1]; listener.reset(); ssl.startHandshake(); int maxTries = 60; // 60 * 1000 = example 1 minute time out for (int i = 0; i < maxTries; i++) { if (log.isTraceEnabled()) log.trace("Reading for try #" + i); try { int read = in.read(b); if (read > 0) { // Shouldn't happen as all input should have been swallowed // before trying to do the handshake. If it does, something // went wrong so lets bomb out now. throw new SSLException( sm.getString("jsseSupport.unexpectedData")); } } catch(SSLException sslex) { log.info(sm.getString("jsseSupport.clientCertError"), sslex); throw sslex; } catch (IOException e) { // ignore - presumably the timeout } if (listener.completed) { break; } } ssl.setSoTimeout(oldTimeout); if (listener.completed == false) { throw new SocketException("SSL Cert handshake timeout"); } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public Socket acceptSocket(ServerSocket socket) throws IOException { SSLSocket asock = null; try { asock = (SSLSocket)socket.accept(); } catch (SSLException e){ throw new SocketException("SSL handshake error" + e.toString()); } return asock; }
1
              
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException e){ throw new SocketException("SSL handshake error" + e.toString()); }
3
              
// in java/org/apache/tomcat/util/net/SocketProperties.java
public void setProperties(Socket socket) throws SocketException{ if (rxBufSize != null) socket.setReceiveBufferSize(rxBufSize.intValue()); if (txBufSize != null) socket.setSendBufferSize(txBufSize.intValue()); if (ooBInline !=null) socket.setOOBInline(ooBInline.booleanValue()); if (soKeepAlive != null) socket.setKeepAlive(soKeepAlive.booleanValue()); if (performanceConnectionTime != null && performanceLatency != null && performanceBandwidth != null) socket.setPerformancePreferences( performanceConnectionTime.intValue(), performanceLatency.intValue(), performanceBandwidth.intValue()); if (soReuseAddress != null) socket.setReuseAddress(soReuseAddress.booleanValue()); if (soLingerOn != null && soLingerTime != null) socket.setSoLinger(soLingerOn.booleanValue(), soLingerTime.intValue()); if (soTimeout != null && soTimeout.intValue() >= 0) socket.setSoTimeout(soTimeout.intValue()); if (tcpNoDelay != null) socket.setTcpNoDelay(tcpNoDelay.booleanValue()); if (soTrafficClass != null) socket.setTrafficClass(soTrafficClass.intValue()); }
// in java/org/apache/tomcat/util/net/SocketProperties.java
public void setProperties(ServerSocket socket) throws SocketException{ if (rxBufSize != null) socket.setReceiveBufferSize(rxBufSize.intValue()); if (performanceConnectionTime != null && performanceLatency != null && performanceBandwidth != null) socket.setPerformancePreferences( performanceConnectionTime.intValue(), performanceLatency.intValue(), performanceBandwidth.intValue()); if (soReuseAddress != null) socket.setReuseAddress(soReuseAddress.booleanValue()); if (soTimeout != null && soTimeout.intValue() >= 0) socket.setSoTimeout(soTimeout.intValue()); }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
private void completeConnect() throws SocketException { //we connected, register ourselves for writing setConnected(true); connecting = false; setRequestCount(0); setConnectTime(System.currentTimeMillis()); if (socketChannel!=null) { socketChannel.socket().setSendBufferSize(getTxBufSize()); socketChannel.socket().setReceiveBufferSize(getRxBufSize()); socketChannel.socket().setSoTimeout((int)getTimeout()); socketChannel.socket().setSoLinger(getSoLingerOn(),getSoLingerOn()?getSoLingerTime():0); socketChannel.socket().setTcpNoDelay(getTcpNoDelay()); socketChannel.socket().setKeepAlive(getSoKeepAlive()); socketChannel.socket().setReuseAddress(getSoReuseAddress()); socketChannel.socket().setOOBInline(getOoBInline()); socketChannel.socket().setSoLinger(getSoLingerOn(),getSoLingerTime()); socketChannel.socket().setTrafficClass(getSoTrafficClass()); } else if (dataChannel!=null) { dataChannel.socket().setSendBufferSize(getUdpTxBufSize()); dataChannel.socket().setReceiveBufferSize(getUdpRxBufSize()); dataChannel.socket().setSoTimeout((int)getTimeout()); dataChannel.socket().setReuseAddress(getSoReuseAddress()); dataChannel.socket().setTrafficClass(getSoTrafficClass()); } }
(Lib) UnsupportedCallbackException 2
              
// in java/org/apache/catalina/realm/JAASCallbackHandler.java
Override public void handle(Callback callbacks[]) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof NameCallback) { if (realm.getContainer().getLogger().isTraceEnabled()) realm.getContainer().getLogger().trace(sm.getString("jaasCallback.username", username)); ((NameCallback) callbacks[i]).setName(username); } else if (callbacks[i] instanceof PasswordCallback) { final char[] passwordcontents; if (password != null) { passwordcontents = password.toCharArray(); } else { passwordcontents = new char[0]; } ((PasswordCallback) callbacks[i]).setPassword (passwordcontents); } else if (callbacks[i] instanceof TextInputCallback) { TextInputCallback cb = ((TextInputCallback) callbacks[i]); if (cb.getPrompt().equals("nonce")) { cb.setText(nonce); } else if (cb.getPrompt().equals("nc")) { cb.setText(nc); } else if (cb.getPrompt().equals("cnonce")) { cb.setText(cnonce); } else if (cb.getPrompt().equals("qop")) { cb.setText(qop); } else if (cb.getPrompt().equals("realmName")) { cb.setText(realmName); } else if (cb.getPrompt().equals("md5a2")) { cb.setText(md5a2); } else if (cb.getPrompt().equals("authMethod")) { cb.setText(authMethod); } else { throw new UnsupportedCallbackException(callbacks[i]); } } else { throw new UnsupportedCallbackException(callbacks[i]); } } }
0 1
              
// in java/org/apache/catalina/realm/JAASCallbackHandler.java
Override public void handle(Callback callbacks[]) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof NameCallback) { if (realm.getContainer().getLogger().isTraceEnabled()) realm.getContainer().getLogger().trace(sm.getString("jaasCallback.username", username)); ((NameCallback) callbacks[i]).setName(username); } else if (callbacks[i] instanceof PasswordCallback) { final char[] passwordcontents; if (password != null) { passwordcontents = password.toCharArray(); } else { passwordcontents = new char[0]; } ((PasswordCallback) callbacks[i]).setPassword (passwordcontents); } else if (callbacks[i] instanceof TextInputCallback) { TextInputCallback cb = ((TextInputCallback) callbacks[i]); if (cb.getPrompt().equals("nonce")) { cb.setText(nonce); } else if (cb.getPrompt().equals("nc")) { cb.setText(nc); } else if (cb.getPrompt().equals("cnonce")) { cb.setText(cnonce); } else if (cb.getPrompt().equals("qop")) { cb.setText(qop); } else if (cb.getPrompt().equals("realmName")) { cb.setText(realmName); } else if (cb.getPrompt().equals("md5a2")) { cb.setText(md5a2); } else if (cb.getPrompt().equals("authMethod")) { cb.setText(authMethod); } else { throw new UnsupportedCallbackException(callbacks[i]); } } else { throw new UnsupportedCallbackException(callbacks[i]); } } }
(Lib) ArithmeticException 1 0 0
(Lib) CRLException 1
              
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected CertPathParameters getParameters(String algorithm, String crlf, KeyStore trustStore) throws Exception { CertPathParameters params = null; if("PKIX".equalsIgnoreCase(algorithm)) { PKIXBuilderParameters xparams = new PKIXBuilderParameters(trustStore, new X509CertSelector()); Collection<? extends CRL> crls = getCRLs(crlf); CertStoreParameters csp = new CollectionCertStoreParameters(crls); CertStore store = CertStore.getInstance("Collection", csp); xparams.addCertStore(store); xparams.setRevocationEnabled(true); String trustLength = endpoint.getTrustMaxCertLength(); if(trustLength != null) { try { xparams.setMaxPathLength(Integer.parseInt(trustLength)); } catch(Exception ex) { log.warn("Bad maxCertLength: "+trustLength); } } params = xparams; } else { throw new CRLException("CRLs not supported for type: "+algorithm); } return params; }
0 1
              
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected Collection<? extends CRL> getCRLs(String crlf) throws IOException, CRLException, CertificateException { File crlFile = new File(crlf); if( !crlFile.isAbsolute() ) { crlFile = new File( System.getProperty(Constants.CATALINA_BASE_PROP), crlf); } Collection<? extends CRL> crls = null; InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlFile); crls = cf.generateCRLs(is); } catch(IOException iex) { throw iex; } catch(CRLException crle) { throw crle; } catch(CertificateException ce) { throw ce; } finally { if(is != null) { try{ is.close(); } catch(Exception ex) { // Ignore } } } return crls; }
(Lib) CharConversionException 1
              
// in java/javax/servlet/ServletOutputStream.java
public void print(String s) throws IOException { if (s == null) s = "null"; int len = s.length(); for (int i = 0; i < len; i++) { char c = s.charAt(i); // // XXX NOTE: This is clearly incorrect for many strings, // but is the only consistent approach within the current // servlet framework. It must suffice until servlet output // streams properly encode their output. // if ((c & 0xff00) != 0) { // high order byte must be zero String errMsg = lStrings.getString("err.not_iso8859_1"); Object[] errArgs = new Object[1]; errArgs[0] = Character.valueOf(c); errMsg = MessageFormat.format(errMsg, errArgs); throw new CharConversionException(errMsg); } write(c); } }
0 0
(Domain) DecodeException 1
              
// in java/org/apache/tomcat/util/buf/UDecoder.java
public void convert(MessageBytes mb, boolean query) throws IOException { switch (mb.getType()) { case MessageBytes.T_STR: String strValue=mb.toString(); if( strValue==null ) { return; } try { mb.setString( convert( strValue, query )); } catch (RuntimeException ex) { throw new DecodeException(ex.getMessage()); } break; case MessageBytes.T_CHARS: CharChunk charC=mb.getCharChunk(); convert( charC, query ); break; case MessageBytes.T_BYTES: ByteChunk bytesC=mb.getByteChunk(); convert( bytesC, query ); break; } }
1
              
// in java/org/apache/tomcat/util/buf/UDecoder.java
catch (RuntimeException ex) { throw new DecodeException(ex.getMessage()); }
0
(Lib) ELParseException 1 1
              
// in java/org/apache/jasper/el/ExpressionEvaluatorImpl.java
catch (javax.el.ELException e) { throw new ELParseException(e.getMessage()); }
0
(Domain) IOFileUploadException 1
              
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
public List<FileItem> parseRequest(RequestContext ctx) throws FileUploadException { List<FileItem> items = new ArrayList<FileItem>(); boolean successful = false; try { FileItemIterator iter = getItemIterator(ctx); FileItemFactory fac = getFileItemFactory(); if (fac == null) { throw new NullPointerException( "No FileItemFactory has been set."); } while (iter.hasNext()) { final FileItemStream item = iter.next(); // Don't use getName() here to prevent an InvalidFileNameException. final String fileName = ((org.apache.tomcat.util.http.fileupload.FileUploadBase.FileItemIteratorImpl.FileItemStreamImpl) item).name; FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), fileName); items.add(fileItem); try { Streams.copy(item.openStream(), fileItem.getOutputStream(), true); } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); } if (fileItem instanceof FileItemHeadersSupport) { final FileItemHeaders fih = item.getHeaders(); ((FileItemHeadersSupport) fileItem).setHeaders(fih); } } successful = true; return items; } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new FileUploadException(e.getMessage(), e); } finally { if (!successful) { for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) { FileItem fileItem = iterator.next(); try { fileItem.delete(); } catch (Exception e) { // ignore it } } } } }
1
              
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); }
0
(Lib) IllegalAccessError 1
              
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
Override protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { ClassLoader latestLoader = (classLoaders!=null && classLoaders.length==0)?null:classLoaders[0]; ClassLoader nonPublicLoader = null; boolean hasNonPublicInterface = false; // define proxy in class loader of non-public interface(s), if any Class<?>[] classObjs = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { Class<?> cl = this.resolveClass(interfaces[i]); if (latestLoader==null) latestLoader = cl.getClassLoader(); if ((cl.getModifiers() & Modifier.PUBLIC) == 0) { if (hasNonPublicInterface) { if (nonPublicLoader != cl.getClassLoader()) { throw new IllegalAccessError( "conflicting non-public interface class loaders"); } } else { nonPublicLoader = cl.getClassLoader(); hasNonPublicInterface = true; } } classObjs[i] = cl; } try { return Proxy.getProxyClass(hasNonPublicInterface ? nonPublicLoader : latestLoader, classObjs); } catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); } }
0 0
(Domain) IllegalBoundaryException 1
              
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public void setBoundary(byte[] boundary) throws IllegalBoundaryException { if (boundary.length != boundaryLength - BOUNDARY_PREFIX.length) { throw new IllegalBoundaryException( "The length of a boundary token can not be changed"); } System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length); }
0 1
              
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public void setBoundary(byte[] boundary) throws IllegalBoundaryException { if (boundary.length != boundaryLength - BOUNDARY_PREFIX.length) { throw new IllegalBoundaryException( "The length of a boundary token can not be changed"); } System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length); }
(Lib) InstantiationException 1
              
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected TrustManager[] getTrustManagers(String keystoreType, String keystoreProvider, String algorithm) throws Exception { String crlf = endpoint.getCrlFile(); String className = endpoint.getTrustManagerClassName(); if(className != null && className.length() > 0) { ClassLoader classLoader = getClass().getClassLoader(); Class<?> clazz = classLoader.loadClass(className); if(!(TrustManager.class.isAssignableFrom(clazz))){ throw new InstantiationException(sm.getString( "jsse.invalidTrustManagerClassName", className)); } Object trustManagerObject = clazz.newInstance(); TrustManager trustManager = (TrustManager) trustManagerObject; return new TrustManager[]{ trustManager }; } TrustManager[] tms = null; KeyStore trustStore = getTrustStore(keystoreType, keystoreProvider); if (trustStore != null || endpoint.getTrustManagerClassName() != null) { if (crlf == null) { TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init(trustStore); tms = tmf.getTrustManagers(); } else { TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); CertPathParameters params = getParameters(algorithm, crlf, trustStore); ManagerFactoryParameters mfp = new CertPathTrustManagerParameters(params); tmf.init(mfp); tms = tmf.getTrustManagers(); } } return tms; }
0 5
              
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
Filter getFilter() throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { // Return the existing filter instance, if any if (this.filter != null) return (this.filter); // Identify the class loader we will be using String filterClass = filterDef.getFilterClass(); this.filter = (Filter) getInstanceManager().newInstance(filterClass); initFilter(); return (this.filter); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
void setFilterDef(FilterDef filterDef) throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { this.filterDef = filterDef; if (filterDef == null) { // Release any previously allocated filter instance if (this.filter != null){ if (Globals.IS_SECURITY_ENABLED) { try{ SecurityUtil.doAsPrivilege("destroy", filter); } catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); } SecurityUtil.remove(filter); } else { filter.destroy(); } if (!context.getIgnoreAnnotations()) { try { ((StandardContext) context).getInstanceManager().destroyInstance(this.filter); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); } } } this.filter = null; } else { // Allocate a new filter instance if necessary if (filterDef.getFilter() == null) { getFilter(); } } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { Class<?> clazz = loadClassMaybePrivileged(className, classLoader); return newInstance(clazz.newInstance(), clazz); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(final String className, final ClassLoader classLoader) throws IllegalAccessException, NamingException, InvocationTargetException, InstantiationException, ClassNotFoundException { Class<?> clazz = classLoader.loadClass(className); return newInstance(clazz.newInstance(), clazz); }
(Domain) InvalidContentTypeException 1 0 0
(Domain) InvalidFileNameException 1
              
// in java/org/apache/tomcat/util/http/fileupload/util/Streams.java
public static String checkFileName(String pFileName) { if (pFileName != null && pFileName.indexOf('\u0000') != -1) { // pFileName.replace("\u0000", "\\0") final StringBuffer sb = new StringBuffer(); for (int i = 0; i < pFileName.length(); i++) { char c = pFileName.charAt(i); switch (c) { case 0: sb.append("\\0"); break; default: sb.append(c); break; } } throw new InvalidFileNameException(pFileName, "Invalid file name: " + sb); } return pFileName; }
0 0
(Domain) JspException 1
              
// in java/org/apache/jasper/runtime/TagHandlerPool.java
public Tag get(Class<? extends Tag> handlerClass) throws JspException { Tag handler; synchronized (this) { if (current >= 0) { handler = handlers[current--]; return handler; } } // Out of sync block - there is no need for other threads to // wait for us to construct a tag for this thread. try { if (Constants.USE_INSTANCE_MANAGER_FOR_TAGS) { return (Tag) instanceManager.newInstance( handlerClass.getName(), handlerClass.getClassLoader()); } else { Tag instance = handlerClass.newInstance(); instanceManager.newInstance(instance); return instance; } } catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JspException(e.getMessage(), t); } }
1
              
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JspException(e.getMessage(), t); }
12
              
// in java/org/apache/jasper/tagplugins/jstl/Util.java
public static String resolveUrl( String url, String context, PageContext pageContext) throws JspException { // don't touch absolute URLs if (isAbsoluteUrl(url)) return url; // normalize relative URLs against a context root HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); if (context == null) { if (url.startsWith("/")) return (request.getContextPath() + url); else return url; } else { if (!context.startsWith("/") || !url.startsWith("/")) { throw new JspTagException( "In URL tags, when the \"context\" attribute is specified, values of both \"context\" and \"url\" must start with \"/\"."); } if (context.equals("/")) { // Don't produce string starting with '//', many // browsers interpret this as host name, not as // path on same host. return url; } else { return (context + url); } } }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
public Tag get(Class<? extends Tag> handlerClass) throws JspException { Tag handler; synchronized (this) { if (current >= 0) { handler = handlers[current--]; return handler; } } // Out of sync block - there is no need for other threads to // wait for us to construct a tag for this thread. try { if (Constants.USE_INSTANCE_MANAGER_FOR_TAGS) { return (Tag) instanceManager.newInstance( handlerClass.getName(), handlerClass.getClassLoader()); } else { Tag instance = handlerClass.newInstance(); instanceManager.newInstance(instance); return instance; } } catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JspException(e.getMessage(), t); } }
// in java/javax/servlet/jsp/tagext/TagSupport.java
Override public int doStartTag() throws JspException { return SKIP_BODY; }
// in java/javax/servlet/jsp/tagext/TagSupport.java
Override public int doEndTag() throws JspException { return EVAL_PAGE; }
// in java/javax/servlet/jsp/tagext/TagSupport.java
Override public int doAfterBody() throws JspException { return SKIP_BODY; }
// in java/javax/servlet/jsp/tagext/TagAdapter.java
Override public int doStartTag() throws JspException { throw new UnsupportedOperationException( "Illegal to invoke doStartTag() on TagAdapter wrapper"); }
// in java/javax/servlet/jsp/tagext/TagAdapter.java
Override public int doEndTag() throws JspException { throw new UnsupportedOperationException( "Illegal to invoke doEndTag() on TagAdapter wrapper"); }
// in java/javax/servlet/jsp/tagext/SimpleTagSupport.java
Override public void doTag() throws JspException, IOException { // NOOP by default }
// in java/javax/servlet/jsp/tagext/BodyTagSupport.java
Override public int doStartTag() throws JspException { return EVAL_BODY_BUFFERED; }
// in java/javax/servlet/jsp/tagext/BodyTagSupport.java
Override public int doEndTag() throws JspException { return super.doEndTag(); }
// in java/javax/servlet/jsp/tagext/BodyTagSupport.java
Override public void doInitBody() throws JspException { // NOOP by default }
// in java/javax/servlet/jsp/tagext/BodyTagSupport.java
Override public int doAfterBody() throws JspException { return SKIP_BODY; }
(Domain) JspPropertyNotWritableException 1
              
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void setValue(ELContext context, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { try { this.target.setValue(context, value); } catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
1
              
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); }
0
(Domain) JspTagException 1
              
// in java/org/apache/jasper/tagplugins/jstl/Util.java
public static String resolveUrl( String url, String context, PageContext pageContext) throws JspException { // don't touch absolute URLs if (isAbsoluteUrl(url)) return url; // normalize relative URLs against a context root HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); if (context == null) { if (url.startsWith("/")) return (request.getContextPath() + url); else return url; } else { if (!context.startsWith("/") || !url.startsWith("/")) { throw new JspTagException( "In URL tags, when the \"context\" attribute is specified, values of both \"context\" and \"url\" must start with \"/\"."); } if (context.equals("/")) { // Don't produce string starting with '//', many // browsers interpret this as host name, not as // path on same host. return url; } else { return (context + url); } } }
0 0
(Lib) NoSuchMethodException 1
              
// in java/org/apache/tomcat/util/IntrospectionUtils.java
public static Object callMethod1(Object target, String methodN, Object param1, String typeParam1, ClassLoader cl) throws Exception { if (target == null || param1 == null) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Assert: Illegal params " + target + " " + param1); } if (log.isDebugEnabled()) log.debug("IntrospectionUtils: callMethod1 " + target.getClass().getName() + " " + param1.getClass().getName() + " " + typeParam1); Class<?> params[] = new Class[1]; if (typeParam1 == null) params[0] = param1.getClass(); else params[0] = cl.loadClass(typeParam1); Method m = findMethod(target.getClass(), methodN, params); if (m == null) throw new NoSuchMethodException(target.getClass().getName() + " " + methodN); try { return m.invoke(target, new Object[] { param1 }); } catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; } }
0 2
              
// in java/org/apache/catalina/core/AprLifecycleListener.java
private static void terminateAPR() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { String methodName = "terminate"; Method method = Class.forName("org.apache.tomcat.jni.Library") .getMethod(methodName, (Class [])null); method.invoke(null, (Object []) null); aprAvailable = false; aprInitialized = false; sslInitialized = false; // Well we cleaned the pool in terminate. sslAvailable = false; // Well we cleaned the pool in terminate. fipsModeActive = false; }
// in java/org/apache/catalina/core/AprLifecycleListener.java
private static void initializeSSL() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { if ("off".equalsIgnoreCase(SSLEngine)) { return; } if (sslInitialized) { //only once per VM return; } sslInitialized = true; String methodName = "randSet"; Class<?> paramTypes[] = new Class[1]; paramTypes[0] = String.class; Object paramValues[] = new Object[1]; paramValues[0] = SSLRandomSeed; Class<?> clazz = Class.forName("org.apache.tomcat.jni.SSL"); Method method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); methodName = "initialize"; paramValues[0] = "on".equalsIgnoreCase(SSLEngine)?null:SSLEngine; method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); if("on".equalsIgnoreCase(FIPSMode)) { log.info(sm.getString("aprListener.initializingFIPS")); int result = SSL.fipsModeSet(1); // success is defined as return value = 1 if(1 == result) { fipsModeActive = true; log.info(sm.getString("aprListener.initializeFIPSSuccess")); } else { // This case should be handled by the native method, // but we'll make absolutely sure, here. String message = sm.getString("aprListener.initializeFIPSFailed"); log.error(message); throw new IllegalStateException(message); } } log.info(sm.getString("aprListener.initializedOpenSSL", SSL.versionString())); sslAvailable = true; }
(Lib) SSLException 1
              
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
protected void handShake() throws IOException { if( ssl.getWantClientAuth() ) { log.debug(sm.getString("jsseSupport.noCertWant")); } else { ssl.setNeedClientAuth(true); } if (ssl.getEnabledCipherSuites().length == 0) { // Handshake is never going to be successful. // Assume this is because handshakes are disabled log.warn(sm.getString("jsseSupport.serverRenegDisabled")); session.invalidate(); ssl.close(); return; } InputStream in = ssl.getInputStream(); int oldTimeout = ssl.getSoTimeout(); ssl.setSoTimeout(1000); byte[] b = new byte[1]; listener.reset(); ssl.startHandshake(); int maxTries = 60; // 60 * 1000 = example 1 minute time out for (int i = 0; i < maxTries; i++) { if (log.isTraceEnabled()) log.trace("Reading for try #" + i); try { int read = in.read(b); if (read > 0) { // Shouldn't happen as all input should have been swallowed // before trying to do the handshake. If it does, something // went wrong so lets bomb out now. throw new SSLException( sm.getString("jsseSupport.unexpectedData")); } } catch(SSLException sslex) { log.info(sm.getString("jsseSupport.clientCertError"), sslex); throw sslex; } catch (IOException e) { // ignore - presumably the timeout } if (listener.completed) { break; } } ssl.setSoTimeout(oldTimeout); if (listener.completed == false) { throw new SocketException("SSL Cert handshake timeout"); } }
0 0
(Domain) SizeLimitExceededException 1 0 0
(Lib) UnsupportedClassVersionError 1
              
// in java/org/apache/catalina/loader/WebappClassLoader.java
protected Class<?> findClassInternal(String name) throws ClassNotFoundException { if (!validate(name)) throw new ClassNotFoundException(name); String tempPath = name.replace('.', '/'); String classPath = tempPath + ".class"; ResourceEntry entry = null; if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, classPath); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, classPath); } if (entry == null) throw new ClassNotFoundException(name); Class<?> clazz = entry.loadedClass; if (clazz != null) return clazz; synchronized (this) { clazz = entry.loadedClass; if (clazz != null) return clazz; if (entry.binaryContent == null) throw new ClassNotFoundException(name); // Looking up the package String packageName = null; int pos = name.lastIndexOf('.'); if (pos != -1) packageName = name.substring(0, pos); Package pkg = null; if (packageName != null) { pkg = getPackage(packageName); // Define the package (if null) if (pkg == null) { try { if (entry.manifest == null) { definePackage(packageName, null, null, null, null, null, null, null); } else { definePackage(packageName, entry.manifest, entry.codeBase); } } catch (IllegalArgumentException e) { // Ignore: normal error due to dual definition of package } pkg = getPackage(packageName); } } if (securityManager != null) { // Checking sealing if (pkg != null) { boolean sealCheck = true; if (pkg.isSealed()) { sealCheck = pkg.isSealed(entry.codeBase); } else { sealCheck = (entry.manifest == null) || !isPackageSealed(packageName, entry.manifest); } if (!sealCheck) throw new SecurityException ("Sealing violation loading " + name + " : Package " + packageName + " is sealed."); } } try { clazz = defineClass(name, entry.binaryContent, 0, entry.binaryContent.length, new CodeSource(entry.codeBase, entry.certificates)); } catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); } entry.loadedClass = clazz; entry.binaryContent = null; entry.source = null; entry.codeBase = null; entry.manifest = null; entry.certificates = null; } return clazz; }
1
              
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); }
0
(Lib) UnsupportedEncodingException 1
              
// in java/org/apache/tomcat/util/buf/B2CConverter.java
public static Charset getCharset(String enc) throws UnsupportedEncodingException{ // Encoding names should all be ASCII String lowerCaseEnc = enc.toLowerCase(Locale.US); Charset charset = encodingToCharsetCache.get(lowerCaseEnc); if (charset == null) { // Pre-population of the cache means this must be invalid throw new UnsupportedEncodingException( sm.getString("b2cConverter.unknownEncoding", enc)); } return charset; }
0 28
              
// in java/org/apache/jasper/tagplugins/jstl/Util.java
public String getString() throws UnsupportedEncodingException { if (isWriterUsed) return sw.toString(); else if (isStreamUsed) { if (this.charEncoding != null && !this.charEncoding.equals("")) return bos.toString(charEncoding); else return bos.toString("ISO-8859-1"); } else return ""; // target didn't write anything }
// in java/org/apache/jasper/compiler/SmapUtil.java
void addSDE() throws UnsupportedEncodingException, IOException { copy(4 + 2 + 2); // magic min/maj version int constantPoolCountPos = genPos; int constantPoolCount = readU2(); if (log.isDebugEnabled()) log.debug("constant pool count: " + constantPoolCount); writeU2(constantPoolCount); // copy old constant pool return index of SDE symbol, if found sdeIndex = copyConstantPool(constantPoolCount); if (sdeIndex < 0) { // if "SourceDebugExtension" symbol not there add it writeUtf8ForSDE(); // increment the countantPoolCount sdeIndex = constantPoolCount; ++constantPoolCount; randomAccessWriteU2(constantPoolCountPos, constantPoolCount); if (log.isDebugEnabled()) log.debug("SourceDebugExtension not found, installed at: " + sdeIndex); } else { if (log.isDebugEnabled()) log.debug("SourceDebugExtension found at: " + sdeIndex); } copy(2 + 2 + 2); // access, this, super int interfaceCount = readU2(); writeU2(interfaceCount); if (log.isDebugEnabled()) log.debug("interfaceCount: " + interfaceCount); copy(interfaceCount * 2); copyMembers(); // fields copyMembers(); // methods int attrCountPos = genPos; int attrCount = readU2(); writeU2(attrCount); if (log.isDebugEnabled()) log.debug("class attrCount: " + attrCount); // copy the class attributes, return true if SDE attr found (not copied) if (!copyAttrs(attrCount)) { // we will be adding SDE and it isn't already counted ++attrCount; randomAccessWriteU2(attrCountPos, attrCount); if (log.isDebugEnabled()) log.debug("class attrCount incremented"); } writeAttrForSDE(sdeIndex); }
// in java/org/apache/jasper/compiler/SmapUtil.java
int copyConstantPool(int constantPoolCount) throws UnsupportedEncodingException, IOException { int sdeIndex = -1; // copy const pool index zero not in class file for (int i = 1; i < constantPoolCount; ++i) { int tag = readU1(); writeU1(tag); switch (tag) { case 7 : // Class case 8 : // String if (log.isDebugEnabled()) log.debug(i + " copying 2 bytes"); copy(2); break; case 9 : // Field case 10 : // Method case 11 : // InterfaceMethod case 3 : // Integer case 4 : // Float case 12 : // NameAndType if (log.isDebugEnabled()) log.debug(i + " copying 4 bytes"); copy(4); break; case 5 : // Long case 6 : // Double if (log.isDebugEnabled()) log.debug(i + " copying 8 bytes"); copy(8); i++; break; case 1 : // Utf8 int len = readU2(); writeU2(len); byte[] utf8 = readBytes(len); String str = new String(utf8, "UTF-8"); if (log.isDebugEnabled()) log.debug(i + " read class attr -- '" + str + "'"); if (str.equals(nameSDE)) { sdeIndex = i; } writeBytes(utf8); break; default : throw new IOException("unexpected tag: " + tag); } } return sdeIndex; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, 1, 1, 4096); }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, startline, startcolumn, 4096); }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
Override public String getString(final String charset) throws UnsupportedEncodingException { return new String(get(), charset); }
// in java/org/apache/tomcat/util/http/fileupload/ByteArrayOutputStream.java
public String toString(String enc) throws UnsupportedEncodingException { return new String(toByteArray(), enc); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
public static Charset getCharset(String enc) throws UnsupportedEncodingException{ // Encoding names should all be ASCII String lowerCaseEnc = enc.toLowerCase(Locale.US); Charset charset = encodingToCharsetCache.get(lowerCaseEnc); if (charset == null) { // Pre-population of the cache means this must be invalid throw new UnsupportedEncodingException( sm.getString("b2cConverter.unknownEncoding", enc)); } return charset; }
// in java/org/apache/el/parser/SimpleCharStream.java
public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); }
// in java/org/apache/el/parser/SimpleCharStream.java
public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, 1, 1, 4096); }
// in java/org/apache/el/parser/SimpleCharStream.java
public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, startline, startcolumn, 4096); }
// in java/org/apache/catalina/realm/RealmBase.java
protected Charset getDigestCharset() throws UnsupportedEncodingException { if (digestEncoding == null) { return B2CConverter.ISO_8859_1; } else { return B2CConverter.getCharset(getDigestEncoding()); } }
// in java/org/apache/catalina/servlets/CGIServlet.java
protected void setupFromRequest(HttpServletRequest req) throws UnsupportedEncodingException { boolean isIncluded = false; // Look to see if this request is an include if (req.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI) != null) { isIncluded = true; } if (isIncluded) { this.contextPath = (String) req.getAttribute( RequestDispatcher.INCLUDE_CONTEXT_PATH); this.servletPath = (String) req.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); this.pathInfo = (String) req.getAttribute( RequestDispatcher.INCLUDE_PATH_INFO); } else { this.contextPath = req.getContextPath(); this.servletPath = req.getServletPath(); this.pathInfo = req.getPathInfo(); } // If getPathInfo() returns null, must be using extension mapping // In this case, pathInfo should be same as servletPath if (this.pathInfo == null) { this.pathInfo = this.servletPath; } // If the request method is GET, POST or HEAD and the query string // does not contain an unencoded "=" this is an indexed query. // The parsed query string becomes the command line parameters // for the cgi command. if (req.getMethod().equals("GET") || req.getMethod().equals("POST") || req.getMethod().equals("HEAD")) { String qs; if (isIncluded) { qs = (String) req.getAttribute( RequestDispatcher.INCLUDE_QUERY_STRING); } else { qs = req.getQueryString(); } if (qs != null && qs.indexOf("=") == -1) { StringTokenizer qsTokens = new StringTokenizer(qs, "+"); while ( qsTokens.hasMoreTokens() ) { cmdLineParameters.add(URLDecoder.decode(qsTokens.nextToken(), parameterEncoding)); } } } }
// in java/org/apache/catalina/connector/Request.java
Override public void setCharacterEncoding(String enc) throws UnsupportedEncodingException { if (usingReader) { return; } // Ensure that the specified encoding is valid byte buffer[] = new byte[1]; buffer[0] = (byte) 'a'; // Confirm that the encoding name is valid B2CConverter.getCharset(enc); // Save the validated encoding coyoteRequest.setCharacterEncoding(enc); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public void setCharacterEncoding(String env) throws java.io.UnsupportedEncodingException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } request.setCharacterEncoding(env); }
// in java/org/apache/catalina/core/ApplicationPart.java
public String getString(String encoding) throws UnsupportedEncodingException { return fileItem.getString(encoding); }
// in java/org/apache/catalina/util/RequestUtil.java
public static void parseParameters(Map<String,String[]> map, byte[] data, String encoding) throws UnsupportedEncodingException { Charset charset = B2CConverter.getCharset(encoding); if (data != null && data.length > 0) { int ix = 0; int ox = 0; String key = null; String value = null; while (ix < data.length) { byte c = data[ix++]; switch ((char) c) { case '&': value = new String(data, 0, ox, charset); if (key != null) { putMapEntry(map, key, value); key = null; } ox = 0; break; case '=': if (key == null) { key = new String(data, 0, ox, charset); ox = 0; } else { data[ox++] = c; } break; case '+': data[ox++] = (byte)' '; break; case '%': data[ox++] = (byte)((convertHexDigit(data[ix++]) << 4) + convertHexDigit(data[ix++])); break; default: data[ox++] = c; } } //The last value does not end in '&'. So save it now. if (key != null) { value = new String(data, 0, ox, charset); putMapEntry(map, key, value); } } }
// in java/javax/servlet/http/HttpServlet.java
Override public PrintWriter getWriter() throws UnsupportedEncodingException { if (writer == null) { OutputStreamWriter w; w = new OutputStreamWriter(noBody, getCharacterEncoding()); writer = new PrintWriter(w); } return writer; }
// in java/javax/servlet/ServletRequestWrapper.java
Override public void setCharacterEncoding(String enc) throws java.io.UnsupportedEncodingException { this.request.setCharacterEncoding(enc); }
(Lib) ZipException 1
              
// in java/org/apache/catalina/startup/ExpandWar.java
public static String expand(Host host, URL war, String pathname) throws IOException { // Make sure that there is no such directory already existing File docBase = new File(host.getAppBaseFile(), pathname); if (docBase.exists()) { // War file is already installed return (docBase.getAbsolutePath()); } // Create the new document base directory docBase.mkdir(); // Expand the WAR into the new document base directory String canonicalDocBasePrefix = docBase.getCanonicalPath(); if (!canonicalDocBasePrefix.endsWith(File.separator)) { canonicalDocBasePrefix += File.separator; } JarURLConnection juc = (JarURLConnection) war.openConnection(); juc.setUseCaches(false); JarFile jarFile = null; InputStream input = null; boolean success = false; try { jarFile = juc.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String name = jarEntry.getName(); File expandedFile = new File(docBase, name); if (!expandedFile.getCanonicalPath().startsWith( canonicalDocBasePrefix)) { // Trying to expand outside the docBase // Throw an exception to stop the deployment throw new IllegalArgumentException( sm.getString("expandWar.illegalPath",war, name, expandedFile.getCanonicalPath(), canonicalDocBasePrefix)); } int last = name.lastIndexOf('/'); if (last >= 0) { File parent = new File(docBase, name.substring(0, last)); if (!parent.mkdirs() && !parent.isDirectory()) { throw new IOException( sm.getString("expandWar.createFailed", parent)); } } if (name.endsWith("/")) { continue; } input = jarFile.getInputStream(jarEntry); if(null == input) throw new ZipException(sm.getString("expandWar.missingJarEntry", jarEntry.getName())); // Bugzilla 33636 expand(input, expandedFile); long lastModified = jarEntry.getTime(); if ((lastModified != -1) && (lastModified != 0)) { expandedFile.setLastModified(lastModified); } input.close(); input = null; } success = true; } catch (IOException e) { throw e; } finally { if (!success) { // If something went wrong, delete expanded dir to keep things // clean deleteDir(docBase); } if (input != null) { try { input.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } input = null; } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } } // Return the absolute path to our new document base directory return (docBase.getAbsolutePath()); }
0 0
(Domain) ItemSkippedException 4
              
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public int read() throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (available() == 0) { if (makeAvailable() == 0) { return -1; } } ++total; int b = buffer[head++]; if (b >= 0) { return b; } return b + BYTE_POSITIVE_OFFSET; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public int read(byte[] b, int off, int len) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (len == 0) { return 0; } int res = available(); if (res == 0) { res = makeAvailable(); if (res == 0) { return -1; } } res = Math.min(res, len); System.arraycopy(buffer, head, b, off, res); head += res; total += res; return res; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public long skip(long bytes) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } int av = available(); if (av == 0) { av = makeAvailable(); if (av == 0) { return 0; } } long res = Math.min(av, bytes); head += res; return res; }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public InputStream openStream() throws IOException { if (opened) { throw new IllegalStateException( "The stream was already opened."); } if (((Closeable) stream).isClosed()) { throw new FileItemStream.ItemSkippedException(); } return stream; }
0 0
Explicit thrown (throw new...): 1615/2064
Explicit thrown ratio: 78.2%
Builder thrown ratio: 1.3%
Variable thrown ratio: 20.7%
Checked Runtime Total
Domain 224 137 361
Lib 218 560 778
Total 442 697

Caught Exceptions Summary

A (Domain) exception is defined in the application. A (Lib) exception is defined in the JDK or in a library. An exception can be caught, and it happens that the catch block contains a throw (e.g. for wrapping a low-level exception). Hovering over a number triggers showing code snippets from the application code.

Type Exception Caught
(directly)
Caught
with Thrown
(Lib) Exception 475
            
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { e.printStackTrace(); result = null; }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception ex) { maxSize = -1; }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JspException(e.getMessage(), t); }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn("Error processing preDestroy on tag instance of " + handler.getClass().getName(), t); }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn("Error processing preDestroy on tag instance of " + handler.getClass().getName(), t); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException ("error in invoking method", ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (writer != null) { try { writer.close(); writer = null; } catch (Exception e1) { // do nothing } } // Remove the generated .java file File file = new File(javaFileName); if (file.exists()) { if (!file.delete()) { log.warn(Localizer.getMessage( "jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath())); } } throw e; }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e1) { // do nothing }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e2) { // do nothing }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (log.isDebugEnabled()) log.debug("Problem accessing resource. Treat as outdated.", e); return true; }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { // Remove as much as possible, log possible exceptions log.warn(Localizer.getMessage("jsp.warning.compiler.classfile.delete.fail.unknown"), e); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { // Remove as much as possible, log possible exceptions log.warn(Localizer.getMessage("jsp.warning.compiler.classfile.delete.fail.unknown"), e); }
// in java/org/apache/jasper/compiler/ParserController.java
catch (Exception any) { }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Exception ex) { err.jspError(mark, "jsp.error.tld.unable_to_read", jarResource.getUrl(), tldName, ex.toString()); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Exception ex) { err.jspError("jsp.error.tld.unable_to_get_jar", uri, ex .toString()); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Exception e) { err.jspError("jsp.error.teiclass.instantiation", teiClassName, e); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Exception e) { err.jspError("jsp.error.tlvclass.instantiation", validatorClass, e); }
// in java/org/apache/jasper/compiler/Parser.java
catch (Exception ex) { err.jspError(start, ex.getMessage()); }
// in java/org/apache/jasper/compiler/Parser.java
catch (Exception e) { err.jspError(start, "jsp.error.loadclass.taghandler", handlerClassName, tagName); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
catch (Exception e) { // ignore errors }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage( "jsp.error.internal.tldinit", ex.getMessage()), ex); }
// in java/org/apache/jasper/compiler/JspReader.java
catch (Exception any) { if(log.isDebugEnabled()) { log.debug("Exception closing reader: ", any); } }
// in java/org/apache/jasper/compiler/JspReader.java
catch (Exception any) { if(log.isDebugEnabled()) { log.debug("Exception closing reader: ", any); } }
// in java/org/apache/jasper/compiler/Generator.java
catch (Exception e) { // Cannot instantiate the specified class, either a // compilation error or a runtime error will be raised, // depending on a compiler flag. if (ctxt.getOptions() .getErrorOnUseBeanInvalidClassAttribute()) { err.jspError(n, "jsp.error.invalid.bean", klass); } if (canonicalName == null) { // Doing our best here to get a canonical name // from the binary name, should work 99.99% of time. canonicalName = klass.replace('$', '.'); } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (EnableDTDValidationException e) { saxParser = getSAXParser(true, jspDocParser); jspDocParser.isValidating = true; if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } inStream = JspUtil.getInputStream(path, jarFile, jspDocParser.ctxt); saxParser.parse(new InputSource(inStream), jspDocParser); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception any) { }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception any) { }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { jspDocParser.err.jspError(e); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { throw new SAXException( Localizer.getMessage("jsp.error.loadclass.taghandler", handlerClassName, qName), e); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { throw new SAXException(e); }
// in java/org/apache/jasper/compiler/TagPluginManager.java
catch (Exception e) { throw new JasperException(e); }
// in java/org/apache/jasper/compiler/Validator.java
catch (Exception e) { err.jspError (n, "jsp.error.coerce_to_type", tldAttr.getName(), expectedType, attrs.getValue(i)); }
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch(Exception e) { context.log("Security Init for context failed",e); }
// in java/org/apache/jasper/compiler/JspConfig.java
catch (Exception ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JasperException(t); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); // Log any exception, since it can't be passed along log.error(Localizer.getMessage("jsp.error.file.not.found", e.getMessage()), t); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception je) { // If anything goes wrong, just revert to the original behaviour if (ex instanceof JasperException) { return (JasperException) ex; } return new JasperException(ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (Exception ex) { JasperException je = new JasperException( Localizer.getMessage("jsp.error.unable.compile"), ex); // Cache compilation exception jsw.setCompilationException(je); throw je; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); }
// in java/org/apache/jasper/JspC.java
catch( Exception ex ) { uriRoot = s; }
// in java/org/apache/jasper/JspC.java
catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); }
// in java/org/apache/naming/factory/SendMailFactory.java
catch (Exception e) {/*Ignore*/}
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
catch (Exception e) { throw new ServiceException(e); }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { if (e instanceof InvocationTargetException) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } } NamingException ex = new NamingException ("Error while reading Wsdl File"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
catch (Exception x) { if (x instanceof InvocationTargetException) { Throwable cause = x.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } if (cause instanceof Exception) { x = (Exception) cause; } } if (x instanceof NamingException) throw (NamingException)x; else { NamingException nx = new NamingException(x.getMessage()); nx.initCause(x); throw nx; } }
// in java/org/apache/naming/factory/ResourceFactory.java
catch (Exception e) { if (e instanceof NamingException) throw (NamingException) e; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (Exception e) { NamingException ne = new NamingException(e.getMessage()); ne.initCause(e); throw ne; }
// in java/org/apache/naming/NamingContext.java
catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); }
// in java/org/apache/naming/resources/WARDirContext.java
catch (Exception e) { throw new IllegalArgumentException (sm.getString("warResources.invalidWar", e.getMessage())); }
// in java/org/apache/naming/resources/WARDirContext.java
catch (Exception e) { // Ignore }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (Exception e) { // Ignore }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (Exception e) { throw new IllegalArgumentException(sm.getString( "resources.invalidCache", cacheClassName), e); }
// in java/org/apache/naming/resources/ResourceCache.java
catch (Exception e) { // Ignore: the reliability of this lookup is not critical }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (Exception e) { // Ignore }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (Exception e) { // Report error System.err.println("Handler error"); e.printStackTrace(); }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { reportError(null, e, ErrorManager.FORMAT_FAILURE); return; }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { reportError(null, e, ErrorManager.WRITE_FAILURE); return; }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { reportError(null, e, ErrorManager.CLOSE_FAILURE); }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { reportError(null, e, ErrorManager.FLUSH_FAILURE); }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { // Ignore }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { // Ignore and fallback to defaults setFormatter(new SimpleFormatter()); }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { reportError(null, e, ErrorManager.OPEN_FAILURE); writer = null; }
// in java/org/apache/juli/AsyncFileHandler.java
catch (Exception x) { x.printStackTrace(); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().error(sm.getString( "abstractProtocolHandler.mbeanRegistrationFailed", tpOname, getName()), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.initError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.startError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.pauseError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.resumeError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.stopError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().error(sm.getString("abstractProtocolHandler.destroyError", getName()), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().warn("Error registering request"); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().warn("Error unregistering request", e); }
// in java/org/apache/coyote/ajp/Constants.java
catch (Exception e) { // Do nothing }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Exception e) { this.compressionLevel = 0; }
// in java/org/apache/coyote/http11/Http11Processor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11Processor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/AbstractHttp11Protocol.java
catch (Exception ex) { getLog().warn("Failed to init light protocol " + impl, ex); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Exception e) { //TODO Auto-generated catch block e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Exception e) { noApr = new IOException("APR not present", e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Exception ex) { // ignore - the acceptor may have shut down by itself. }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
catch (Exception e) { e.printStackTrace(); }
// in java/org/apache/tomcat/util/net/URL.java
catch (Exception e) { throw new MalformedURLException(e.toString()); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
catch (Exception cx) { IOException x = new IOException(cx); throw x; }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
catch (Exception ignore) {}
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
catch (Exception ignore) {}
// in java/org/apache/tomcat/util/net/SSLImplementation.java
catch (Exception e) { if (logger.isTraceEnabled()) logger.trace("Error creating " + implementations[i], e); }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
catch (Exception e) { if (logger.isDebugEnabled()) logger .debug("Error loading SSL Implementation " + className, e); throw new ClassNotFoundException( "Error loading SSL Implementation " + className + " :" + e.toString()); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch( Exception ignore ) { if (log.isDebugEnabled())log.debug("",ignore); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch( Exception ignore ) { if (log.isDebugEnabled())log.debug("",ignore); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (Exception ignore){}
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Exception x ) { log.error("Unable to set attribute \""+name+"\" to \""+value+"\"",x); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception x) { log.error("", x); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (CancelledKeyException ckx) { try { socket.getPoller().cancelledKey(key,SocketStatus.DISCONNECT); }catch (Exception ignore) {} }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception ignore) {}
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "endpoint.debug.channelCloseFail"), e); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception e){ if (log.isDebugEnabled()) { log.debug(sm.getString( "endpoint.debug.socketCloseFail"), e); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception ignore) { }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception ignore) { }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception ignore) { }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception ignore) { }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Exception x ) { log.error("",x); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { return -1; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw e; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { // Pool not created so no need to destroy it. log.error(sm.getString("endpoint.sendfile.error"), e); data.socket = 0; return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { log.error(sm.getString("endpoint.sendfile.error"), e); Pool.destroy(data.fdpool); data.socket = 0; return false; }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
catch ( Exception x ) { getLog().error("Unable to set attribute \""+name+"\" to \""+value+"\"",x); return false; }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
catch(Exception e) { if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("endpoint.debug.unlock", "" + getPort()), e); } }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
catch (Exception e) { // Ignore }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Exception e) { log.error(sm.getString("endpoint.err.close"), e); }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch(Exception ex) { log.info(sm.getString( "jseeSupport.certTranslationError", certs[i]), ex); return null; }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch(Exception bex) { // ignore. }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception e) { if( e instanceof IOException ) throw (IOException)e; throw new IOException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception ex) { log.warn("Bad maxCertLength: "+trustLength); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception ex) { // Ignore }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (Exception e) { /* * Possible ways of getting here * socket.accept() throws a SecurityException * socket.setSoTimeout() throws a SocketException * socket.accept() throws some other exception (after a JDK change) * In these cases the test won't work so carry on - essentially * the behaviour before this patch * socket.accept() throws a SocketTimeoutException * In this case all is well so carry on */ }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (Exception e) { // ignore it }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (Exception e) { return -1; }
// in java/org/apache/tomcat/util/http/fileupload/FileCleaningTracker.java
catch (Exception e) { continue; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (Exception e) { }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (Exception e) { ex=e; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (Exception e) { throw new MBeanException (e, "Cannot instantiate ModelMBean of class " + getClassName()); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { // Not having a particular attribute in the response // is the indication of a getter problem }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch(Exception ex) { log.error("Error sending notification " + name, ex); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { // Ignore all exceptions }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsSerSource.java
catch( Exception ex ) { log.error( "Error reading descriptors " + source + " " + ex.toString(), ex); throw ex; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java
catch (Exception e) { log.error("Error digesting Registry data", e); throw e; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsIntrospectionSource.java
catch( Exception ex ) { log.error( "Error reading descriptors ", ex); }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsIntrospectionSource.java
catch( Exception ex ) { ex.printStackTrace(); return null; }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Exception t ) { if( failFirst ) throw t; log.info("Error initializing " + current + " " + t.toString()); }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch (Exception e) { log.info( "Can't find metadata for object" + oname ); return null; }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch (Exception e) { log.info( "Can't find metadata " + oname ); return null; }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Exception ex) { log.error("Error registering " + oname, ex ); throw ex; }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch(Exception ex ) { log.error("Error loading " + dURL); }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
catch (Exception e) { // log message and error if (digester.log.isInfoEnabled()) { digester.log.info("[FactoryCreateRule] Create exception ignored: " + ((e.getMessage() == null) ? e.getClass().getName() : e.getMessage())); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule] Ignored exception:", e); } } exceptionIgnoredStack.push(Boolean.TRUE); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Digester.getParser: ", e); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Finish event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Body event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("End event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Begin event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { // ignore - let the attribute have its original value }
// in java/org/apache/tomcat/util/digester/Digester.java
catch(Exception e) { return bodyText; // return unchanged data }
// in java/org/apache/tomcat/util/digester/XercesParser.java
catch (Exception ex){ // Do nothing. }
// in java/org/apache/tomcat/util/digester/ParserFeatureSetterFactory.java
catch (Exception ex){ isXercesUsed = false; }
// in java/org/apache/el/lang/FunctionMapperImpl.java
catch (Exception e) { e.printStackTrace(); }
// in java/org/apache/el/lang/ExpressionBuilder.java
catch (Exception e) { throw new ELException( MessageFactory.get("error.parseFail", expr), e); }
// in java/org/apache/el/lang/ExpressionBuilder.java
catch (Exception e) { if (e instanceof ELException) { throw (ELException) e; } else { throw (new ELException(e)); } }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString("contextConfig.contextMissing", contextXml) , e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString( "contextConfig.defaultError", filename, file), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e); ok = false; }
// in java/org/apache/catalina/startup/TldConfig.java
catch (Exception e) { log.error(sm.getString( "tldConfig.execute", context.getName()), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.threaded.error"), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", contextXml.getAbsolutePath())); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployWar.threaded.error"), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", war.getAbsolutePath())); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", war.getAbsolutePath())); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDir.threaded.error"), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", xml)); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.warn(sm.getString ("hostConfig.context.restart", app.name), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString("hostConfig.jmx.register", oname), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString("hostConfig.jmx.unregister", oname), e); }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage())); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { log.error("Catalina.stop: ", e); System.exit(1); }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", file), e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", getConfigFile()), e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", "server-embed.xml"), e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { log.warn("Catalina.start using " + getConfigFile() + ": " , e); return; }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { e.printStackTrace(System.out); }
// in java/org/apache/catalina/startup/PasswdUserDatabase.java
catch (Exception e) { if (reader != null) { try { reader.close(); } catch (IOException f) { // Ignore } reader = null; } }
// in java/org/apache/catalina/startup/UserConfig.java
catch (Exception e) { host.getLogger().error(sm.getString("userConfig.database"), e); return; }
// in java/org/apache/catalina/startup/UserConfig.java
catch (Exception e) { host.getLogger().error(sm.getString("userConfig.deploy.threaded.error"), e); }
// in java/org/apache/catalina/startup/UserConfig.java
catch (Exception e) { host.getLogger().error(sm.getString("userConfig.error", user), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.jdbcRemoveFailed", contextName), t); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.stopTimerThreadFail", thread.getName(), contextName), t); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badKey", args[1]), e); args[2] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badValue", args[3]), e); args[4] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { return null; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { clazz = null; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Exception e) { // Log and continue anyway, this is not critical log.error("Error registering jndi stream handler", e); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Exception e) { log.error("LifecycleException ", e); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Exception ex) { // Catch the exception if there is an empty jar file // Should ignore and continue loading other jar files // in the dir }
// in java/org/apache/catalina/loader/WebappLoader.java
catch( Exception ex ) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) log.debug("getClasspath ", ex); }
// in java/org/apache/catalina/realm/MemoryRealm.java
catch (Exception e) { log.warn(sm.getString("memoryRealm.xmlFeatureEncoding"), e); }
// in java/org/apache/catalina/realm/MemoryRealm.java
catch (Exception e) { throw new LifecycleException (sm.getString("memoryRealm.readXml"), e); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (Exception e) { connectionAttempt = 1; // log the first exception. containerLog.warn(sm.getString("jndiRealm.exception"), e); // Try connecting to the alternate url. context = new InitialDirContext(getDirectoryContextEnvironment()); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (Exception e) { // Log the problem for posterity containerLog.error(sm.getString("dataSourceRealm.exception"), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (Exception e) { if (log.isDebugEnabled()) log.debug(" Validity exception", e); return (null); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (Exception e) { log.error(sm.getString("realmBase.digest"), e); return (credentials); }
// in java/org/apache/catalina/realm/RealmBase.java
catch(Exception ex) { log.error(ex); return credentials; }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (Exception e) { log.warn("Error processing configuration file " + file.getAbsolutePath(), e); return; }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
catch (Exception e) { log.warn("Error during context [" + context.getName() + "] destroy ", e); }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
catch (Exception e) { log.error("Exception creating UserDatabase MBeans for " + name, e); }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating group [" + groupname + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating role [" + rolename + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating user [" + username + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying group [" + groupname + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying role [" + rolename + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying user [" + username + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (Exception ParseException) { // Ignore }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
catch (Exception e) { log.warn(sm.getString("memoryUserDatabase.xmlFeatureEncoding"), e); }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorEqualsCondition.java
catch (Exception e) { // ignore access or connection open errors }
// in java/org/apache/catalina/ant/jmx/JMXAccessorCondition.java
catch (Exception e) { // ignore access or connection open errors }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
catch (Exception e) { if (isEcho()) handleErrorOutput(e.getMessage()); return "Can't query mbeans " + qry; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
catch (Exception e) { if (isEcho()) handleErrorOutput("Error getting attribute " + oname + " " + pname + attName + " " + e.toString()); continue; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/ant/ValidatorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException("Validation failure", e); } else { handleErrorOutput("Validation failure: " + e); } }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (Exception e) { log("HTMLManagerServlet.sessions[" + cn + "]", e); message = smClient.getString("managerServlet.exception", e.toString()); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch(Exception e) { message = smClient.getString ("htmlManagerServlet.deployUploadFail", e.getMessage()); log(message, e); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (Exception e) { // Assume false on failure for safety isDeployed = false; }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch (Exception ex) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch( Exception ex ) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch (Exception ex) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); return; }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch( Exception ex ) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { getServletContext().log (sm.getString("hostManagerServlet.startFailed", name), e); writer.println(smClient.getString( "hostManagerServlet.startFailed", name)); writer.println(smClient.getString( "hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { getServletContext().log(sm.getString( "hostManagerServlet.stopFailed", name), e); writer.println(smClient.getString("hostManagerServlet.stopFailed", name)); writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
catch (Exception e) { e.printStackTrace(); }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
catch (Exception e) { throw new ServletException(e); }
// in java/org/apache/catalina/manager/StatusTransformer.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/manager/JspHelper.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log(sm.getString("managerServlet.objectNameFail", name), e); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.storeConfig", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.save[" + path + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.check[" + displayPath + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.check[" + displayPath + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/util/SessionUtils.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); // stay silent }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { if ( x instanceof ChannelException ) throw (ChannelException)x; throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch (Exception sx) { log.error("Unable to deserialize message:"+msg,sx); return; }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { //this could be the channel listener throwing an exception, we should log it //as a warning. if ( log.isWarnEnabled() ) log.warn("Error receiving message:",x); throw new RemoteProcessException("Exception:"+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { log.error("Unable to find rpc channel, failed to send NoRpcChannelReply.",x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch (Exception x) { throw new ChannelException("Unable to add MessageDispatchInterceptor to interceptor chain.",x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { log.error("Unable to send heartbeat through Tribes interceptor stack. Will try to sleep again.",x); }
// in java/org/apache/catalina/tribes/group/RpcChannel.java
catch ( Exception x ) { if (excallback != null && !asyncReply) { excallback.replyFailed(rmsg.message, reply, sender, x); } else { log.error("Unable to send back reply in RpcChannel.",x); } }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( Exception x ) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( Exception x ) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpPingInterceptor.java
catch ( Exception x ) { log.warn("Unable to send ping from TCP ping thread.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( Exception x ) { log.warn("Unable to perform heartbeat on the TcpFailureDetector.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch (Exception x ) { log.error("Unable to perform failure detection check, assuming member down.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( Exception ignore ){}
// in java/org/apache/catalina/tribes/group/interceptors/TwoPhaseCommitInterceptor.java
catch ( Exception x ) { log.warn("Unable to perform heartbeat on the TwoPhaseCommit interceptor.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( Exception x ){ log.error("Unable to perform heartbeat.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/FragmentationInterceptor.java
catch ( Exception x ) { if ( log.isErrorEnabled() ) { log.error("Unable to perform heartbeat clean up in the frag interceptor",x); } }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
catch ( Exception ex ) { log.error("Unable to report back completed message.",ex); }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
catch ( Exception x ) { ChannelException cx = null; if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException(x); if ( log.isDebugEnabled() ) log.debug("Error while processing async message.",x); try { if (link.getHandler() != null) link.getHandler().handleError(cx, new UniqueId(msg.getUniqueId())); } catch ( Exception ex ) { log.error("Unable to report back error message.",ex); } }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
catch ( Exception ex ) { log.error("Unable to report back error message.",ex); }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch (Exception x) { if (tryRepFirst) return findExternalClass(name); else return findReplicationClass(name); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { if (log.isDebugEnabled()) { log.debug("Failed to close socket", x); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.error("Unable to run replication listener.", x); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch ( Exception x ) { if ( doListen() ) throw x; }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch ( Exception x ) { log.error("Unable to service bio socket", x); }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close socket", e); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close reader", e); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch ( Exception x ) { if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(Constants.FAIL_ACK_COMMAND); log.error("Error thrown from messageDataReceived.",x); }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close socket", e); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close reader", e); } }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
catch (Exception x) { if (cx == null) cx = new ChannelException(x); cx.addFaultyMember(destination[i],x); }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
catch (Exception x ) { if ( cx== null ) cx = new ChannelException(x); cx.addFaultyMember(destination[i],x); }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
catch ( Exception e ) { if ( x == null ) x = new ChannelException(e); x.addFaultyMember(mbr,e); }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
catch (Exception x){/* Ignore */}
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
catch ( Exception e){/* Ignore */}
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
catch ( Exception x){}
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
catch ( Exception x){}
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
catch ( Exception x){}
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
catch ( Exception x){}
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
catch ( Exception x ) { log.error("Unable to disconnect NioSender. msg="+x.getMessage()); if ( log.isDebugEnabled() ) log.debug("Unable to disconnect NioSender. msg="+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x ) { if (log.isTraceEnabled()) log.trace("Error sending message", x); int faulty = (cx == null)?0:cx.getFaultyMembers().length; if ( cx == null ) { if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException("Parallel NIO send failed.", x); } else { if (x instanceof ChannelException) cx.addFaultyMember( ( (ChannelException) x).getFaultyMembers()); } //count down the remaining on an error if (faulty<cx.getFaultyMembers().length) remaining -= (cx.getFaultyMembers().length-faulty); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x ) { try { this.disconnect(); } catch (Exception e) {/*Ignore*/} if ( x instanceof ChannelException ) throw (ChannelException)x; else throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception e) {/*Ignore*/}
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( Exception ignore){ state.setFailing(); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( Exception e ) { if ( x == null ) x = new ChannelException(e); x.addFaultyMember(mbr,e); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x){/*Ignore*/}
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( Exception e){/*Ignore*/}
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close selector", e); } }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( Exception x ) { log.warn("Error during keepalive test for sender:"+sender,x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception e){/*Ignore*/}
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (Exception e) { //this is common, since the sockets on the other //end expire after a certain time. if ( e instanceof CancelledKeyException ) { //do nothing } else if ( e instanceof IOException ) { //dont spew out stack traces for IO exceptions unless debug is enabled. if (log.isDebugEnabled()) log.debug ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"].", e); else log.warn ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"]."); } else if ( log.isErrorEnabled() ) { //this is a real error, log it. log.error("Exception caught in TcpReplicationThread.drainChannel.",e); } cancelKey(key); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( Exception e ) { log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (Exception x) { log.error("Error registering key for read:"+key,x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch ( Exception x ) { log.error("",x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception e) { if (log.isDebugEnabled()) log.debug("", e); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception iox) { if (log.isDebugEnabled()) log.debug("Unable to close datagram channel.",iox); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.error("Unable to close cluster receiver selector.", x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.error("Unable to run replication listener.", x); }
// in java/org/apache/catalina/tribes/transport/PooledSender.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "PooledSender.senderDisconnectFail"), e); } }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( Exception ignore){}
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (Exception x) { log.error("Unable to apply diff to key:" + entry.getKey(), x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( Exception x ) { log.error("Unable to send AbstractReplicatedMap.ping message",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (Exception x) { log.error("Unable to replicate out data for a LazyReplicatedMap.get operation", x); return null; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( Exception ignore) { ignore.printStackTrace(); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( Exception x ) { log.error("Deserialization error of the MapMessage.key",x); return null; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( Exception x ) { log.error("Deserialization error of the MapMessage.value",x); return null; }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x ) { log.error("Unable to parse mcastTTL="+properties.getProperty("mcastTTL"),x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x ) { log.error("Unable to parse mcastSoTimeout="+properties.getProperty("mcastSoTimeout"),x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x) { log.error("Unable to stop the mcast service, level:"+svc+".",x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch (Exception x) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x ) { log.error("Unable to send payload update.",x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x ) { log.error("Unable to send domain update.",x); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception ignore){}
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception ignore){}
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (Exception x) { log.error("Unable to process member disappeared message.", x); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception x ) { if (x instanceof InterruptedException) interrupted(); else { if (errorCounter==0 && doRunReceiver) log.warn("Error receiving mcast package. Sleeping 500ms",x); else if (log.isDebugEnabled()) log.debug("Error receiving mcast package"+(doRunReceiver?". Sleeping 500ms":"."),x); if (doRunReceiver) { try { Thread.sleep(500); } catch ( Exception ignore ){} if ( (++errorCounter)>=recoveryCounter ) { errorCounter=0; RecoveryThread.recover(McastServiceImpl.this); } } } }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception ignore ){}
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception x ) { if (errorCounter==0) log.warn("Unable to send mcast message.",x); else log.debug("Unable to send mcast message.",x); if ( (++errorCounter)>=recoveryCounter ) { errorCounter=0; RecoveryThread.recover(McastServiceImpl.this); } }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception ignore ) {}
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (Exception x) { log.warn("Recovery thread failed to stop membership service.", x); return false; }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (Exception x) { log.warn("Recovery thread failed to start membership service.", x); return false; }
// in java/org/apache/catalina/session/StoreBase.java
catch (Exception e) { manager.getContainer().getLogger().error("Session: "+keys[i]+"; ", e); try { remove(keys[i]); } catch (IOException e2) { manager.getContainer().getLogger().error("Error removing key", e2); } }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionCreated", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent( "afterSessionDestroyed", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/session/StandardSession.java
catch (Exception e) { manager.getContainer().getLogger().error( sm.getString("standardSession.logoutfail"), e); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { if (unbound != null) { context.fireContainerEvent( "afterSessionAttributeReplaced", listener); } else { context.fireContainerEvent("afterSessionAttributeAdded", listener); } } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionAttributeRemoved", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (Exception e) { container.getLogger().warn( sm.getString("cometConnectionManagerValve.event"), e); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (Exception e) { req.getWrapper().getParent().getLogger().warn(sm.getString( "cometConnectionManagerValve.listenerEvent"), e); }
// in java/org/apache/catalina/valves/PersistentValve.java
catch (Exception e) { container.getLogger().error("deserializeError"); }
// in java/org/apache/catalina/valves/PersistentValve.java
catch (Exception ex) { hsess = null; }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", environment.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", resource.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", resourceLink.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", environment.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", resource.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", resourceLink.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", cr.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", ce.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", crl.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", crl.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", ce.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", cr.getName()), e); }
// in java/org/apache/catalina/ha/context/ReplicatedContext.java
catch ( Exception x ) { log.error("Unable to start ReplicatedContext",x); throw new LifecycleException("Failed to start ReplicatedContext",x); }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
catch (Exception x) { log.warn("Unable to load meta data for class:"+clazz.getName()); return false; }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
catch ( Exception x ) { log.warn("Unable to register default cluster implementation with JMX",x); return false; }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
catch ( Exception x ) { log.warn("Unable to unregister default cluster implementation with JMX",x); return false; }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (Exception e) { throw new Exception("bad ProxyList"); }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (Exception ex) { log.error("Unable to connect to proxy: " + ex); close(i); }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (Exception ex) { log.error("Unable to send collected load information to proxy: " + ex); close(i); }
// in java/org/apache/catalina/ha/backend/HeartbeatListener.java
catch (Exception ex) { log.error("Unable to initialize info collection: " + ex); coll = null; return; }
// in java/org/apache/catalina/ha/backend/HeartbeatListener.java
catch (Exception ex) { log.error("Unable to initialize Sender: " + ex); sender = null; return; }
// in java/org/apache/catalina/ha/backend/HeartbeatListener.java
catch (Exception ex) { log.error("Unable to collect load information: " + ex); coll = null; return; }
// in java/org/apache/catalina/ha/backend/HeartbeatListener.java
catch (Exception ex) { log.error("Unable to send colllected load information: " + ex); }
// in java/org/apache/catalina/ha/backend/MultiCastSender.java
catch (Exception ex) { log.error("Unable to use multicast: " + ex); s = null; return -1; }
// in java/org/apache/catalina/ha/backend/MultiCastSender.java
catch (Exception ex) { log.error("Unable to send colllected load information: " + ex); s.close(); s = null; return -1; }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
catch ( Exception x ) { log.error("Unable to remove element:",x); info = new AttributeInfo(type, action, name, value); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
catch ( Exception x ) { log.error("Unable to remove element",x); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
catch ( Exception x ) { log.error("Unable to remove element",x); info = new AttributeInfo(); }
// in java/org/apache/catalina/ha/session/BackupManager.java
catch ( Exception x ) { log.error(sm.getString("backupManager.startUnable", getName()),x); throw new LifecycleException(sm.getString("backupManager.startFailed", getName()),x); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Exception sleep) { // }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Exception sleep) { }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Exception x) { log.error(sm.getString("deltaManager.receiveMessage.error",getName()), x); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Exception sleep) { }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
catch (Exception ignore) { }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
catch (Exception ignore) { }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception e) { log.error(sm.getString("farmWarDeployer.mbeanNameFail", engine.getName(), hostname),e); return; }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception ex) { log.error(ex); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception ex) { log.error(ex); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception ex) { log.error(sm.getString("farmWarDeployer.removeFailLocal", contextName), ex); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception x) { log.error(sm.getString("farmWarDeployer.modRemoveFail"), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception x) { log.error(sm.getString("farmWarDeployer.modInstallFail"), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception x) { log.error(sm.getString("farmWarDeployer.removeLocalFail"), x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to clone cluster manager, defaulting to org.apache.catalina.ha.session.DeltaManager", x); manager = new org.apache.catalina.ha.session.DeltaManager(); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to start cluster.", x); throw new LifecycleException(x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to stop cluster valve.", x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to send message through cluster sender.", x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to connect to replication system.", x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable remove cluster node from replication system.", x); }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
catch (Exception x) { // FIXME we have a lot of sends, but the trouble with one node stops the correct replication to other nodes! log.error(sm.getString("ReplicationValve.send.failure"), x); }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
catch ( Exception x ) { log.error(sm.getString("ReplicationValve.send.invalid.failure",invalidIds[i]),x); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { log.error(sm.getString( "coyoteConnector.protocolHandlerInstantiationFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { log.error(sm.getString ("coyoteConnector.protocolHandlerPauseFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { log.error(sm.getString ("coyoteConnector.protocolHandlerResumeFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerInitializationFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { String errPrefix = ""; if(this.service != null) { errPrefix += "service.getName(): \"" + this.service.getName() + "\"; "; } throw new LifecycleException (errPrefix + " " + sm.getString ("coyoteConnector.protocolHandlerStartFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerStopFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerDestroyFailed"), e); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception ex) { log.info(sm.getString("applicationFilterConfig.jmxRegisterFail", getFilterClass(), getFilterName()), ex); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch(Exception ex) { log.error(sm.getString( "applicationFilterConfig.jmxUnregisterFail", getFilterClass(), getFilterName()), ex); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Exception e) { // Should never happen log(sm.getString("applicationContext.mapping.error"), e); return (null); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Exception e) { // Unexpected log(sm.getString("applicationContext.lookup.error", path, getContextPath()), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Exception e) { // Unexpected log(sm.getString("applicationContext.lookup.error", path, getContextPath()), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.error(sm.getString("containerBase.threadedStartFailed"), e); fail = true; }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.error(sm.getString("containerBase.threadedStopFailed"), e); fail = true; }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.cluster", cluster), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.loader", loader), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.manager", manager), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.realm", realm), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.valve", current), e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (Exception x) { //log.error("Async.dispatch",x); throw new RuntimeException(x); }
// in java/org/apache/catalina/core/ApplicationFilterFactory.java
catch (Exception e) { // Note: The try catch is there because getFilter has a lot of // declared exceptions. However, the filter is allocated much // earlier Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/ApplicationFilterFactory.java
catch (Exception e) { // Note: The try catch is there because getFilter has a lot of // declared exceptions. However, the filter is allocated much // earlier }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ handleException(ex); return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (Exception e) { logger.warn(sm.getString("naming.jmxRegistrationFailed", e)); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.startFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.pauseFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.stopFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { String message = sm.getString( "standardService.connector.initFailed", connector); log.error(message, e); if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) throw new LifecycleException(message); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.destroyfailed", connector), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Exception ex) { log.error("standardContext.clusterFail", ex); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch(Exception e) { log.error("Error manager.start()", e); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch( Exception ex ) { log.error( "Error reseting context " + this + " " + ex, ex ); }
// in java/org/apache/catalina/core/ApplicationPart.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch( Exception ex ) { log.info("Error registering JSP monitoring with jmx " + instance); }
// in java/org/apache/catalina/core/StandardEngine.java
catch(Exception ex) { log.warn(sm.getString("standardEngine.jvmRouteFail")); }
// in java/org/apache/catalina/core/ThreadLocalLeakPreventionListener.java
catch (Exception e) { String msg = sm.getString( "threadLocalLeakPreventionListener.lifecycleEvent.error", event); log.error(msg, e); }
// in java/org/apache/catalina/core/ThreadLocalLeakPreventionListener.java
catch (Exception e) { String msg = sm.getString( "threadLocalLeakPreventionListener.containerEvent.error", event); log.error(msg, e); }
// in java/org/apache/catalina/util/SchemaResolver.java
catch (Exception e) { throw new SAXException(e); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (Exception e) { log.error(sm.getString("sessionIdGenerator.random", secureRandomClass), e); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (Exception e) { log.warn(sm.getString("lifecycleMBeanBase.registerFail", obj, name), e); }
// in java/org/apache/catalina/util/URLEncoder.java
catch (Exception e) { e.printStackTrace(); writer = new OutputStreamWriter(buf); }
// in java/org/apache/catalina/security/SecurityConfig.java
catch (java.lang.Exception ex){ if (log.isDebugEnabled()){ log.debug("Unable to load properties using CatalinaProperties", ex); } }
// in java/javax/el/BeanELResolver.java
catch (Exception e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (Exception e) { throw new ELException(e); }
137
            
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JspException(e.getMessage(), t); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException ("error in invoking method", ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (writer != null) { try { writer.close(); writer = null; } catch (Exception e1) { // do nothing } } // Remove the generated .java file File file = new File(javaFileName); if (file.exists()) { if (!file.delete()) { log.warn(Localizer.getMessage( "jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath())); } } throw e; }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage( "jsp.error.internal.tldinit", ex.getMessage()), ex); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { throw new SAXException( Localizer.getMessage("jsp.error.loadclass.taghandler", handlerClassName, qName), e); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { throw new SAXException(e); }
// in java/org/apache/jasper/compiler/TagPluginManager.java
catch (Exception e) { throw new JasperException(e); }
// in java/org/apache/jasper/compiler/JspConfig.java
catch (Exception ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JasperException(t); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (Exception ex) { JasperException je = new JasperException( Localizer.getMessage("jsp.error.unable.compile"), ex); // Cache compilation exception jsw.setCompilationException(je); throw je; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); }
// in java/org/apache/jasper/JspC.java
catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); }
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
catch (Exception e) { throw new ServiceException(e); }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { if (e instanceof InvocationTargetException) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } } NamingException ex = new NamingException ("Error while reading Wsdl File"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
catch (Exception x) { if (x instanceof InvocationTargetException) { Throwable cause = x.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } if (cause instanceof Exception) { x = (Exception) cause; } } if (x instanceof NamingException) throw (NamingException)x; else { NamingException nx = new NamingException(x.getMessage()); nx.initCause(x); throw nx; } }
// in java/org/apache/naming/factory/ResourceFactory.java
catch (Exception e) { if (e instanceof NamingException) throw (NamingException) e; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (Exception e) { NamingException ne = new NamingException(e.getMessage()); ne.initCause(e); throw ne; }
// in java/org/apache/naming/NamingContext.java
catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); }
// in java/org/apache/naming/resources/WARDirContext.java
catch (Exception e) { throw new IllegalArgumentException (sm.getString("warResources.invalidWar", e.getMessage())); }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (Exception e) { throw new IllegalArgumentException(sm.getString( "resources.invalidCache", cacheClassName), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.initError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.startError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.pauseError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.resumeError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.stopError", getName()), ex); throw ex; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/util/net/URL.java
catch (Exception e) { throw new MalformedURLException(e.toString()); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
catch (Exception cx) { IOException x = new IOException(cx); throw x; }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
catch (Exception e) { if (logger.isDebugEnabled()) logger .debug("Error loading SSL Implementation " + className, e); throw new ClassNotFoundException( "Error loading SSL Implementation " + className + " :" + e.toString()); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw e; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception e) { if( e instanceof IOException ) throw (IOException)e; throw new IOException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (Exception e) { throw new MBeanException (e, "Cannot instantiate ModelMBean of class " + getClassName()); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsSerSource.java
catch( Exception ex ) { log.error( "Error reading descriptors " + source + " " + ex.toString(), ex); throw ex; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java
catch (Exception e) { log.error("Error digesting Registry data", e); throw e; }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Exception t ) { if( failFirst ) throw t; log.info("Error initializing " + current + " " + t.toString()); }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Exception ex) { log.error("Error registering " + oname, ex ); throw ex; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Finish event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Body event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("End event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Begin event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { throw createSAXException(e); }
// in java/org/apache/el/lang/ExpressionBuilder.java
catch (Exception e) { throw new ELException( MessageFactory.get("error.parseFail", expr), e); }
// in java/org/apache/el/lang/ExpressionBuilder.java
catch (Exception e) { if (e instanceof ELException) { throw (ELException) e; } else { throw (new ELException(e)); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); }
// in java/org/apache/catalina/realm/MemoryRealm.java
catch (Exception e) { throw new LifecycleException (sm.getString("memoryRealm.readXml"), e); }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating group [" + groupname + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating role [" + rolename + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating user [" + username + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying group [" + groupname + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying role [" + rolename + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying user [" + username + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/ValidatorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException("Validation failure", e); } else { handleErrorOutput("Validation failure: " + e); } }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
catch (Exception e) { throw new ServletException(e); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { if ( x instanceof ChannelException ) throw (ChannelException)x; throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { //this could be the channel listener throwing an exception, we should log it //as a warning. if ( log.isWarnEnabled() ) log.warn("Error receiving message:",x); throw new RemoteProcessException("Exception:"+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch (Exception x) { throw new ChannelException("Unable to add MessageDispatchInterceptor to interceptor chain.",x); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( Exception x ) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( Exception x ) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch ( Exception x ) { if ( doListen() ) throw x; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x ) { try { this.disconnect(); } catch (Exception e) {/*Ignore*/} if ( x instanceof ChannelException ) throw (ChannelException)x; else throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch (Exception x) { throw new ChannelException(x); }
// in java/org/apache/catalina/ha/context/ReplicatedContext.java
catch ( Exception x ) { log.error("Unable to start ReplicatedContext",x); throw new LifecycleException("Failed to start ReplicatedContext",x); }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (Exception e) { throw new Exception("bad ProxyList"); }
// in java/org/apache/catalina/ha/session/BackupManager.java
catch ( Exception x ) { log.error(sm.getString("backupManager.startUnable", getName()),x); throw new LifecycleException(sm.getString("backupManager.startFailed", getName()),x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to start cluster.", x); throw new LifecycleException(x); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerInitializationFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { String errPrefix = ""; if(this.service != null) { errPrefix += "service.getName(): \"" + this.service.getName() + "\"; "; } throw new LifecycleException (errPrefix + " " + sm.getString ("coyoteConnector.protocolHandlerStartFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerStopFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerDestroyFailed"), e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (Exception x) { //log.error("Async.dispatch",x); throw new RuntimeException(x); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { String message = sm.getString( "standardService.connector.initFailed", connector); log.error(message, e); if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) throw new LifecycleException(message); }
// in java/org/apache/catalina/core/ApplicationPart.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/catalina/util/SchemaResolver.java
catch (Exception e) { throw new SAXException(e); }
// in java/javax/el/BeanELResolver.java
catch (Exception e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (Exception e) { throw new ELException(e); }
(Lib) IOException 451
            
// in java/org/apache/jasper/runtime/ServletResponseWrapperInclude.java
catch (IOException ioe) { }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
catch (IOException ex) { // ignore }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer.getMessage("jsp.error.flush"), ex); throw ise; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer .getMessage("jsp.error.attempt_to_clear_flushed_buffer")); ise.initCause(ex); throw ise; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch(IOException e) { buf.reset(); continue; }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
catch (IOException e) { err.jspError("jsp.error.file.not.found", path); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
catch (IOException ioe) { throw new JasperException(ioe); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException e) { log.error("Compilation error", e); }
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException ioe) {/*Ignore*/}
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException ioe) {/*Ignore*/}
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException exc) {/*Ignore*/}
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException exc) { log.error("Compilation error", exc); }
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException exc) { // Ignore }
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException exc) { log.error("Compilation error", exc); }
// in java/org/apache/jasper/compiler/WebXml.java
catch (IOException e) { log.error(Localizer.getMessage( "jsp.error.stream.close.failed")); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (IOException ioe) { jspDocParser.err.jspError("jsp.error.data.file.read", path, ioe); }
// in java/org/apache/jasper/compiler/JavacErrorDetail.java
catch (IOException ioe) { // Can't read files - ignore }
// in java/org/apache/jasper/compiler/JavacErrorDetail.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/jasper/compiler/JavacErrorDetail.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JasperLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IOException e) { throw new ServletException("Could not precompile jsp: " + jspFile, e); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IOException e) { throw e; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (IOException io) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), io); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { throw new JasperException(ioe); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { mapout = null; servletout = null; mappingout = null; }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // noting to do if it fails since we are done with it }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // since this is an optional default and a null value // for uriRoot has a non-error meaning, we can just // pass straight through }
// in java/org/apache/jasper/JspC.java
catch (IOException ex) { fis.close(); throw ex; }
// in java/org/apache/jasper/JspC.java
catch (IOException ex) { fos.close(); throw ex; }
// in java/org/apache/naming/resources/WARDirContext.java
catch (IOException e) { log.warn ("Exception closing WAR File " + base.getName(), e); }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (IOException e) { // Ignore }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (IOException e) { //Ignore }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (IOException e) { // Ignore }
// in java/org/apache/naming/resources/FileDirContext.java
catch (IOException e) { // Ignore }
// in java/org/apache/naming/resources/FileDirContext.java
catch (IOException e) { // Ignore }
// in java/org/apache/naming/resources/FileDirContext.java
catch (IOException e) { NamingException ne = new NamingException (sm.getString("resources.bindFailed", e)); ne.initCause(e); throw ne; }
// in java/org/apache/naming/resources/FileDirContext.java
catch (IOException e) { // Ignore }
// in java/org/apache/naming/resources/FileDirContext.java
catch (IOException e) { // Ignore }
// in java/org/apache/naming/resources/BaseDirContext.java
catch (IOException ioe) { log.warn(sm.getString("resources.addResourcesJarFail", url), ioe); }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (IOException e) { // Ignore }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (IOException e) { // Ignore }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IOException e) { // Ignore }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IOException e) { // Ignore }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IOException e) { // Critical problem, do something ... }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IOException e) { // Report error System.err.println("Configuration error"); e.printStackTrace(); }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/coyote/AbstractProtocol.java
catch (java.io.IOException e) { // IOExceptions are normal getLog().debug(sm.getString( "ajpprotocol.proto.ioexception.debug"), e); }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (IOException e) { error = true; break; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (IOException e) { error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (IOException e) { error = true; break; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch ( IOException x ) { //ignore }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch ( IOException x ) { // Ignore }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { // Set error flag error = true; return; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException iex) { // Ignore }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { response.setStatus(400); error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (IOException e) { error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (IOException e) { error = true; break; }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (IOException ioe) { log.warn(sm.getString("http11processor.socket.sslreneg",ioe)); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
catch ( IOException x ) { // Ignore }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
catch ( IOException x ) { //ignore }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
catch ( IOException x ) { // Ignore }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
catch ( IOException x ) { //ignore }
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Ignored exception while flushing gzip filter", e); } }
// in java/org/apache/coyote/http11/filters/BufferedInputFilter.java
catch(IOException ioe) { // No need for i18n - this isn't going to get logged anywhere throw new IllegalStateException( "Request body too large for buffer"); }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
catch (IOException ignore) { // If our write failed, then trailer write in finish() will fail // with IOException as well, but it will leave Deflater in more // consistent state. }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
catch (IOException ignored) { // Ignore. As OutputStream#close() says, the contract of close() // is to close the stream. It does not matter much if the // stream is not writable any more. }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { // Set error flag error = true; response.setErrorException(e); }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), e); } error = true; break; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { error = true; }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
catch ( IOException x ) { //ignore }
// in java/org/apache/coyote/spdy/SpdyAprNpnHandler.java
catch (IOException e) { }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (IOException e) { e.printStackTrace(); // Set error flag error = true; return; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (IOException e) { // Set error flag e.printStackTrace(); error = true; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (IOException iex) { // Ignore }
// in java/org/apache/coyote/spdy/SpdyProxyProtocol.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (IOException e) { apr.reset(); throw e; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (IOException e) { throw e; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException e) { log.log(Level.SEVERE, this + " error ", e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException t) { reset(); // also sets status ERROR if (handler instanceof AprSocketContext.NonBlockingPollHandler) { ((AprSocketContext.NonBlockingPollHandler) handler).process(this, false, false, true); } notifyError(t, false); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException e) { throw e; }
// in java/org/apache/tomcat/buildutil/CheckEol.java
catch (IOException e) { throw new BuildException("Could not check file '" + file.getAbsolutePath() + "'", e); }
// in java/org/apache/tomcat/buildutil/Txt2Html.java
catch( IOException e ) { throw new BuildException( "Could not convert '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath() + "'", e ); }
// in java/org/apache/tomcat/spdy/SpdyStream.java
catch (IOException e) { e.printStackTrace(); // TODO: send rst, error processing the stream. }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (IOException ex) { abort("Compress error"); return false; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (IOException e) { // connection closed - abort all streams e.printStackTrace(); onClose(); return false; }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); ch.reset(); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (IOException ex) { ex.printStackTrace(); throw ex; }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (IOException ex) { if (running) { ex.printStackTrace(); } running = false; }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
catch (IOException x) { throw x; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw ioe; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException x) { if (running) { log.error(sm.getString("endpoint.accept.fail"), x); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("", ioe); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("", ioe); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { log.error(sm.getString( "endpoint.nio.selectorCloseFail"), ioe); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { log.error(sm.getString( "endpoint.nio.selectorCloseFail"), ioe); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( IOException x ) { if ( log.isDebugEnabled() ) log.debug("Unable to complete sendfile request:", x); cancelledKey(sk,SocketStatus.ERROR); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( IOException x ) { handshake = -1; if ( log.isDebugEnabled() ) log.debug("Error during SSL handshake",x);
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (IOException ioe) { countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw ioe; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (IOException x) { if (running) { log.error(sm.getString("endpoint.accept.fail"), x); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (IOException e) { // Ignore }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (IOException e) { // Ignore }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch (IOException e) { // ignore - presumably the timeout }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { Throwable cause = ioe.getCause(); if (cause instanceof UnrecoverableKeyException) { // Log a warning we had a password issue log.warn(sm.getString("jsse.invalid_truststore_password"), cause); // Re-try trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, null); } else { // Something else went wrong - re-throw throw ioe; } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { // May be expected when working with a trust store // Re-throw. Caller will catch and log as required throw ioe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { // Do nothing }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(IOException iex) { throw iex; }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
catch (NoSuchElementException x ) { try { synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 s = Selector.open(); } } catch (IOException iox) { } }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
catch (IOException iox) { }
// in java/org/apache/tomcat/util/http/parser/HttpParserTokenManager.java
catch(java.io.IOException e) { return pos + 1; }
// in java/org/apache/tomcat/util/http/parser/HttpParserTokenManager.java
catch(java.io.IOException e) { return curPos; }
// in java/org/apache/tomcat/util/http/parser/HttpParserTokenManager.java
catch(java.io.IOException e) { jjmatchedKind = 0; matchedToken = jjFillToken(); return matchedToken; }
// in java/org/apache/tomcat/util/http/parser/HttpParserTokenManager.java
catch (java.io.IOException e1) { EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException e) { // Can't happen, as decodedQuery can't overflow e.printStackTrace(); }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException ioe) { // Should never happen... log.error(sm.getString("parameters.copyFail"), ioe); }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException e) { parseFailed = true; decodeFailCount++; if (decodeFailCount == 1 || log.isDebugEnabled()) { if (log.isDebugEnabled()) { log.debug(sm.getString("parameters.decodeFail.debug", origName.toString(), origValue.toString()), e); } else if (log.isInfoEnabled()) { UserDataHelper.Mode logMode = userDataLog.getNextMode(); if (logMode != null) { String message = sm.getString( "parameters.decodeFail.info", tmpName.toString(), tmpValue.toString()); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString("parameters.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } } } }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); }
// in java/org/apache/tomcat/util/http/fileupload/IOUtils.java
catch (IOException ioe) { // ignore }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
catch (IOException e) { fileData = null; }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
catch (IOException e) { // ignore }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
catch (IOException e) { // ignore }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
catch (IOException e) { // ignore }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new FileUploadException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/http/fileupload/FileDeleteStrategy.java
catch (IOException ex) { return false; }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
catch (IOException ioe) { exception = ioe; }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
catch (IOException ioe) { exception = ioe; }
// in java/org/apache/tomcat/util/http/fileupload/util/Streams.java
catch (IOException ioe) { /* Ignore me */ }
// in java/org/apache/tomcat/util/http/fileupload/util/Streams.java
catch (IOException ioe) { /* Ignore me */ }
// in java/org/apache/tomcat/util/http/fileupload/ThresholdingOutputStream.java
catch (IOException ignored) { // ignore }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
catch( IOException ex) { if(log.isDebugEnabled()) { log.debug("B2CConverter: Reseting the converter " + ex.toString()); } reset(); throw ex; }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
catch(IOException ioe){ }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
catch (IOException e) { log.warn(sm.getString("c2bConverter.recycleFailed"), e); try { init(); } catch (IOException ignore) { // Should never happen since this means encoding is invalid and // in that case, the constructor will have failed. } }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
catch (IOException ignore) { // Should never happen since this means encoding is invalid and // in that case, the constructor will have failed. }
// in java/org/apache/tomcat/util/buf/UEncoder.java
catch (IOException iex) { }
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
catch (IOException e) { log.warn(sm.getString("jarScan.webinflibFail", url), e); }
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
catch (IOException ioe) { log.warn(sm.getString( "jarScan.classloaderFail",urls[i]), ioe); }
// in java/org/apache/tomcat/util/scan/UrlJar.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/tomcat/util/scan/UrlJar.java
catch (IOException ioe) { entry = null; }
// in java/org/apache/tomcat/util/scan/FileUrlJar.java
catch (IOException e) { // Ignore }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (IOException e) { System.out.println(buf.toString()); e.printStackTrace(); throw new ClassFormatException("Byte code error: " + e, e); }
// in java/org/apache/el/parser/SimpleCharStream.java
catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_0(0, active0); return 1; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { return curPos; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(0, active0); return 1; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(1, active0); return 2; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(2, active0); return 3; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(3, active0); return 4; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(4, active0); return 5; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(5, active0); return 6; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(6, active0); return 7; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(7, active0); return 8; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(8, active0); return 9; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { return pos + 1; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { return curPos; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjmatchedKind = 0; matchedToken = jjFillToken(); return matchedToken; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch (java.io.IOException e1) { continue EOFLoop; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch (java.io.IOException e1) { EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { props = null; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.contextClose"), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString( "contextConfig.fixDocBase", context.getName()), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { globalTimeStamp = -1; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { hostTimeStamp = -1; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException ioe) { log.error(sm.getString( "contextConfig.servletContainerInitializerFail", url, context.getName())); ok = false; return; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException ioe) { log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName())); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.baseError"), e); return null; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamJar", entryName, url),e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.jarFile", url), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamJndi", url),e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.jndiUrl", url), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamFile", file.getAbsolutePath()),e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.webxmlFail", resourcePath, descriptor.getTaglibURI()), ioe); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.webinfFail", path), ioe); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.dirFail", fileList[i].getAbsolutePath()), ioe); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.jarFail", jarConn.getURL()), ioe); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { return file; }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException ioe) { return false; }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { /* Ignore */ }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException ioe) { // Ignore; }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { /* Ignore */ }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { /* Ignore */ }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e){ // Ignore }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e){ // Ignore }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { log.warn(sm.getString ("hostConfig.canonicalizing", app.name), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { log.warn(sm.getString ("hostConfig.canonicalizing", app.name), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { log.warn(sm.getString ("hostConfig.canonicalizing", app.name), e); }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { throw e; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { throw e; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { log.error(sm.getString ("expandWar.copy", fileSrc, fileDest), e); result = false; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/startup/Catalina.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/startup/Catalina.java
catch (IOException e) { log.error("Catalina.stop: ", e); System.exit(1); }
// in java/org/apache/catalina/startup/Catalina.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/startup/Catalina.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/startup/Catalina.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/startup/PasswdUserDatabase.java
catch (Exception e) { if (reader != null) { try { reader.close(); } catch (IOException f) { // Ignore } reader = null; } }
// in java/org/apache/catalina/startup/PasswdUserDatabase.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (IOException ioe) { homeFile = f.getAbsoluteFile(); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (IOException ioe) { homeFile = f.getAbsoluteFile(); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (IOException ioe) { homeFile = f.getAbsoluteFile(); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (IOException ioe) { baseFile = baseFile.getAbsoluteFile(); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (IOException e) { baseFile = baseFile.getAbsoluteFile(); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (IOException e) { homeFile = homeFile.getAbsoluteFile(); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { canonicalLoaderDir = null; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to close JAR", e); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { log.warn(sm.getString( "webappClassLoader.jdbcRemoveStreamError", contextName), ioe); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to open JAR", e); } return false; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { return null; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { return null; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { throw new IllegalArgumentException( sm.getString("webappClassLoader.validationErrorJarPath", jarEntry2.getName()), ioe); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { log.error(sm.getString("webappClassLoader.readError", name), e); return null; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { /* Ignore */}
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (IOException e) { return false; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (IOException e) { return false; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (IOException e) { // Should never happen containerLog.error("Could not append password bytes to chunk: ", e); }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (IOException e) { throw new LoginException(e.toString()); }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (IOException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.createServerFailed", serverName), e); }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (IOException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.destroyServerFailed", serverName),e); }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
catch (IOException e) { if (writer != null) { writer.close(); } fileNew.delete(); throw e; }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/ant/DeployTask.java
catch (IOException e) { throw new BuildException(e); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (IOException e) { throw new BuildException(e); }
// in java/org/apache/catalina/ant/BaseRedirectorHelperTask.java
catch (IOException ioe) { log("Error closing redirector: " + ioe.getMessage(), Project.MSG_ERR); }
// in java/org/apache/catalina/websocket/StreamInbound.java
catch (IOException ioe) { // Given something must have gone to reach this point, this // might not work but try it anyway. closeOutboundConnection(Constants.STATUS_PROTOCOL_ERROR, null); return SocketState.CLOSED; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (IOException e) { appBaseFile = file; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (IOException e) { writer.println(smClient.getString( "hostManagerServlet.managerXml")); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { if (war.exists() && !war.delete()) { writer.println( smClient.getString("managerServlet.deleteFail", war)); } throw e; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { e.printStackTrace(); result = false; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
catch ( IOException x ) { log.error("Unable to compress byte contents"); throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
catch ( IOException x ) { log.error("Unable to decompress byte contents",x); }
// in java/org/apache/catalina/tribes/io/ObjectReader.java
catch ( IOException x ) { //unable to get buffer size log.warn("Unable to retrieve the socket receiver buffer size, setting to default 43800 bytes."); this.buffer = new XByteBuffer(43800,true); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException xx) { exception = xx; closeSocket(); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { // Ignore }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch ( java.io.IOException x ) { log.warn("Unable to send ACK back through channel, channel disconnected?: "+x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch (IOException ioe) { log.error("Failed bind replication listener on address:"+ host, ioe); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind server socket to:" + addr + " throwing error."); throw x; } port++; }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
catch ( IOException x ) { throw new RuntimeException("Unable to open NIO selector.",x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( IOException io ) { if ( x==null ) x = new ChannelException(io); x.addFaultyMember(senders[i].getDestination(),io); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( IOException io ) { if ( x==null ) x = new ChannelException(io); x.addFaultyMember(senders[i].getDestination(),io); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( IOException x ) { sender.disconnect(); sender.reset(); //nioSenders.remove(entry.getKey()); i.remove(); result = true; }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( java.io.IOException x ) { log.warn("Unable to send ACK back through channel, channel disconnected?: "+x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (IOException e) { if (log.isDebugEnabled()) log.debug("", e); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (IOException e) { if (log.isDebugEnabled()) log.debug("", e); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch ( IOException ignore ){ if (log.isWarnEnabled()) { log.warn("Unable to cleanup on selector close.",ignore); } }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { log.error("Unable to diff object. Will replicate the entire object instead.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { log.error("Unable to transfer LazyReplicatedMap state.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x ) { log.error("Unable to deserialize MapMessage.",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { log.error("Unable to deserialize MapMessage.", x); return; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( IOException x ) { throw new RuntimeException(x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { throw new RuntimeException(x); }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
catch ( IOException x ) { throw new RuntimeException("Unable to parse hostname.",x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( IOException x ) { throw new IllegalArgumentException(x); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (IOException iox) { log.error("Unable to join multicast group, make sure your system has multicasting enabled."); throw iox; }
// in java/org/apache/catalina/tribes/membership/StaticMember.java
catch (IOException x) { throw new RuntimeException(x);}
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException f) { // ignored }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { error = true; log.error(sm.getString("standardManager.unloading.ioe", e), e); throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.unloading.ioe", e), e); try { oos.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/StoreBase.java
catch (IOException e) { manager.getContainer().getLogger().error("Error getting keys", e); return; }
// in java/org/apache/catalina/session/StoreBase.java
catch (IOException ioe) { // Ignore - session will be expired }
// in java/org/apache/catalina/session/StoreBase.java
catch (Exception e) { manager.getContainer().getLogger().error("Session: "+keys[i]+"; ", e); try { remove(keys[i]); } catch (IOException e2) { manager.getContainer().getLogger().error("Error removing key", e2); } }
// in java/org/apache/catalina/session/StoreBase.java
catch (IOException e2) { manager.getContainer().getLogger().error("Error removing key", e2); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/session/JDBCStore.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException e) { if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException e) { if (fos != null) { try { fos.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("checking isLoaded for id, " + id + ", "+e.getMessage(), e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("Exception clearing the Store: " + e, e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("Can't load sessions from store, " + e.getMessage(), e); return; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("Failed load session from store, " + e.getMessage(), e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("Exception removing session " + e.getMessage(), e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { // This is logged in writeSession() }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error(sm.getString ("persistentManager.serializeError", session.getIdInternal(), e)); throw e; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { // This is logged in writeSession() }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { // This is logged in writeSession() }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { // This is logged in writeSession() }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (IOException e) { container.getLogger().warn(sm.getString( "cometConnectionManagerValve.event"), e); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (IOException e) { writer = null; currentLogFile = null; log.error(sm.getString("accessLogValve.openFail", pathname), e); }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
catch (IOException e) { log.error("parse error", e); return null; }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (IOException ioe) { log.debug("Request body too big to save during authentication"); response.sendError(HttpServletResponse.SC_FORBIDDEN, sm.getString("authenticator.requestBodyTooBig")); return (false); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IOException e) { exception = e; len = -1; break; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IOException e) { exception = e; len = -1; break; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IOException e) { return e; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IOException e) { exception = e; len = -1; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (IOException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (IOException e) { lockRequestType = LOCK_REFRESH; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException ioe) { // delete in case file is corrupted if (f.exists()) { if (!f.delete() && debug >= 2) { log("expandCGIScript: failed to delete '" + f.getAbsolutePath() + "'"); } } }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException e){ log ("Caught exception " + e); throw e; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException ioe) { log ("Exception closing header reader " + ioe); }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException ioe) { log ("Exception closing output stream " + ioe); }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException e) { log("sendToLog error", e) ; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException ce) { log("sendToLog error", ce) ; }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (IOException e) { }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (IOException e) { }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (IOException e) { }
// in java/org/apache/catalina/ha/session/JvmRouteBinderValve.java
catch (IOException e) { // Hups! }
// in java/org/apache/catalina/ha/session/JvmRouteBinderValve.java
catch (IOException e) { // Hups! }
// in java/org/apache/catalina/ha/session/JvmRouteSessionIDBinderListener.java
catch (IOException e) { log.error(e); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.unableSerializeSessionID", newSessionID), e); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.loading.ioe", e), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException f) { // ignored }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.unloading.ioe", e), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException x) { log.error(sm.getString("deltaManager.createMessage.unableCreateDeltaRequest",sessionId), x); return null; }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOnListener.java
catch (IOException io) { log.error("Session doesn't exist:" + io); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOnListener.java
catch (IOException io) { log.error("Session doesn't exist:" + io); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (java.io.IOException x) { log.error(sm.getString("farmWarDeployer.msgIoe"), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (IOException e) { log.error(sm.getString("farmWarDeployer.fileCopyFail", from, to), e); return false; }
// in java/org/apache/catalina/ssi/SSIInclude.java
catch (IOException e) { ssiMediator.log("#include--Couldn't include file: " + substitutedValue, e); writer.write(configErrMsg); }
// in java/org/apache/catalina/ssi/SSIFlastmod.java
catch (IOException e) { ssiMediator.log( "#flastmod--Couldn't get last modified for file: " + substitutedValue, e); writer.write(configErrMsg); }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
catch (IOException e) { // Ignore this. It will always fail for non-file based includes }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
catch (IOException e) { // Ignore this. It will always fail for non-file based includes }
// in java/org/apache/catalina/ssi/SSIExec.java
catch (IOException e) { if (!foundProgram) { //apache doesn't output an error message if it can't find // a program } ssiMediator.log("Couldn't exec file: " + substitutedValue, e); }
// in java/org/apache/catalina/ssi/SSIFsize.java
catch (IOException e) { ssiMediator.log("#fsize--Couldn't get size for file: " + substitutedValue, e); writer.write(configErrMsg); }
// in java/org/apache/catalina/connector/OutputBuffer.java
catch (IOException e) { // An IOException on a write is almost always due to // the remote client aborting the request. Wrap this // so that it can be handled better by the error dispatcher. throw new ClientAbortException(e); }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { throw new SecurityException(sm.getString( "coyoteRequest.sendfileNotCanonical", value), e); }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Can't find the session }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/connector/Request.java
catch (IOException ioe) { partsParseException = ioe; return; }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { session = null; }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Client disconnect if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Client disconnect or chunkedPostTooLarge error if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; }
// in java/org/apache/catalina/connector/Response.java
catch (IOException ioe) { // Ignore - the client has probably closed the connection }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { throw new IllegalArgumentException(cc.toString(), e); }
// in java/org/apache/catalina/connector/CoyoteWriter.java
catch (IOException e) { error = true; }
// in java/org/apache/catalina/connector/CoyoteWriter.java
catch (IOException ex ) { // Ignore }
// in java/org/apache/catalina/connector/CoyoteWriter.java
catch (IOException e) { error = true; }
// in java/org/apache/catalina/connector/CoyoteWriter.java
catch (IOException e) { error = true; }
// in java/org/apache/catalina/connector/CoyoteWriter.java
catch (IOException e) { error = true; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException e) { error = true; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException e) { success = false; // Ignore }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException ioe) { res.setStatus(400); res.setMessage("Invalid URI: " + ioe.getMessage()); connector.getService().getContainer().logAccess( request, response, 0, true); return false; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException e) { // Ignore log.error("Invalid URI encoding; using HTTP default"); connector.setURIEncoding(null); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException e) { log.error("Invalid URI character encoding; trying ascii"); cc.recycle(); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardHost.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedServletsResource"), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedListenersResources"), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedServletsResources"), e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IOException ioe) { log.warn("onComplete() failed for listener of type [" + listener.getClass().getName() + "]", ioe); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IOException ioe) { log.warn("onStartAsync() failed for listener of type [" + listener.getClass().getName() + "]", ioe); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IOException ioe) { log.warn("onStartAsync() failed for listener of type [" + listener.getClass().getName() + "]", ioe); }
// in java/org/apache/catalina/core/ApplicationHttpRequest.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/core/ApplicationHttpRequest.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/core/StandardContextValve.java
catch (IOException ioe) { container.getLogger().error(sm.getString( "standardContextValve.acknowledgeException"), ioe); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { // Ignored }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { log.error("StandardServer.await: create[" + address + ":" + port + "]: ", e); return; }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { if (stopAwait) { // Wait was aborted with socket.close() break; } log.error("StandardServer.await: accept: ", e); break; }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { log.warn("StandardServer.await: read: ", e); ch = -1; }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (IOException e) { container.getLogger().warn("Exception Processing " + errorPage, e); }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (IOException e) { container.getLogger().warn("Exception Processing " + errorPage, e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException e) { log.warn(sm.getString("standardContext.workPath", getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException ioe) { log.error("Error in dependencyCheck", ioe); dependencyCheck = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException e) { log.warn(sm.getString("standardContext.workCreateException", workDir, catalinaHomePath, getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException e) { return ""; }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException ioe) {/*Ignore*/}
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IllegalStateException e) { try { ServletOutputStream stream = response.getOutputStream(); stream.close(); } catch (IllegalStateException f) { // Ignore } catch (IOException f) { // Ignore } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); ioException = e; }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IOException e) { log.error(sm.getString( "jreLeakListener.jarUrlConnCacheFail"), e); }
// in java/org/apache/catalina/util/URLEncoder.java
catch(IOException e) { buf.reset(); continue; }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (IOException e) { log.error(sm.getString ("extensionValidator.failload", item), e); }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (IOException e) { log.error (sm.getString ("extensionValidator.failload", files[i]), e); }
// in java/javax/servlet/jsp/tagext/BodyContent.java
catch (IOException ex) { // TODO -- clean this one up. throw new Error("internal error!;"); }
// in java/javax/servlet/http/HttpUtils.java
catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); }
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { throw new ELException("Failed to read " + SERVICE_RESOURCE_NAME, e); }
// in java/javax/el/ExpressionFactory.java
catch (IOException ioe) {/*Ignore*/}
// in java/javax/el/ExpressionFactory.java
catch (IOException ioe) {/*Ignore*/}
// in java/javax/el/ExpressionFactory.java
catch (IOException ioe) {/*Ignore*/}
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { throw new ELException("Failed to read " + PROPERTY_FILE, e); }
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { // Ignore }
81
            
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer.getMessage("jsp.error.flush"), ex); throw ise; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer .getMessage("jsp.error.attempt_to_clear_flushed_buffer")); ise.initCause(ex); throw ise; }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
catch (IOException ioe) { throw new JasperException(ioe); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IOException e) { throw new ServletException("Could not precompile jsp: " + jspFile, e); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IOException e) { throw e; }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (IOException io) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), io); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { throw new JasperException(ioe); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ex) { fis.close(); throw ex; }
// in java/org/apache/jasper/JspC.java
catch (IOException ex) { fos.close(); throw ex; }
// in java/org/apache/naming/resources/FileDirContext.java
catch (IOException e) { NamingException ne = new NamingException (sm.getString("resources.bindFailed", e)); ne.initCause(e); throw ne; }
// in java/org/apache/coyote/http11/filters/BufferedInputFilter.java
catch(IOException ioe) { // No need for i18n - this isn't going to get logged anywhere throw new IllegalStateException( "Request body too large for buffer"); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (IOException e) { apr.reset(); throw e; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (IOException e) { throw e; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException e) { throw e; }
// in java/org/apache/tomcat/buildutil/CheckEol.java
catch (IOException e) { throw new BuildException("Could not check file '" + file.getAbsolutePath() + "'", e); }
// in java/org/apache/tomcat/buildutil/Txt2Html.java
catch( IOException e ) { throw new BuildException( "Could not convert '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath() + "'", e ); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (IOException ex) { ex.printStackTrace(); throw ex; }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
catch (IOException x) { throw x; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw ioe; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (IOException ioe) { countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw ioe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { Throwable cause = ioe.getCause(); if (cause instanceof UnrecoverableKeyException) { // Log a warning we had a password issue log.warn(sm.getString("jsse.invalid_truststore_password"), cause); // Re-try trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, null); } else { // Something else went wrong - re-throw throw ioe; } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { // May be expected when working with a trust store // Re-throw. Caller will catch and log as required throw ioe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(IOException iex) { throw iex; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new FileUploadException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
catch( IOException ex) { if(log.isDebugEnabled()) { log.debug("B2CConverter: Reseting the converter " + ex.toString()); } reset(); throw ex; }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (IOException e) { System.out.println(buf.toString()); e.printStackTrace(); throw new ClassFormatException("Byte code error: " + e, e); }
// in java/org/apache/el/parser/SimpleCharStream.java
catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { throw e; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { throw new IllegalArgumentException( sm.getString("webappClassLoader.validationErrorJarPath", jarEntry2.getName()), ioe); }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (IOException e) { throw new LoginException(e.toString()); }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
catch (IOException e) { if (writer != null) { writer.close(); } fileNew.delete(); throw e; }
// in java/org/apache/catalina/ant/DeployTask.java
catch (IOException e) { throw new BuildException(e); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (IOException e) { throw new BuildException(e); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { if (war.exists() && !war.delete()) { writer.println( smClient.getString("managerServlet.deleteFail", war)); } throw e; }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
catch ( IOException x ) { log.error("Unable to compress byte contents"); throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind server socket to:" + addr + " throwing error."); throw x; } port++; }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
catch ( IOException x ) { throw new RuntimeException("Unable to open NIO selector.",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( IOException x ) { throw new RuntimeException(x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { throw new RuntimeException(x); }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
catch ( IOException x ) { throw new RuntimeException("Unable to parse hostname.",x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( IOException x ) { throw new IllegalArgumentException(x); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (IOException iox) { log.error("Unable to join multicast group, make sure your system has multicasting enabled."); throw iox; }
// in java/org/apache/catalina/tribes/membership/StaticMember.java
catch (IOException x) { throw new RuntimeException(x);}
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { error = true; log.error(sm.getString("standardManager.unloading.ioe", e), e); throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.unloading.ioe", e), e); try { oos.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException e) { if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException e) { if (fos != null) { try { fos.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error(sm.getString ("persistentManager.serializeError", session.getIdInternal(), e)); throw e; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException e){ log ("Caught exception " + e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.loading.ioe", e), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.unloading.ioe", e), e); throw e; }
// in java/org/apache/catalina/connector/OutputBuffer.java
catch (IOException e) { // An IOException on a write is almost always due to // the remote client aborting the request. Wrap this // so that it can be handled better by the error dispatcher. throw new ClientAbortException(e); }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { throw new SecurityException(sm.getString( "coyoteRequest.sendfileNotCanonical", value), e); }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { throw new IllegalArgumentException(cc.toString(), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; }
// in java/javax/servlet/jsp/tagext/BodyContent.java
catch (IOException ex) { // TODO -- clean this one up. throw new Error("internal error!;"); }
// in java/javax/servlet/http/HttpUtils.java
catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); }
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { throw new ELException("Failed to read " + SERVICE_RESOURCE_NAME, e); }
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { throw new ELException("Failed to read " + PROPERTY_FILE, e); }
(Lib) Throwable 305
            
// in java/org/apache/jasper/runtime/JspFactoryImpl.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.fatal("Exception initializing page context", ex); return null; }
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/jasper/compiler/ParserController.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/jasper/compiler/Localizer.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); t.printStackTrace(); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/jasper/compiler/JspReader.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.error("Exception parsing file ", ex); // Pop state being constructed: popFile(); err.jspError("jsp.error.file.cannot.read", file); }
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); jsw.getServletContext().log("Background compile failed", t); }
// in java/org/apache/jasper/servlet/JspCServletContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (null); }
// in java/org/apache/jasper/servlet/JspCServletContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); url = null; }
// in java/org/apache/jasper/servlet/JspCServletContext.java
catch (Throwable t2) { ExceptionUtils.handleThrowable(t2); }
// in java/org/apache/jasper/servlet/JspCServletContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (null); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); // Need to localize this. log.warn("Failed to load engineOptionsClass", e); // Use the default Options implementation options = new EmbeddedServletOptions(config, context); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException(e); }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
catch (Throwable t) { if (t instanceof InvocationTargetException && t.getCause() != null) { throw t.getCause(); } else { throw t; } }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(Throwable t) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(Throwable t) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/juli/logging/DirectJDKLog.java
catch( Throwable t ) { }
// in java/org/apache/juli/logging/DirectJDKLog.java
catch( Throwable t ) { // maybe it wasn't included - the ugly default will be used. }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); // any other exception or error is odd. Here we log it // with "ERROR" level, so it will show up even on // less-than-verbose logs. getLog().error(sm.getString("ajpprotocol.proto.error"), e); }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), t); } // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug(sm.getString( "http11processor.request.prepare"), t); } // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString( "http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.finish"), t); // 500 - Internal Server Error // Can't add a 500 to the access log since that has already been // written in the Adapter.service method. response.setStatus(500); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.response.finish"), t); error = true; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error t.printStackTrace(); response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; }
// in java/org/apache/tomcat/jni/SSLExt.java
catch (Throwable t) { t.printStackTrace(); return -1; }
// in java/org/apache/tomcat/jni/SSLExt.java
catch (Throwable t) { // ignore return false; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable e) { apr.reset(); e.printStackTrace(); throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable t) { throw new IOException(t); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable t) { log.log(Level.SEVERE, "endpoint.poll.error", t); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable t) { t.printStackTrace(); if (pollTime > FALLBACK_POLL_TIME) { pollTime = FALLBACK_POLL_TIME; } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable t) { throw new IOException(t); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable t) { t.printStackTrace(); // no error handler yet reset(); notifyError(t, false); return; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable e) { log.log(Level.SEVERE, this + " error ", e); reset(); // no notifyIO - just did it. }
// in java/org/apache/tomcat/jni/Library.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } String name = System.mapLibraryName(NAMES[i]); String path = System.getProperty("java.library.path"); String sep = System.getProperty("path.separator"); String [] paths = path.split(sep); for (int j=0; j<paths.length; j++) { java.io.File fd = new java.io.File(paths[j] , name); if (fd.exists()) { t.printStackTrace(); } } if ( i > 0) err.append(", "); err.append(t.getMessage()); }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { t.printStackTrace(); trace("< onData-ERROR() " + lastChannel); abort("Error processing socket" + t); return CLOSE; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { abort("Error handling frame"); t.printStackTrace(); return CLOSE; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { log.log(Level.SEVERE, "Error parsing head SYN_STREAM", t); abort("Error reading headers " + t); return CLOSE; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { log.info("Error parsing head SYN_STREAM" + t); abort("Error reading headers " + t); return CLOSE; }
// in java/org/apache/tomcat/spdy/SpdyContext.java
catch (Throwable t) { // ignore, openssl not supported }
// in java/org/apache/tomcat/spdy/SpdyContext.java
catch (Throwable t) { // ignore, npn not supported }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (Throwable x) { ExceptionUtils.handleThrowable(x); log.error("",x); continue; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch ( Throwable t ) { log.error("",t); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); System.err.println(oomParachuteMsg); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { log.error("",t); } catch (Throwable tt) { ExceptionUtils.handleThrowable(t); } // Tell to close the socket return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable tt) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable oomt ) { try { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.accept.fail"), t); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable x ) { log.error("",x); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); if (log.isDebugEnabled()) log.error("",e); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable x) { ExceptionUtils.handleThrowable(x); log.error("",x); continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("",t); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable t ) { log.error("",t); cancelledKey(sk, SocketStatus.ERROR); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; socket.getPoller().cancelledKey(key,SocketStatus.ERROR); releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable t ) { log.error("",t); socket.getPoller().cancelledKey(key,SocketStatus.ERROR); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { if (step == 2) { log.debug(sm.getString("endpoint.err.handshake"), t); } else { log.debug(sm.getString("endpoint.err.unexpected"), t); } } // Tell to close the socket return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (running) { String msg = sm.getString("endpoint.accept.fail"); if (t instanceof Error) { Error e = (Error) t; if (e.getError() == 233) { // Not an error on HP-UX so log as a warning // so it can be filtered out on that platform // See bug 50273 log.warn(msg, t); } else { log.error(msg, t); } } else { log.error(msg, t); } } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.poll.error"), t); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.poll.error"), t); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.accept.fail"), t); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.err.handshake"), t); } // Tell to close the socket state = SocketState.CLOSED; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.err.unexpected"), t); // Close the socket return false; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch( Throwable t ) { log.debug(sm.getString("jsseSupport.clientCertError"), t); return null; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Throwable t ) { log.error( "Error unregistering mbean ", t); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); LogFactory.getLog("org.apache.tomcat.util.digester.Digester"). error("Unable to load property source["+className+"].",t); }
// in java/org/apache/el/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte004) { if (jjtc004) { jjtree.clearNodeScope(jjtn004); jjtc004 = false; } else { jjtree.popNode(); } if (jjte004 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte004;} } if (jjte004 instanceof ParseException) { {if (true) throw (ParseException)jjte004;} } {if (true) throw (Error)jjte004;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString( "contextConfig.authenticatorInstantiate", authenticatorName), t); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), t); return null; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployDescriptor.error", contextXml.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployWar.error", war.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployDir.error", dir.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString ("hostConfig.context.remove", app.name), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString ("hostConfig.context.remove", app.name), t); }
// in java/org/apache/catalina/startup/CatalinaProperties.java
catch (Throwable t) { handleThrowable(t); }
// in java/org/apache/catalina/startup/CatalinaProperties.java
catch (Throwable t) { handleThrowable(t); }
// in java/org/apache/catalina/startup/CatalinaProperties.java
catch (Throwable t) { handleThrowable(t); }
// in java/org/apache/catalina/startup/CatalinaProperties.java
catch (Throwable t) { handleThrowable(t); error = t; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/Catalina.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This will fail on JDK 1.2. Ignoring, as Tomcat can run // fine without the shutdown hook. }
// in java/org/apache/catalina/startup/Catalina.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.error(sm.getString("catalina.shutdownHookFail"), ex); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (Throwable t) { handleThrowable(t); log.error("Class loader creation threw exception", t); System.exit(1); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (Throwable t) { handleThrowable(t); t.printStackTrace(); return; }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (Throwable t) { // Unwrap the Exception for clearer error reporting if (t instanceof InvocationTargetException && t.getCause() != null) { t = t.getCause(); } handleThrowable(t); t.printStackTrace(); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Class loader creation threw exception", t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Exception creating instance of " + className, t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Exception locating main() method", t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error("Exception calling main() method", t); System.exit(1); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(Throwable t) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in class " + clazz.getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not clean fields for class " + clazz.getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in object instance of class " + instance.getClass().getName(), t); } }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This is likely a dual registration log.info("Dual registration of jndi stream handler: " + t.getMessage()); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error( "LifecycleException ", t ); throw new LifecycleException("start: ", t); }
// in java/org/apache/catalina/realm/UserDatabaseRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); containerLog.error(sm.getString("userDatabaseRealm.lookup", resourceName), e); database = null; }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("jaasRealm.unexpectedError"), e); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("jaasRealm.unexpectedError"), e); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch( Throwable t) { log.error( "error ", t); return null; }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Error getting attribute " + oname + " " + attName, t); continue; }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); sb.append("NON-STRINGABLE VALUE"); }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/StatusTransformer.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.install[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.reload[" + cn.getDisplayName() + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.resources[" + type + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.resources[" + type + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log("ManagerServlet.serverinfo",t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.sessions[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log(sm.getString("managerServlet.startFailed", displayPath), t); writer.println(smClient.getString("managerServlet.startFailed", displayPath)); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.stop[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.undeploy[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Throwable x ) { clazz = MessageDispatchInterceptor.class; }
// in java/org/apache/catalina/tribes/io/BufferPool.java
catch ( Throwable x ) { log.warn("Unable to initilize BufferPool, not pooling XByteBuffer objects:"+x.getMessage()); if ( log.isDebugEnabled() ) log.debug("Unable to initilize BufferPool, not pooling XByteBuffer objects:",x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( Throwable t ) {}
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } log.error("Unable to process request in NioReceiver", t); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } log.error("Unable to receive broadcast message.",t); }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardManager.managerLoad"), t); }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardManager.managerUnload"), t); }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionCreated", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent( "afterSessionDestroyed", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t){ manager.getContainer().getLogger().error (sm.getString("standardSession.bindingEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.bindingEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { if (unbound != null) { context.fireContainerEvent( "afterSessionAttributeReplaced", listener); } else { context.fireContainerEvent("afterSessionAttributeAdded", listener); } } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionAttributeRemoved", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (Throwable tt) { ExceptionUtils.handleThrowable(tt); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("status.setContentType", t); } }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("accessLogValve.rotateFail"), e); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.info(sm.getString("accessLogValve.closeFail"), e); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); init = "127.0.0.1"; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* Log error */ return "-"; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); value = "localhost"; }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardLoginFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardErrorFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("deltaManager.managerLoad"), t); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOn.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new LifecycleException( "ClusterSingleSignOn exception during clusterLoad " + t); }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
catch (Throwable ignore) { ExceptionUtils.handleThrowable(ignore); }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
catch (Throwable ignore) { ExceptionUtils.handleThrowable(ignore); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("coyoteRequest.sessionEndAccessFail"), t); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (!(t instanceof IOException)) { log.error(sm.getString("coyoteAdapter.service"), t); } error = true; return false; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); success = false; log.error(sm.getString("coyoteAdapter.service"), t); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("coyoteAdapter.accesslogFail"), t); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error(sm.getString("aprListener.sslInit"), t); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.info(sm.getString("aprListener.aprDestroy")); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.info(sm.getString("aprListener.aprInit", System.getProperty("java.library.path"))); return; }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardHost.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString( "standardHost.invalidErrorReportValveClass", errorValve), t); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (null); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.fireContainerEvent("afterContextAttributeRemoved", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (replaced) context.fireContainerEvent("afterContextAttributeReplaced", listener); else context.fireContainerEvent("afterContextAttributeAdded", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Exception invoking periodic operation: ", t); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/JasperListener.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // Should not occur, obviously log.warn("Couldn't initialize Jasper", t); }
// in java/org/apache/catalina/core/StandardServer.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(t); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch(Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof MalformedURLException){ throw (MalformedURLException)t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch(Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage(), t); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); throwable(request, response, t); }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // Report our failure to process this custom page container.getLogger().error("Exception Processing " + errorPage, t); return (false); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); this.charsetMapper = new CharsetMapper(); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.filterStart", name), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.applicationListener", listeners[i]), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextInitialized", listener); getLogger().error (sm.getString("standardContext.listenerStart", instances[i].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextDestroyed", listener); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardContext.resourcesStart"), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardContext.resourcesStop"), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[i].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[j].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (false); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servlet = null; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e); // FIXME: Exception handling needs to be similar to what is in the StandardWrapperValue }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); }
// in java/org/apache/catalina/util/CharsetMapper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new IllegalArgumentException(t.toString()); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.startFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.stopFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/util/ServerInfo.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
126
            
// in java/org/apache/jasper/servlet/JspServlet.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException(e); }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
catch (Throwable t) { if (t instanceof InvocationTargetException && t.getCause() != null) { throw t.getCause(); } else { throw t; } }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(Throwable t) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(Throwable t) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable e) { apr.reset(); e.printStackTrace(); throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable t) { throw new IOException(t); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable t) { throw new IOException(t); }
// in java/org/apache/tomcat/jni/Library.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } String name = System.mapLibraryName(NAMES[i]); String path = System.getProperty("java.library.path"); String sep = System.getProperty("path.separator"); String [] paths = path.split(sep); for (int j=0; j<paths.length; j++) { java.io.File fd = new java.io.File(paths[j] , name); if (fd.exists()) { t.printStackTrace(); } } if ( i > 0) err.append(", "); err.append(t.getMessage()); }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte004) { if (jjtc004) { jjtree.clearNodeScope(jjtn004); jjtc004 = false; } else { jjtree.popNode(); } if (jjte004 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte004;} } if (jjte004 instanceof ParseException) { {if (true) throw (ParseException)jjte004;} } {if (true) throw (Error)jjte004;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error( "LifecycleException ", t ); throw new LifecycleException("start: ", t); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } log.error("Unable to process request in NioReceiver", t); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } log.error("Unable to receive broadcast message.",t); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOn.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new LifecycleException( "ClusterSingleSignOn exception during clusterLoad " + t); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch(Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof MalformedURLException){ throw (MalformedURLException)t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch(Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage(), t); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/util/CharsetMapper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new IllegalArgumentException(t.toString()); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.startFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.stopFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); }
(Lib) NamingException 112
            
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (NamingException e) { throw new RuntimeException(e.getMessage(), e); }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (NamingException e) { throw e; }
// in java/org/apache/naming/NamingContext.java
catch (NamingException e) { throw e; }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException e) { // Object not found }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException ne) { // Shouldn't happen }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException ne) { // Shouldn't happen }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException e) { // Ignore }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException e) { // Unexpected exception throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
catch ( NamingException ex) { // ignore }
// in java/org/apache/naming/resources/BaseDirContext.java
catch (NamingException ne) { // Ignore }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (NamingException e) { entry.exists = false; }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (NamingException e) { return false; }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (NamingException e) { exists = false; }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (NamingException e) { exists = false; }
// in java/org/apache/naming/resources/VirtualDirContext.java
catch (NamingException exc) { initialException = exc; }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { return null; }
// in java/org/apache/tomcat/util/http/mapper/Mapper.java
catch(NamingException nex) { // Swallow not found, since this is normal }
// in java/org/apache/tomcat/util/http/mapper/Mapper.java
catch(NamingException nex) { // Swallow, since someone else handles the 404 }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (NamingException e) { log.error(sm.getString( "contextConfig.webinfClassesUrl", "/WEB-INF/classes"), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (NamingException e) { //not found, ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NamingException e) { log.error(" Resource '" + paths[i] + "' is missing"); return (true); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NamingException e) { if (log.isDebugEnabled()) log.debug(" Failed tracking modifications of '" + getJarPath() + "'"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappLoader.java
catch(NamingException e) { // Silent catch: it's valid that no /WEB-INF/classes collection // exists }
// in java/org/apache/catalina/loader/WebappLoader.java
catch(NamingException e) { // Silent catch: it's valid that no /WEB-INF/lib collection // exists }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", libPath)); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", filename)); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { return false; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Log the problem for posterity containerLog.error(sm.getString("jndiRealm.exception"), e); // Close the connection so that it gets reopened next time if (context != null) close(context); // Return "not authenticated" for this request if (containerLog.isDebugEnabled()) containerLog.debug("Returning null principal."); return (null); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // If the getUserByPattern() call fails, try it again with the // credentials of the user that we're searching for try { userCredentialsAdd(context, dn, credentials); user = getUserByPattern(context, username, attrIds, dn); } finally { userCredentialsRemove(context); } }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { containerLog.error(sm.getString("jndiRealm.close"), e); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Log the problem for posterity containerLog.error(sm.getString("jndiRealm.exception"), e); // Close the connection so that it gets reopened next time if (context != null) close(context); // Return "not authenticated" for this request return (null); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { throw new LifecycleException(sm.getString("jndiRealm.open"), e); }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
catch (NamingException e) { log.error("No global naming context defined for server"); return; }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
catch (NamingException e) { log.error("Exception processing Global JNDI Resources", e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (NamingException e) { manager.getContainer().getLogger().error( sm.getString(getStoreName() + ".wrongDataSource", this.dataSourceName), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (NamingException e) { log.warn(sm.getString("namingResources.cleanupNoContext", container), e); return; }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (NamingException e) { log.warn(sm.getString( "namingResources.cleanupNoResource", cr.getName(), container), e); continue; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Failed throw new ServletException("No resources", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch(NamingException e) { result = false; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { result = false; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { if (debug > 10) log("readme '" + readmeFile + "' not found", e); return null; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { if (debug > 10) log("localXsltFile '" + localXsltFile + "' not found", e); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { continue; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { resp.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { result = false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put (dest, new Integer(WebdavStatus.SC_CONFLICT)); return false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put (dest, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR)); return false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { if (e.getCause() instanceof FileNotFoundException) { // We know the source exists so it must be the // destination dir that can't be found errorList.put(source, new Integer(WebdavStatus.SC_CONFLICT)); } else { errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR)); } return false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); return false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put(path, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put(path, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); return; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { if (!(object instanceof DirContext)) { // If it's not a collection, then it's an unknown // error errorList.put (childName, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put (childName, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { return (null); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (NamingException e) { ServletException se = new ServletException(e); throw se; }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { // Never happens }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error (sm.getString("naming.namingContextCreationFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { // Silent catch. Probably an object is already bound in // the context. currentContext = (javax.naming.Context) currentContext.lookup(token); }
// in java/org/apache/catalina/core/StandardContext.java
catch (NamingException e) { // Doesn't exist - ignore and carry on }
// in java/org/apache/catalina/core/StandardContext.java
catch (NamingException e) { // Silent catch, as this is a normal case during the early // startup stages }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (NamingException nex) { // Application does not contain a MANIFEST.MF file }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (NamingException nex) { // Jump out of the check for this application because it // has no resources }
15
            
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (NamingException e) { throw new RuntimeException(e.getMessage(), e); }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (NamingException e) { throw e; }
// in java/org/apache/naming/NamingContext.java
catch (NamingException e) { throw e; }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException e) { // Unexpected exception throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", libPath)); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", filename)); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { throw new LifecycleException(sm.getString("jndiRealm.open"), e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Failed throw new ServletException("No resources", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (NamingException e) { ServletException se = new ServletException(e); throw se; }
(Lib) ClassNotFoundException 70
            
// in java/org/apache/jasper/compiler/BeanRepository.java
catch (ClassNotFoundException ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
catch (ClassNotFoundException e) { throw new JasperException(e); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError (n, "jsp.error.unknown_attribute_type", tldAttr.getName(), expectedType); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError("jsp.error.function.classnotfound", n .getFunctionInfo().getFunctionClass(), n .getPrefix() + ':' + n.getName(), e.getMessage()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError("jsp.error.signature.classnotfound", paramTypes[i], n.getPrefix() + ':' + n.getName(), e.getMessage()); }
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch (ClassNotFoundException ex) { throw new IllegalStateException(ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (ClassNotFoundException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.error.compiler"), e); } }
// in java/org/apache/jasper/JspCompilationContext.java
catch (ClassNotFoundException cex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.load"), cex); }
// in java/org/apache/jasper/security/SecurityClassLoad.java
catch (ClassNotFoundException ex) { log.error("SecurityClassLoad", ex); }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/BeanFactory.java
catch(ClassNotFoundException e) { }
// in java/org/apache/naming/factory/BeanFactory.java
catch(ClassNotFoundException e) { e.printStackTrace(); }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load service Interface"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch(ClassNotFoundException e) { break; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch( ClassNotFoundException e ) { }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (ClassNotFoundException e) { throw new ReflectionException (e, "Cannot find Class for " + signature); }
// in java/org/apache/tomcat/util/digester/CallMethodRule.java
catch (ClassNotFoundException e) { // use the digester log digester.getLogger().error("(CallMethodRule) Cannot load class " + this.paramClassNames[i], e); this.paramTypes[i] = null; // Will cause NPE later }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassNotFoundException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassNotFoundException e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); return null; }
// in java/org/apache/catalina/startup/WebAnnotationSet.java
catch (ClassNotFoundException e) { // We do nothing }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(ClassNotFoundException cnfe) { // Ignore - will search internal repositories next }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(ClassNotFoundException cnfe) { if (!hasExternalRepositories || searchExternalFirst) { throw cnfe; } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { if (log.isTraceEnabled()) log.trace(" --> Passing on ClassNotFoundException"); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { log.info(sm.getString("webappClassLoader.clearRmiInfo", contextName), e); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (ClassNotFoundException e) { log.error("Class "+classNames[i]+" not found! Class not added."); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassNotFoundException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassNotFoundException", className), e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (ClassNotFoundException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch (ClassNotFoundException e) { return super.resolveClass(classDesc); }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch ( ClassNotFoundException x ) { cnfe = x; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ClassNotFoundException x) { log.error("Unable to transfer LazyReplicatedMap state.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ClassNotFoundException x ) { log.error("Unable to deserialize MapMessage.",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ClassNotFoundException x) { log.error("Unable to deserialize MapMessage.", x); return; }
// in java/org/apache/catalina/session/StandardManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/JDBCStore.java
catch (ClassNotFoundException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (ClassNotFoundException e) { String msg = sm.getString( "persistentManager.deserializeError", id); log.error(msg, e); throw new IllegalStateException(msg, e); }
// in java/org/apache/catalina/ha/session/SerializablePrincipal.java
catch (ClassNotFoundException e) { log.error(sm.getString( "serializablePrincipal.readPrincipal.cnfe"), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("deltaManager.loading.cnfe", e), e); throw e; }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (ClassNotFoundException e) { ServletException se = new ServletException(e); throw se; }
// in java/org/apache/catalina/core/StandardContext.java
catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException(cnfe.getMessage()); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ClassNotFoundException e) { // Safe to ignore. No class means no annotations to process }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException cnfe) { // Ignore this case: we must be running on a // non-Sun-based JRE. }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { if (System.getProperty("java.vendor").startsWith( "Sun")) { log.error(sm.getString( "jreLeakListener.gcDaemonFail"), e); } else { log.debug(sm.getString( "jreLeakListener.gcDaemonFail"), e); } }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch(ClassNotFoundException e) { // Ignore. The class is deprecated. }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch(ClassNotFoundException e) { // Ignore }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { if (System.getProperty("java.vendor").startsWith( "Sun")) { log.error(sm.getString( "jreLeakListener.ldapPoolManagerFail"), e); } else { log.debug(sm.getString( "jreLeakListener.ldapPoolManagerFail"), e); } }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { log.error( sm.getString("jreLeakListener.classToInitializeFail", classNameToLoad), e); // continue with next class to load }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (ClassNotFoundException e) { try { // Try also the superclass because of primitive types return super.resolveClass(classDesc); } catch (ClassNotFoundException e2) { // Rethrow original exception, as it can have more information // about why the class was not found. BZ 48007 throw e; } }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (ClassNotFoundException e2) { // Rethrow original exception, as it can have more information // about why the class was not found. BZ 48007 throw e; }
// in java/javax/el/ExpressionFactory.java
catch (ClassNotFoundException e) { throw new ELException( "Unable to find ExpressionFactory of type: " + className, e); }
// in java/javax/el/CompositeELResolver.java
catch (ClassNotFoundException e) { // Ignore. This is expected if using the EL stand-alone }
35
            
// in java/org/apache/jasper/compiler/BeanRepository.java
catch (ClassNotFoundException ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
catch (ClassNotFoundException e) { throw new JasperException(e); }
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch (ClassNotFoundException ex) { throw new IllegalStateException(ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (ClassNotFoundException cex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.load"), cex); }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load service Interface"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (ClassNotFoundException e) { throw new ReflectionException (e, "Cannot find Class for " + signature); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassNotFoundException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(ClassNotFoundException cnfe) { if (!hasExternalRepositories || searchExternalFirst) { throw cnfe; } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { if (log.isTraceEnabled()) log.trace(" --> Passing on ClassNotFoundException"); throw e; }
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassNotFoundException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassNotFoundException", className), e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (ClassNotFoundException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/session/StandardManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (ClassNotFoundException e) { String msg = sm.getString( "persistentManager.deserializeError", id); log.error(msg, e); throw new IllegalStateException(msg, e); }
// in java/org/apache/catalina/ha/session/SerializablePrincipal.java
catch (ClassNotFoundException e) { log.error(sm.getString( "serializablePrincipal.readPrincipal.cnfe"), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("deltaManager.loading.cnfe", e), e); throw e; }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (ClassNotFoundException e) { ServletException se = new ServletException(e); throw se; }
// in java/org/apache/catalina/core/StandardContext.java
catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException(cnfe.getMessage()); }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (ClassNotFoundException e) { try { // Try also the superclass because of primitive types return super.resolveClass(classDesc); } catch (ClassNotFoundException e2) { // Rethrow original exception, as it can have more information // about why the class was not found. BZ 48007 throw e; } }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (ClassNotFoundException e2) { // Rethrow original exception, as it can have more information // about why the class was not found. BZ 48007 throw e; }
// in java/javax/el/ExpressionFactory.java
catch (ClassNotFoundException e) { throw new ELException( "Unable to find ExpressionFactory of type: " + className, e); }
(Lib) NumberFormatException 57
            
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
catch (NumberFormatException e) { err.jspError("jsp.error.invalid.implicit.version", path); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (NumberFormatException ex) { errDispatcher.jspError(ex); }
// in java/org/apache/jasper/compiler/PageInfo.java
catch (NumberFormatException e) { if (n == null) { err.jspError("jsp.error.page.invalid.buffer"); } else { err.jspError(n, "jsp.error.page.invalid.buffer"); } }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
catch (NumberFormatException e) { lineNum = -1; }
// in java/org/apache/jasper/compiler/JspConfig.java
catch (NumberFormatException e) { }
// in java/org/apache/jasper/JspC.java
catch (NumberFormatException nfe) { dieLevel = DEFAULT_DIE_LEVEL; }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.checkInterval")); } }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval")); } }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.maxLoadedJsps", ""+this.maxLoadedJsps)); } }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.jspIdleTimeout", ""+this.jspIdleTimeout)); } }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NumberFormatException e) { // Ignore }
// in java/org/apache/juli/FileHandler.java
catch (NumberFormatException ignore) { //no op }
// in java/org/apache/coyote/Response.java
catch( NumberFormatException ex ) { // Do nothing - the spec doesn't have any "throws" // and the user might know what he's doing return false; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (NumberFormatException nfe) { // Ignore invalid value }
// in java/org/apache/tomcat/util/net/URL.java
catch (NumberFormatException e) { throw new MalformedURLException(e.toString()); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (NumberFormatException ex) { ok = false; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (NumberFormatException ex) { ok = false; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (NumberFormatException ex) { }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NumberFormatException e) { log.error(sm.getString("webappLoader.reloadable", event.getNewValue().toString())); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { throw new RuntimeException("Exception parsing number '" + i + "' (zero based) of comma delimited list '" + commaDelimitedInts + "'"); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { // default to now calendar = Calendar.getInstance(); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { throw new IllegalStateException(sm.getString( "Invalid duration (number) '{}' in directive '{}'", currentToken, line)); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException nfe) { log.debug("Invalid port value [" + portHeaderValue + "] provided in header [" + getPortHeader() + "]"); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTP_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTPS_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to integer:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to long:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to float:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to double:" + value); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (NumberFormatException e) { log("Could not parse idle parameter to an int: " + idleParam); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (NumberFormatException e) { log("Could not parse idle parameter to an int: " + idleParam); }
// in java/org/apache/catalina/session/ManagerBase.java
catch (NumberFormatException e) { log.error(sm.getString("managerBase.sessionTimeout", event.getNewValue())); }
// in java/org/apache/catalina/valves/RemoteIpValve.java
catch (NumberFormatException nfe) { if (log.isDebugEnabled()) { log.debug(sm.getString( "remoteIpValve.invalidPortHeader", portHeaderValue, portHeader), nfe); } }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
catch (NumberFormatException nfe) { return false; }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
catch (NumberFormatException nfe) { return false; }
// in java/org/apache/catalina/deploy/ErrorPage.java
catch (NumberFormatException nfe) { this.errorCode = 0; }
// in java/org/apache/catalina/deploy/WebXml.java
catch (NumberFormatException nfe) { log.warn(sm.getString("webXml.version.nfe", major, version), nfe); majorVersion = 0; }
// in java/org/apache/catalina/deploy/WebXml.java
catch (NumberFormatException nfe) { log.warn(sm.getString("webXml.version.nfe", minor, version), nfe); minorVersion = 0; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NumberFormatException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NumberFormatException e) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse .SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NumberFormatException e) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse .SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NumberFormatException e) { lockDuration = MAX_TIMEOUT; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (NumberFormatException nfe) { // Not a valid status code log ("runCGI: invalid status code:" + status); return HttpServletResponse.SC_INTERNAL_SERVER_ERROR; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (NumberFormatException nfe) { // Not a valid status code log ("runCGI: invalid status code:" + status); return HttpServletResponse.SC_INTERNAL_SERVER_ERROR; }
// in java/org/apache/catalina/connector/Request.java
catch (NumberFormatException e) { quality = 0.0; }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NumberFormatException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", env.getName())); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (NumberFormatException e) { setLoadOnStartup(0); }
// in java/org/apache/catalina/security/SecurityListener.java
catch (NumberFormatException nfe) { log.warn(sm.getString("SecurityListener.checkUmaskParseFail", prop)); }
// in java/javax/servlet/http/HttpUtils.java
catch (NumberFormatException e) { // XXX // need to be more specific about illegal arg throw new IllegalArgumentException(); }
14
            
// in java/org/apache/tomcat/util/net/URL.java
catch (NumberFormatException e) { throw new MalformedURLException(e.toString()); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { throw new RuntimeException("Exception parsing number '" + i + "' (zero based) of comma delimited list '" + commaDelimitedInts + "'"); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { throw new IllegalStateException(sm.getString( "Invalid duration (number) '{}' in directive '{}'", currentToken, line)); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTP_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTPS_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
// in java/javax/servlet/http/HttpUtils.java
catch (NumberFormatException e) { // XXX // need to be more specific about illegal arg throw new IllegalArgumentException(); }
(Lib) InterruptedException 54
            
// in java/org/apache/juli/AsyncFileHandler.java
catch (InterruptedException x) { //allow thread to be interrupted and back out of the publish operation //after this we clear the flag Thread.interrupted(); }
// in java/org/apache/juli/AsyncFileHandler.java
catch (InterruptedException x) { Thread.interrupted(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (InterruptedException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (InterruptedException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (InterruptedException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (InterruptedException e) { }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (InterruptedException e) { return 0; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (InterruptedException e) { return 0; }
// in java/org/apache/tomcat/spdy/SpdyStream.java
catch (InterruptedException e) { return null; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (InterruptedException ignore) { Thread.interrupted(); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (InterruptedException ignore) { Thread.interrupted(); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (InterruptedException ignore) { }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore and clean the interrupt flag Thread.interrupted(); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (InterruptedException e) { // yes, ignore }
// in java/org/apache/catalina/startup/HostConfig.java
catch (InterruptedException e1) { // Ignore }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( InterruptedException x ) { interrupted(); }
// in java/org/apache/catalina/tribes/group/RpcChannel.java
catch ( InterruptedException ix ) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpPingInterceptor.java
catch ( InterruptedException ix ) { interrupted(); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( InterruptedException x ) { Thread.interrupted(); }
// in java/org/apache/catalina/tribes/group/interceptors/SimpleCoordinator.java
catch (final InterruptedException e) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/bio/util/SingleRemoveSynchronizedAddLock.java
catch ( InterruptedException e ) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/bio/util/SingleRemoveSynchronizedAddLock.java
catch ( InterruptedException e ) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch (InterruptedException ti) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/PooledSender.java
catch (InterruptedException x){}
// in java/org/apache/catalina/tribes/transport/RxTaskPool.java
catch (java.lang.InterruptedException x) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (InterruptedException ignore){}
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (InterruptedException ignore) { }
// in java/org/apache/catalina/valves/SemaphoreValve.java
catch (InterruptedException e) { shouldRelease = false; permitDenied(request, response); return; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IllegalThreadStateException e) { try { Thread.sleep(500); } catch (InterruptedException ignored) { // Ignore } }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (InterruptedException ignored) { // Ignore }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (InterruptedException e) { log ("Interupted waiting for stderr reader thread"); }
// in java/org/apache/catalina/ssi/SSIExec.java
catch (InterruptedException e) { ssiMediator.log("Couldn't exec file: " + substitutedValue, e); writer.write(configErrMsg); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (InterruptedException e) { // Should never happen }
// in java/org/apache/catalina/core/ContainerBase.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/catalina/core/ContainerBase.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/catalina/core/StandardServer.java
catch (InterruptedException e) { // Ignored }
// in java/org/apache/catalina/core/StandardServer.java
catch( InterruptedException ex ) { // continue and check the flag }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (InterruptedException e) { // Ignore }
1
            
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); }
(Lib) IllegalStateException 39
            
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch(IllegalStateException ise) { // Session has been invalidated. // Ignore and fall through to application scope. }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch(IllegalStateException ise) { // Session has been invalidated. // Ignore and fall through to application scope. }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch(IllegalStateException ise) { // Session has been invalidated. // Ignore and fall throw to application scope. }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IllegalStateException ise) { include(errorPageURL); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IllegalStateException ise) { log.error(Localizer.getMessage("jsp.error.file.not.found", jspUri)); }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IllegalStateException ise) { // We are probably already being shutdown. Ignore this error. }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IllegalStateException ise) { // Hitting limit stops processing further params but does // not cause request to fail. parseFailed = true; UserDataHelper.Mode logMode = maxParamCountLog.getNextMode(); if (logMode != null) { String message = ise.getMessage(); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString( "parameters.maxCountFail.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } break; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalStateException e) { log.info(sm.getString("webappClassLoader.stopped", name), e); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (IllegalStateException ise) { // at least 1 of the sessions is invalidated req.setAttribute(APPLICATION_ERROR, "Can't sort session list: one session is invalidated"); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (IllegalStateException ise) { if (debug >= 1) { log("Can't invalidate already invalidated session id " + sessionId); } }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (IllegalStateException ise) { if (debug >= 1) { log("Can't remote attribute '" + attributeName + "' for invalidated session id " + sessionId); } }
// in java/org/apache/catalina/manager/JspHelper.java
catch (IllegalStateException ise) { //ignore: invalidated session return ""; }
// in java/org/apache/catalina/manager/JspHelper.java
catch (IllegalStateException ise) { //ignore: invalidated session return ""; }
// in java/org/apache/catalina/manager/JspHelper.java
catch (IllegalStateException ise) { //ignore: invalidated session return ""; }
// in java/org/apache/catalina/manager/JspHelper.java
catch (IllegalStateException ise) { //ignore: invalidated session return ""; }
// in java/org/apache/catalina/manager/JspHelper.java
catch (IllegalStateException ise) { //ignore: invalidated session return ""; }
// in java/org/apache/catalina/manager/util/SessionUtils.java
catch (IllegalStateException ise) { //ignore: invalidated session return null; }
// in java/org/apache/catalina/manager/util/SessionUtils.java
catch (IllegalStateException ise) { //ignore: invalidated session return null; }
// in java/org/apache/catalina/manager/util/SessionUtils.java
catch (IllegalStateException ise) { //ignore: invalidated session return -1; }
// in java/org/apache/catalina/manager/util/SessionUtils.java
catch (IllegalStateException ise) { //ignore: invalidated session return -1; }
// in java/org/apache/catalina/manager/util/SessionUtils.java
catch (IllegalStateException ise) { //ignore: invalidated session return -1; }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (IllegalStateException ise) { log.debug("Unable to decode message.",ise); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (IllegalStateException e) { // Ignore }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (IllegalStateException e) { // Ignore }
// in java/org/apache/catalina/authenticator/SSLAuthenticator.java
catch (IllegalStateException ise) { // Request body was too large for save buffer response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.certificates")); return false; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalStateException e) { // Silent catch }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalStateException e) { // Silent catch }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalStateException e) { // Silent catch }
// in java/org/apache/catalina/ssi/SSIFilter.java
catch (IllegalStateException e) { // Ignore, will try to use a writer }
// in java/org/apache/catalina/connector/Request.java
catch (IllegalStateException e) { checkSwallowInput(); partsParseException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IllegalStateException e) { throw e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IllegalStateException e) { try { ServletOutputStream stream = response.getOutputStream(); stream.close(); } catch (IllegalStateException f) { // Ignore } catch (IOException f) { // Ignore } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IllegalStateException f) { // Ignore }
6
            
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IllegalStateException e) { throw e; }
(Lib) UnsupportedEncodingException 36
            
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (java.io.UnsupportedEncodingException ex) { // Use the default encoding? writer = new OutputStreamWriter(buf); }
// in java/org/apache/jasper/compiler/JspUtil.java
catch (UnsupportedEncodingException ex) { err.jspError("jsp.error.unsupported.encoding", encoding); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (UnsupportedEncodingException ex) { errDispatcher.jspError("jsp.error.needAlternateJavaEncoding", javaEncoding); }
// in java/org/apache/juli/FileHandler.java
catch (UnsupportedEncodingException ex) { // Ignore }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (UnsupportedEncodingException e) { return DEFAULT_CHARSET; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (UnsupportedEncodingException e) { // Fall back to platform default if specified encoding is not // supported. headers = baos.toString(); }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
catch (UnsupportedEncodingException e) { return new String(rawdata); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
catch (UnsupportedEncodingException e) { // Impossible. All JVMs must support these. e.printStackTrace(); }
// in java/org/apache/el/parser/ELParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/el/parser/ELParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (UnsupportedEncodingException e) { // Should never happen with UTF-8 // If it does - ignore & return null }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (UnsupportedEncodingException uee) { // Impossible. All JVMs are required to support UTF-8. }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/ant/JMXSetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/ResourcesTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JMXGetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/AbstractCatalinaCommandTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JKStatusUpdateTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JMXQueryTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (UnsupportedEncodingException ex) { log.error(sm.getString( "accessLogValve.unsupportedEncoding", encoding), ex); }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
catch (UnsupportedEncodingException e) { // Should never happen - all JVMs are required to support UTF-8 return null; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
catch (UnsupportedEncodingException e) { retVal = queryString; }
// in java/org/apache/catalina/connector/Request.java
catch (UnsupportedEncodingException e) { // Ignore }
// in java/org/apache/catalina/connector/Request.java
catch (UnsupportedEncodingException uee) { try { value = part.getString(Parameters.DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { // Should not be possible } }
// in java/org/apache/catalina/connector/Request.java
catch (UnsupportedEncodingException e) { // Should not be possible }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (UnsupportedEncodingException e1) { log.warn(sm.getString("coyoteAdapter.parsePathParam", enc)); }
// in java/org/apache/catalina/util/RequestUtil.java
catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.parseParameters.uee", encoding), uee); } }
// in java/org/apache/catalina/util/RequestUtil.java
catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee); } }
// in java/org/apache/catalina/util/RequestUtil.java
catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee); } return null; }
// in java/javax/servlet/http/HttpUtils.java
catch (java.io.UnsupportedEncodingException e) { // XXX function should accept an encoding parameter & throw this // exception. Otherwise throw something expected. throw new IllegalArgumentException(e.getMessage(), e); }
// in java/javax/el/ExpressionFactory.java
catch (UnsupportedEncodingException e) { // Should never happen with UTF-8 // If it does - ignore & return null }
15
            
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/el/parser/ELParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/el/parser/ELParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/ant/JMXSetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/ResourcesTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JMXGetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/AbstractCatalinaCommandTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JKStatusUpdateTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JMXQueryTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/javax/servlet/http/HttpUtils.java
catch (java.io.UnsupportedEncodingException e) { // XXX function should accept an encoding parameter & throw this // exception. Otherwise throw something expected. throw new IllegalArgumentException(e.getMessage(), e); }
(Domain) LifecycleException 35
            
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { log.error("Catalina.stop: ", e); }
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) { throw new java.lang.Error(e); } else { log.error("Catalina.start", e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { log.error("Catalina.start: ", e); }
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { log.error("Catalina.stop", e); }
// in java/org/apache/catalina/realm/CombinedRealm.java
catch (LifecycleException e) { // If realm doesn't start can't authenticate against it iter.remove(); log.error(sm.getString("combinedRealm.realmStartFail", realm.getClass().getName()), e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (LifecycleException e){ throw new MBeanException(e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setLoader: stop: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setLoader: start: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setManager: stop: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setManager: start: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setCluster: stop: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setCluster: start: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setRealm: stop: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setRealm: start: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.addChild: start: ", e); throw new IllegalStateException ("ContainerBase.addChild: start: " + e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.removeChild: stop: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.removeChild: destroy: ", e); }
// in java/org/apache/catalina/core/StandardServer.java
catch (LifecycleException e) { // Ignore }
// in java/org/apache/catalina/core/StandardServer.java
catch (LifecycleException e) { // Ignore }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException e) { // Ignore }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException e) { // Ignore }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException e) { log.error(sm.getString( "standardService.connector.startFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException e) { log.error(sm.getString( "standardService.connector.stopFailed", connectors[j]), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException x) { log.error("Executor.start", x); }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException e) { log.error("Executor.stop", e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.warn("standardContext.namingResource.destroy.fail", e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.warn("standardContext.namingResource.init.fail", e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.error( sm.getString("standardContext.stoppingContext", getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.error( sm.getString("standardContext.startingContext", getName()), e); }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (LifecycleException e) { log.error("StandardPipeline.setBasic: stop", e); }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (LifecycleException e) { log.error("StandardPipeline.setBasic: start", e); return; }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (LifecycleException e) { log.error("StandardPipeline.addValve: start: ", e); }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (LifecycleException e) { log.error("StandardPipeline.removeValve: stop: ", e); }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (LifecycleException e) { log.error("StandardPipeline.removeValve: destroy: ", e); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (LifecycleException e) { // Just log. Still want to destroy. log.warn(sm.getString("lifecycleBase.destroyStopFail"), e); }
3
            
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) { throw new java.lang.Error(e); } else { log.error("Catalina.start", e); } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (LifecycleException e){ throw new MBeanException(e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.addChild: start: ", e); throw new IllegalStateException ("ContainerBase.addChild: start: " + e); }
(Lib) IllegalAccessException 31
            
// in java/org/apache/jasper/JspCompilationContext.java
catch (IllegalAccessException e) { log.warn(Localizer.getMessage("jsp.error.compiler"), e); }
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.IllegalAccessException iae) { NamingException ne = new NamingException(iae.getMessage()); ne.setRootCause(iae); throw ne; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalAccessException iae) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: IllegalAccessException for " + o.getClass() + " " + name + "=" + value + ")", iae); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalAccessException iae) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: IllegalAccessException for " + o.getClass() + " " + name + ")", iae); }
// in java/org/apache/el/parser/AstFunction.java
catch (IllegalAccessException iae) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), iae); }
// in java/org/apache/el/parser/AstValue.java
catch (IllegalAccessException iae) { throw new ELException(iae); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IllegalAccessException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (IllegalAccessException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.IllegalAccessException", className), e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (IllegalAccessException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/session/JDBCStore.java
catch (IllegalAccessException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (IllegalAccessException e) { log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IllegalAccessException e) { ServletException se = new ServletException(e); throw se; }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalAccessException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalAccessException e) { log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/javax/el/ExpressionFactory.java
catch (IllegalAccessException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
20
            
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.IllegalAccessException iae) { NamingException ne = new NamingException(iae.getMessage()); ne.setRootCause(iae); throw ne; }
// in java/org/apache/el/parser/AstFunction.java
catch (IllegalAccessException iae) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), iae); }
// in java/org/apache/el/parser/AstValue.java
catch (IllegalAccessException iae) { throw new ELException(iae); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IllegalAccessException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (IllegalAccessException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.IllegalAccessException", className), e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (IllegalAccessException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IllegalAccessException e) { ServletException se = new ServletException(e); throw se; }
// in java/javax/el/ExpressionFactory.java
catch (IllegalAccessException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
(Lib) IllegalArgumentException 31
            
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/jasper/compiler/Parser.java
catch (IllegalArgumentException iae) { // Duplicate attribute err.jspError(reader.mark(), "jsp.error.attribute.duplicate"); }
// in java/org/apache/jasper/compiler/Parser.java
catch (IllegalArgumentException iae) { err.jspError(start, iae.getMessage()); }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (IllegalArgumentException e) { proxyInstance = Proxy.newProxyInstance(tcl, serviceInterfaces, proxy); }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IllegalArgumentException e) { // Leave level set to null }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalArgumentException biae) { //the boolean method had the wrong //parameter types. lets try the other if (setPropertyMethodVoid!=null) { setPropertyMethodVoid.invoke(o, params); return true; }else { throw biae; } }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalArgumentException ex2) { log.warn("IAE " + o + " " + name + " " + value, ex2); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalArgumentException ex2) { log.warn("IAE " + o + " " + name, ex2); }
// in java/org/apache/tomcat/util/log/UserDataHelper.java
catch (IllegalArgumentException iae) { // Ignore - use default tempConfig = Config.INFO_THEN_DEBUG; }
// in java/org/apache/el/lang/ELSupport.java
catch (IllegalArgumentException iae) { throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/parser/AstValue.java
catch (IllegalArgumentException iae) { throw new ELException(iae); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { // Ignore: normal error due to dual definition of package }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (IllegalArgumentException e) { log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalArgumentException e) { // Ignore }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalArgumentException illegalArgument) { return true; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch(IllegalArgumentException illegalArgument) { return true; }
// in java/org/apache/catalina/connector/Request.java
catch (IllegalArgumentException e) { return null; }
// in java/org/apache/catalina/connector/Request.java
catch(IllegalArgumentException e) { // Ignore bad cookie }
// in java/org/apache/catalina/connector/Response.java
catch (IllegalArgumentException e) { setStatus(SC_NOT_FOUND); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (IllegalArgumentException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", env.getName())); }
// in java/org/apache/catalina/core/StandardContext.java
catch (IllegalArgumentException e) { log.error("Error initializing resources: " + e.getMessage()); ok = false; }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalArgumentException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalArgumentException e) { log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); }
// in java/javax/el/ExpressionFactory.java
catch (IllegalArgumentException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalArgumentException e) { throw new ELException(e); }
8
            
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalArgumentException biae) { //the boolean method had the wrong //parameter types. lets try the other if (setPropertyMethodVoid!=null) { setPropertyMethodVoid.invoke(o, params); return true; }else { throw biae; } }
// in java/org/apache/el/lang/ELSupport.java
catch (IllegalArgumentException iae) { throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/parser/AstValue.java
catch (IllegalArgumentException iae) { throw new ELException(iae); }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); }
// in java/javax/el/ExpressionFactory.java
catch (IllegalArgumentException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalArgumentException e) { throw new ELException(e); }
(Lib) MalformedURLException 31
            
// in java/org/apache/jasper/compiler/WebXml.java
catch (MalformedURLException e) { log.warn(Localizer.getMessage( "jsp.error.internal.filenotfound", altDDName)); }
// in java/org/apache/jasper/compiler/JarURLResource.java
catch (MalformedURLException e) { throw new RuntimeException("", e); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
catch (MalformedURLException me) { // Fallback to using context-relative path file = where.getFile(); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (MalformedURLException e) { throw new ServletException("Can not locate jsp file", e); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (MalformedURLException e) { throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"), e); }
// in java/org/apache/jasper/JspC.java
catch (MalformedURLException me) { System.out.println("**" + me); }
// in java/org/apache/tomcat/util/net/URL.java
catch (MalformedURLException e) { throw e; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.badUrl", defaultContextFile), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.badUrl", hostContextFile), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.webinfClassesUrl", resource), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { globalTimeStamp = -1; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { hostTimeStamp = -1; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString("contextConfig.applicationUrl")); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString("contextConfig.applicationUrl")); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (MalformedURLException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { IllegalArgumentException iae = new IllegalArgumentException ("Invalid repository: " + repository); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { repositoryURLs = new URL[0]; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { return null; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { return null; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (MalformedURLException e) { // Ignore }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (MalformedURLException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.invalidURL", serverName, url.toString()), e); return null; }
// in java/org/apache/catalina/connector/Response.java
catch (MalformedURLException e) { return (false); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { // Ignore and carry on }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { // Ignore and carry on }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { logger.error(sm.getString("naming.wsdlFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { // Ignore and carry on }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { // Ignore and carry on }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { logger.error(sm.getString("naming.wsdlFailed", e)); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (MalformedURLException e) { log.error(sm.getString( "jreLeakListener.jarUrlConnCacheFail"), e); }
5
            
// in java/org/apache/jasper/compiler/JarURLResource.java
catch (MalformedURLException e) { throw new RuntimeException("", e); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (MalformedURLException e) { throw new ServletException("Can not locate jsp file", e); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (MalformedURLException e) { throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"), e); }
// in java/org/apache/tomcat/util/net/URL.java
catch (MalformedURLException e) { throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { IllegalArgumentException iae = new IllegalArgumentException ("Invalid repository: " + repository); iae.initCause(e); throw iae; }
(Lib) PrivilegedActionException 31
            
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); throw (JasperException)e; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ServletException) throw (ServletException)t; throw new ServletException("Could not precompile jsp: " + jspFile, e); }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof ClassNotFoundException){ throw (ClassNotFoundException)exception; } else if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in load() " + exception); }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in unLoad() " + exception); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); log.error("Exception clearing the Store: " + exception, exception); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); log.error("Exception in the Store during load: " + exception, exception); return; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); log.error("Exception in the Store during removeSession: " + exception, exception); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (PrivilegedActionException ex) { Exception e = ex.getException(); log.error(sm.getString( "persistentManager.swapInException", id), e); if (e instanceof IOException){ throw (IOException)e; } else if (e instanceof ClassNotFoundException) { throw (ClassNotFoundException)e; } }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException) { throw (IOException) exception; } log.error("Exception in the Store during writeSession: " + exception, exception); }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (PrivilegedActionException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail", e)); response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
// in java/org/apache/catalina/connector/OutputBuffer.java
catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } }
// in java/org/apache/catalina/connector/Response.java
catch (PrivilegedActionException pae){ IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(pae.getException()); throw iae; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage() ,e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/InputBuffer.java
catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } }
// in java/org/apache/catalina/connector/ResponseFacade.java
catch(PrivilegedActionException e){ Exception ex = e.getException(); if (ex instanceof IOException){ throw (IOException)ex; } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; }
// in java/org/apache/catalina/security/SecurityUtil.java
catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
52
            
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); throw (JasperException)e; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ServletException) throw (ServletException)t; throw new ServletException("Could not precompile jsp: " + jspFile, e); }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof ClassNotFoundException){ throw (ClassNotFoundException)exception; } else if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in load() " + exception); }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in unLoad() " + exception); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (PrivilegedActionException ex) { Exception e = ex.getException(); log.error(sm.getString( "persistentManager.swapInException", id), e); if (e instanceof IOException){ throw (IOException)e; } else if (e instanceof ClassNotFoundException) { throw (ClassNotFoundException)e; } }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException) { throw (IOException) exception; } log.error("Exception in the Store during writeSession: " + exception, exception); }
// in java/org/apache/catalina/connector/OutputBuffer.java
catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } }
// in java/org/apache/catalina/connector/Response.java
catch (PrivilegedActionException pae){ IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(pae.getException()); throw iae; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage() ,e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/InputBuffer.java
catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } }
// in java/org/apache/catalina/connector/ResponseFacade.java
catch(PrivilegedActionException e){ Exception ex = e.getException(); if (ex instanceof IOException){ throw (IOException)ex; } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; }
// in java/org/apache/catalina/security/SecurityUtil.java
catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
(Lib) InstanceNotFoundException 30
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (InstanceNotFoundException e) { throw e; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (InstanceNotFoundException e) { log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", on), e); }
29
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (InstanceNotFoundException e) { throw e; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
(Lib) SQLException 29
            
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (SQLException e) { containerLog.error("Exception committing connection before closing:", e); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (SQLException e) { containerLog.error(sm.getString("dataSourceRealm.close"), e); // Just log it here }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch(SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getPassword.exception", username)); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getPassword.exception", username)); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch(SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getRoles.exception", username)); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getRoles.exception", username)); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { // Log the problem for posterity containerLog.error(sm.getString("jdbcRealm.exception"), e); // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { containerLog.warn(sm.getString("jdbcRealm.close"), e); // Just log it here }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { // Log the problem for posterity containerLog.error(sm.getString("jdbcRealm.exception"), e); // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { // Log the problem for posterity containerLog.error(sm.getString("jdbcRealm.exception"), e); // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { containerLog.error(sm.getString("jdbcRealm.open"), e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); keys = new String[0]; // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { // Ignore }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { // Ignore }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { // Ignore }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionSQLException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".commitSQLException"), e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".close", e.toString())); // Just log it here }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { // Ignore }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { // Log the problem for posterity container.getLogger().error(sm.getString("jdbcAccessLogValve.exception"), e); // Close the connection so that it gets reopened next time if (conn != null) { close(); } }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { container.getLogger().error(sm.getString("jdbcAccessLogValeve.close"), e); // Just log it here }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { throw new LifecycleException(e); }
1
            
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { throw new LifecycleException(e); }
(Lib) InvalidTargetObjectTypeException 28
            
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
28
            
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
(Lib) InvocationTargetException 24
            
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.reflect.InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } NamingException ne = new NamingException(ite.getMessage()); ne.setRootCause(ite); throw ne; }
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
catch (InvocationTargetException ite) { throw ite.getTargetException(); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); if (log.isDebugEnabled()) log.debug("IntrospectionUtils: InvocationTargetException for " + o.getClass() + " " + name + "=" + value + ")", ie); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); if (log.isDebugEnabled()) log.debug("IntrospectionUtils: InvocationTargetException for " + o.getClass() + " " + name + ")"); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; }
// in java/org/apache/el/parser/AstFunction.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(MessageFactory.get("error.function", this .getOutputName()), cause); }
// in java/org/apache/el/parser/AstValue.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (InvocationTargetException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (InvocationTargetException e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), t); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); ServletException se = new ServletException(e); throw se; }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/javax/el/ExpressionFactory.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
38
            
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.reflect.InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } NamingException ne = new NamingException(ite.getMessage()); ne.setRootCause(ite); throw ne; }
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
catch (InvocationTargetException ite) { throw ite.getTargetException(); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; }
// in java/org/apache/el/parser/AstFunction.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(MessageFactory.get("error.function", this .getOutputName()), cause); }
// in java/org/apache/el/parser/AstValue.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); ServletException se = new ServletException(e); throw se; }
// in java/javax/el/ExpressionFactory.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
(Lib) RuntimeOperationsException 22
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (RuntimeOperationsException e) { throw e; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
22
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (RuntimeOperationsException e) { throw e; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
(Domain) ServletException 22
            
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (ServletException e) { throw e; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
catch (ServletException e) { throw new IOException("Couldn't include file: " + originalPath + " because of ServletException: " + e.getMessage()); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ServletException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.init", listenerClass.getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (ServletException e) { getLogger().error(sm.getString("standardWrapper.loadException", getName()), StandardWrapper.getRootCause(e)); // NOTE: load errors (including a servlet that throws // UnavailableException from tht init() method) are NOT // fatal to application startup }
// in java/org/apache/catalina/core/StandardContext.java
catch (ServletException e) { // TODO: Log error ok = false; break; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { throw e; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { throw e; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw f; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { getServletContext().log(sm.getString ("standardWrapper.unloadException", getName()), e); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause); } servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = e; }
14
            
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (ServletException e) { throw e; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
catch (ServletException e) { throw new IOException("Couldn't include file: " + originalPath + " because of ServletException: " + e.getMessage()); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ServletException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.init", listenerClass.getName()), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { throw e; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { throw e; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw f; }
(Domain) ChannelException 21
            
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( ChannelException cx ) { throw cx; }
// in java/org/apache/catalina/tribes/group/interceptors/TcpPingInterceptor.java
catch (ChannelException x) { log.warn("Unable to send TCP ping.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( ChannelException cx ) { FaultyMember[] mbrs = cx.getFaultyMembers(); for ( int i=0; i<mbrs.length; i++ ) { if ( mbrs[i].getCause()!=null && (!(mbrs[i].getCause() instanceof RemoteProcessException)) ) {//RemoteProcessException's are ok this.memberDisappeared(mbrs[i].getMember()); }//end if }//for throw cx; }
// in java/org/apache/catalina/tribes/group/interceptors/OrderInterceptor.java
catch ( ChannelException x ) { if ( cx == null ) cx = x; cx.addFaultyMember(x.getFaultyMembers()); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.warn("Unable to send election message to:"+msg.getMembers()[current]); current = Arrays.nextIndex(msg.getMembers()[current],msg.getMembers()); if ( current == next ) throw x; }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.error("Error processing coordination message. Could be fatal.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.error("Unable to start election when member was added.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.error("Unable to start election when member was removed.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/ThroughputInterceptor.java
catch ( ChannelException x ) { msgTxErr.addAndGet(1); if ( access.get() == 1 ) access.addAndGet(-1); throw x; }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
catch (ChannelException x) { sender.disconnect(); throw x; }
// in java/org/apache/catalina/tribes/tipis/LazyReplicatedMap.java
catch ( ChannelException x ) { log.error("Unable to replicate backup key:"+key+" to backup:"+next+". Reason:"+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/tipis/LazyReplicatedMap.java
catch ( ChannelException x ) { //log the error, but proceed, this should only happen if a node went down, //and if the node went down, then it can't receive the message, the others //should still get it. log.error("Unable to replicate proxy key:"+key+" to backup:"+next+". Reason:"+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.warn("Unable to send map start message."); // remove listener from channel this.rpcChannel.breakdown(); this.channel.removeChannelListener(this); this.channel.removeMembershipListener(this); throw new RuntimeException("Unable to start replicated map.",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException ce) { // Handle known failed members FaultyMember[] faultyMembers = ce.getFaultyMembers(); for (FaultyMember faultyMember : faultyMembers) { memberDisappeared(faultyMember.getMember()); } }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to replicate data.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to transfer LazyReplicatedMap state.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to select backup node.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to relocate[" + entry.getKey() + "] to a new backup node", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to relocate[" + entry.getKey() + "] to a new backup node", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( ChannelException x ) { log.error("Unable to replicate out data for a LazyReplicatedMap.remove operation",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to replicate out data for a LazyReplicatedMap.put operation", x); }
6
            
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( ChannelException cx ) { throw cx; }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( ChannelException cx ) { FaultyMember[] mbrs = cx.getFaultyMembers(); for ( int i=0; i<mbrs.length; i++ ) { if ( mbrs[i].getCause()!=null && (!(mbrs[i].getCause() instanceof RemoteProcessException)) ) {//RemoteProcessException's are ok this.memberDisappeared(mbrs[i].getMember()); }//end if }//for throw cx; }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.warn("Unable to send election message to:"+msg.getMembers()[current]); current = Arrays.nextIndex(msg.getMembers()[current],msg.getMembers()); if ( current == next ) throw x; }
// in java/org/apache/catalina/tribes/group/interceptors/ThroughputInterceptor.java
catch ( ChannelException x ) { msgTxErr.addAndGet(1); if ( access.get() == 1 ) access.addAndGet(-1); throw x; }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
catch (ChannelException x) { sender.disconnect(); throw x; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.warn("Unable to send map start message."); // remove listener from channel this.rpcChannel.breakdown(); this.channel.removeChannelListener(this); this.channel.removeMembershipListener(this); throw new RuntimeException("Unable to start replicated map.",x); }
(Lib) NoSuchMethodException 21
            
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (NoSuchMethodException e) { err.jspError("jsp.error.noFunctionMethod", n .getMethodName(), n.getName(), c.getName()); }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (NoSuchMethodException e) { exception = e; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (NoSuchMethodException e) { exception = e; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (NoSuchMethodException e) { exception = e; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (NoSuchMethodException e) { exception = e; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (NoSuchMethodException e) { exception = e; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (NoSuchMethodException e) { exception = e; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsIntrospectionSource.java
catch (java.lang.NoSuchMethodException e) { return false; }
// in java/org/apache/catalina/startup/WebRuleSet.java
catch (NoSuchMethodException e) { digester.getLogger().error("Can't find method " + method + " in " + top + " CLASS " + top.getClass()); return; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchMethodException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (NoSuchMethodException e) { log.debug(sm.getString("namingResources.cleanupNoClose", name, container, closeMethod)); return; }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (NoSuchMethodException e) { // Should never happen. On that basis don't log // it. }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (NoSuchMethodException e) { // Should never happen. On that basis don't log it. }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (NoSuchMethodException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (NoSuchMethodException e) { log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/javax/el/ExpressionFactory.java
catch (NoSuchMethodException nsme) { // This can be ignored // This is OK for this constructor not to exist }
// in java/javax/el/BeanELResolver.java
catch (NoSuchMethodException e) { // Ignore }
// in java/javax/el/BeanELResolver.java
catch (NoSuchMethodException e) { // Ignore }
// in java/javax/el/BeanELResolver.java
catch (NoSuchMethodException e) { throw new MethodNotFoundException(e); }
3
            
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
// in java/javax/el/BeanELResolver.java
catch (NoSuchMethodException e) { throw new MethodNotFoundException(e); }
(Lib) InstantiationException 17
            
// in java/org/apache/jasper/JspCompilationContext.java
catch (InstantiationException e) { log.warn(Localizer.getMessage("jsp.error.compiler"), e); }
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.InstantiationException ie2) { NamingException ne = new NamingException(ie2.getMessage()); ne.setRootCause(ie2); throw ne; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (InstantiationException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (InstantiationException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.InstantiationException", className), e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (InstantiationException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/session/JDBCStore.java
catch (InstantiationException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (InstantiationException e) { ServletException se = new ServletException(e); throw se; }
// in java/javax/el/ExpressionFactory.java
catch (InstantiationException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
15
            
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.InstantiationException ie2) { NamingException ne = new NamingException(ie2.getMessage()); ne.setRootCause(ie2); throw ne; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (InstantiationException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (InstantiationException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.InstantiationException", className), e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (InstantiationException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (InstantiationException e) { ServletException se = new ServletException(e); throw se; }
// in java/javax/el/ExpressionFactory.java
catch (InstantiationException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
(Lib) FileNotFoundException 16
            
// in java/org/apache/jasper/compiler/ParserController.java
catch (FileNotFoundException ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (FileNotFoundException ex) { // if file not found on filesystem, get the resource through // the context return ctxt.getResourceAsStream(uri); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (FileNotFoundException ex) { err.jspError(mark, "jsp.error.file.not.found", tldName); }
// in java/org/apache/jasper/compiler/Parser.java
catch (FileNotFoundException ex) { err.jspError(start, "jsp.error.file.not.found", file); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
catch (FileNotFoundException e) { err.jspError("jsp.error.file.not.found", path); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (FileNotFoundException fnfe) { throw new SAXParseException( Localizer.getMessage("jsp.error.file.not.found", fname), locator, fnfe); }
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch (FileNotFoundException ex) { ctxt.incrementRemoved(); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (FileNotFoundException ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (FileNotFoundException fnfe) { handleMissingResource(request, response, jspUri); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (FileNotFoundException fnfe) { // Re-throw to let caller handle this - will result in a 404 throw fnfe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (FileNotFoundException fnfe) { log.error(sm.getString("jsse.keystore_load_failed", type, path, fnfe.getMessage()), fnfe); throw fnfe; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (FileNotFoundException e) { log.error(sm.getString("contextConfig.altDDNotFound", altDDName)); }
// in java/org/apache/catalina/session/StandardManager.java
catch (FileNotFoundException e) { if (log.isDebugEnabled()) log.debug("No persisted data file found"); return; }
// in java/org/apache/catalina/session/FileStore.java
catch (FileNotFoundException e) { if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug("No persisted data file found"); return (null); }
// in java/javax/el/ExpressionFactory.java
catch (FileNotFoundException e) { // Should not happen - ignore it if it does }
6
            
// in java/org/apache/jasper/compiler/ParserController.java
catch (FileNotFoundException ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (FileNotFoundException fnfe) { throw new SAXParseException( Localizer.getMessage("jsp.error.file.not.found", fname), locator, fnfe); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (FileNotFoundException ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (FileNotFoundException fnfe) { // Re-throw to let caller handle this - will result in a 404 throw fnfe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (FileNotFoundException fnfe) { log.error(sm.getString("jsse.keystore_load_failed", type, path, fnfe.getMessage()), fnfe); throw fnfe; }
(Domain) ELException 15
            
// in java/org/apache/jasper/compiler/Validator.java
catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", attrs.getValue(i), e.toString()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", value, e .toString()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ELException e) { }
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/jasper/el/ExpressionEvaluatorImpl.java
catch (javax.el.ELException e) { throw new ELParseException(e.getMessage()); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/el/parser/AstFunction.java
catch (ELException ele) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), ele); }
// in java/org/apache/el/ValueExpressionImpl.java
catch (ELException ele) { return false; }
// in java/org/apache/el/util/ReflectionUtil.java
catch (ELException e) { return false; }
16
            
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/jasper/el/ExpressionEvaluatorImpl.java
catch (javax.el.ELException e) { throw new ELParseException(e.getMessage()); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/el/parser/AstFunction.java
catch (ELException ele) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), ele); }
(Lib) MalformedObjectNameException 15
            
// in java/org/apache/tomcat/util/modeler/Registry.java
catch (MalformedObjectNameException e) { log.info("Error creating object name " + e ); }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch (MalformedObjectNameException e) { return null; }
// in java/org/apache/catalina/mbeans/UserMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for group " + group); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/UserMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role " + role); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (MalformedObjectNameException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for group [" + groupname + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role [" + rolename + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for user [" + username + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/GroupMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role " + role); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/GroupMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for user " + user); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for environment " + envs[i]); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for resource " + resources[i]); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for resource " + resourceLinks[i]); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (MalformedObjectNameException e) { if (isEcho()) handleErrorOutput("Unable to convert to ObjectName:" + value); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (MalformedObjectNameException e) { log.warn(sm.getString("lifecycleMBeanBase.registerFail", obj, name), e); }
11
            
// in java/org/apache/catalina/mbeans/UserMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for group " + group); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/UserMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role " + role); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (MalformedObjectNameException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for group [" + groupname + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role [" + rolename + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for user [" + username + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/GroupMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role " + role); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/GroupMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for user " + user); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for environment " + envs[i]); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for resource " + resources[i]); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for resource " + resourceLinks[i]); iae.initCause(e); throw iae; }
(Domain) JasperException 14
            
// in java/org/apache/jasper/compiler/SmapUtil.java
catch (JasperException ex) { }
// in java/org/apache/jasper/compiler/SmapUtil.java
catch (JasperException ex) { }
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
catch (JasperException je) { throw new RuntimeException(je.toString(), je); }
// in java/org/apache/jasper/compiler/Node.java
catch (JasperException e) { }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (JasperException e) { // Hack - makes exception handling simpler throw new IOException(e); }
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (JasperException e) { log.error("Error visiting node", e); }
// in java/org/apache/jasper/compiler/Generator.java
catch (JasperException ex) { // Ignore }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (JasperException je) { throw new SAXParseException( Localizer.getMessage("jsp.error.could.not.add.taglibraries"), locator, je); }
// in java/org/apache/jasper/compiler/Dumper.java
catch (JasperException e) { e.printStackTrace(); }
// in java/org/apache/jasper/compiler/Dumper.java
catch (JasperException e) { e.printStackTrace(); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { System.err.println(je); if (jspc.dieLevel != NO_DIE_LEVEL) { System.exit(jspc.dieLevel); } }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { rootCause.printStackTrace(); } throw je; }
6
            
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
catch (JasperException je) { throw new RuntimeException(je.toString(), je); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (JasperException e) { // Hack - makes exception handling simpler throw new IOException(e); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (JasperException je) { throw new SAXParseException( Localizer.getMessage("jsp.error.could.not.add.taglibraries"), locator, je); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { rootCause.printStackTrace(); } throw je; }
(Lib) CancelledKeyException 13
            
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (CancelledKeyException cx) { cancel(sk,key,ops); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (CancelledKeyException cx) { if (sk!=null) { sk.cancel(); sk.attach(null); } }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch ( CancelledKeyException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); continue; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (CancelledKeyException ckx) { sk.cancel(); countDown(attachment.getReadLatch()); countDown(attachment.getWriteLatch()); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (CancelledKeyException ckx) { try { socket.getPoller().cancelledKey(key,SocketStatus.DISCONNECT); }catch (Exception ignore) {} }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( CancelledKeyException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( CancelledKeyException ckx ) { cancelledKey(sk, SocketStatus.ERROR); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( CancelledKeyException ckx ) { cancelledKey(key, SocketStatus.ERROR); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( CancelledKeyException ckx ) { handshake = -1; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch(CancelledKeyException cx) { socket.getPoller().cancelledKey(key,null); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (CancelledKeyException ckx ) { NioReceiver.cancelledKey(key); if ( log.isTraceEnabled() ) log.trace("CKX Cancelling key:"+key); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch ( CancelledKeyException ckx ) { cancelledKey(key); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (java.nio.channels.CancelledKeyException nx) { log.warn("Replication client disconnected, error when polling key. Ignoring client."); }
1
            
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( CancelledKeyException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; }
(Lib) MissingResourceException 13
            
// in java/org/apache/jasper/compiler/Localizer.java
catch (MissingResourceException e) { }
// in java/org/apache/jasper/compiler/Localizer.java
catch (MissingResourceException e) { }
// in java/org/apache/naming/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { tempBundle = ResourceBundle.getBundle( bundleName, Locale.getDefault(), cl); } catch(MissingResourceException ex2) { // Ignore } } }
// in java/org/apache/naming/StringManager.java
catch(MissingResourceException ex2) { // Ignore }
// in java/org/apache/naming/StringManager.java
catch(MissingResourceException mre) { //bad: shouldn't mask an exception the following way: // str = "[cannot find message associated with key '" + key + "' due to " + mre + "]"; // because it hides the fact that the String was missing // from the calling code. //good: could just throw the exception (or wrap it in another) // but that would probably cause much havoc on existing // code. //better: consistent with container pattern to // simply return null. Calling code can then do // a null check. str = null; }
// in java/org/apache/tomcat/util/res/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { bnd = ResourceBundle.getBundle(bundleName, locale, cl); } catch(MissingResourceException ex2) { // Ignore } } }
// in java/org/apache/tomcat/util/res/StringManager.java
catch(MissingResourceException ex2) { // Ignore }
// in java/org/apache/tomcat/util/res/StringManager.java
catch(MissingResourceException mre) { //bad: shouldn't mask an exception the following way: // str = "[cannot find message associated with key '" + key + // "' due to " + mre + "]"; // because it hides the fact that the String was missing // from the calling code. //good: could just throw the exception (or wrap it in another) // but that would probably cause much havoc on existing // code. //better: consistent with container pattern to // simply return null. Calling code can then do // a null check. str = null; }
// in java/org/apache/catalina/tribes/util/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { bundle = ResourceBundle.getBundle( bundleName, Locale.getDefault(), cl); } catch(MissingResourceException ex2) { // Ignore } } }
// in java/org/apache/catalina/tribes/util/StringManager.java
catch(MissingResourceException ex2) { // Ignore }
// in java/org/apache/catalina/tribes/util/StringManager.java
catch(MissingResourceException mre) { //bad: shouldn't mask an exception the following way: // str = "[cannot find message associated with key '" + key + "' due to " + mre + "]"; // because it hides the fact that the String was missing // from the calling code. //good: could just throw the exception (or wrap it in another) // but that would probably cause much havoc on existing // code. //better: consistent with container pattern to // simply return null. Calling code can then do // a null check. str = null; }
// in java/javax/el/ResourceBundleELResolver.java
catch (MissingResourceException mre) { return "???" + property.toString() + "???"; }
// in java/javax/el/ELResolver.java
catch (MissingResourceException e) { return "Missing Resource: '" + name + "' for Locale " + locale.getDisplayName(); }
0
(Lib) RuntimeException 13
            
// in java/org/apache/jasper/servlet/JspServlet.java
catch (RuntimeException e) { throw e; }
// in java/org/apache/tomcat/util/buf/UDecoder.java
catch (RuntimeException ex) { throw new DecodeException(ex.getMessage()); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
catch( RuntimeException ex) { log.error("RuntimeException " + ex); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (RuntimeException e) { throw new ServletException(sm.getString( "expiresFilter.exceptionProcessingParameter", name, value), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); runtimeException = e; }
13
            
// in java/org/apache/jasper/servlet/JspServlet.java
catch (RuntimeException e) { throw e; }
// in java/org/apache/tomcat/util/buf/UDecoder.java
catch (RuntimeException ex) { throw new DecodeException(ex.getMessage()); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (RuntimeException e) { throw new ServletException(sm.getString( "expiresFilter.exceptionProcessingParameter", name, value), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); }
(Lib) SecurityException 13
            
// in java/org/apache/jasper/servlet/JasperLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; se.printStackTrace(); throw new ClassNotFoundException(error); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (SecurityException ex1) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: SecurityException for " + o.getClass() + " " + name + "=" + value + ")", ex1); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (SecurityException ex1) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: SecurityException for " + o.getClass() + " " + name + ")", ex1); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { return; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (SecurityException e) { log.debug(sm.getString("namingResources.cleanupCloseSecurity", closeMethod, name, container)); return; }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (SecurityException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch(SecurityException e) { // Ignore. Don't need call to getPolicy() to be // successful, just need to trigger static initializer. }
// in java/javax/el/ExpressionFactory.java
catch (SecurityException se) { throw new ELException(se); }
3
            
// in java/org/apache/jasper/servlet/JasperLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; se.printStackTrace(); throw new ClassNotFoundException(error); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); }
// in java/javax/el/ExpressionFactory.java
catch (SecurityException se) { throw new ELException(se); }
(Lib) ClassCastException 12
            
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassCastException e) { log.error(sm.getString("contextConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/TldConfig.java
catch (ClassCastException e) { log.error(sm.getString("tldConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/EngineConfig.java
catch (ClassCastException e) { log.error(sm.getString("engineConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/HostConfig.java
catch (ClassCastException e) { log.error(sm.getString("hostConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/UserConfig.java
catch (ClassCastException e) { log.error(sm.getString("hostConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/Tomcat.java
catch (ClassCastException e) { return; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassCastException e) { log.error(" Failed tracking modifications of '" + getJarPath() + "' : " + e.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassCastException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (ClassCastException cce) { project.log("wrong object reference " + refId + " - " + pref.getClass()); return null; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (ClassCastException cce) { getProject().log( "Wrong object reference " + getRef() + " - " + pref.getClass()); return null; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ClassCastException e) { unavailable(null); // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.notServlet", servletClass), e); }
// in java/javax/servlet/http/HttpServlet.java
catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); }
3
            
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassCastException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ClassCastException e) { unavailable(null); // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.notServlet", servletClass), e); }
// in java/javax/servlet/http/HttpServlet.java
catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); }
(Lib) CloneNotSupportedException 9
            
// in java/org/apache/tomcat/util/buf/CharChunk.java
catch (CloneNotSupportedException e) { // Cannot happen return null; }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapEntry.java
catch (CloneNotSupportedException e) { }
// in java/org/apache/tomcat/util/bcel/classfile/Attribute.java
catch (CloneNotSupportedException e) { e.printStackTrace(); // Never occurs }
// in java/org/apache/tomcat/util/bcel/classfile/LocalVariable.java
catch (CloneNotSupportedException e) { }
// in java/org/apache/tomcat/util/bcel/classfile/InnerClass.java
catch (CloneNotSupportedException e) { }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapTableEntry.java
catch (CloneNotSupportedException e) { }
// in java/org/apache/tomcat/util/bcel/classfile/CodeException.java
catch (CloneNotSupportedException e) { }
// in java/org/apache/tomcat/util/bcel/classfile/LineNumber.java
catch (CloneNotSupportedException e) { }
// in java/javax/servlet/http/Cookie.java
catch (CloneNotSupportedException e) { throw new RuntimeException(e.getMessage()); }
1
            
// in java/javax/servlet/http/Cookie.java
catch (CloneNotSupportedException e) { throw new RuntimeException(e.getMessage()); }
(Lib) EmptyStackException 9
            
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { throw createSAXException("endPrefixMapping popped too many times"); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/log/SystemLogHandler.java
catch (EmptyStackException e) { log = new CaptureLog(); }
1
            
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { throw createSAXException("endPrefixMapping popped too many times"); }
(Lib) InterruptedIOException 9
            
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (InterruptedIOException e) { error = true; }
0
(Lib) NoSuchAlgorithmException 9
            
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (NoSuchAlgorithmException e) { throw new IOException(e); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (NoSuchAlgorithmException e) { // Assume no RFC 5746 support }
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { throw new LifecycleException (sm.getString("realmBase.algorithm", digest), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { log.error("Couldn't get MD5 digest: ", e); throw new IllegalStateException(e.getMessage()); }
// in java/org/apache/catalina/websocket/WebSocketServlet.java
catch (NoSuchAlgorithmException e) { throw new ServletException(e); }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new IllegalStateException(); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NoSuchAlgorithmException e) { throw new UnavailableException("No MD5"); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (NoSuchAlgorithmException e) { log.error(sm.getString("sessionIdGenerator.randomAlgorithm", secureRandomAlgorithm), e); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (NoSuchAlgorithmException e) { log.error(sm.getString("sessionIdGenerator.randomAlgorithm", secureRandomAlgorithm), e); }
6
            
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (NoSuchAlgorithmException e) { throw new IOException(e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { throw new LifecycleException (sm.getString("realmBase.algorithm", digest), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { log.error("Couldn't get MD5 digest: ", e); throw new IllegalStateException(e.getMessage()); }
// in java/org/apache/catalina/websocket/WebSocketServlet.java
catch (NoSuchAlgorithmException e) { throw new ServletException(e); }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new IllegalStateException(); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NoSuchAlgorithmException e) { throw new UnavailableException("No MD5"); }
(Domain) ParseException 9
            
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (ParseException e) { // Ignore }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (ParseException e) { // Ignore }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (ParseException e) { // Ignore }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (ParseException e) { // Ignore }
// in java/org/apache/coyote/Response.java
catch (ParseException e) { // Invalid - Assume no charset and just pass through whatever // the user provided. this.contentType = type; return; }
// in java/org/apache/tomcat/util/http/FastHttpDateFormat.java
catch (ParseException e) { // Ignore }
// in java/org/apache/el/parser/ELParser.java
catch (ParseException pe) { throw new ELException(pe.getMessage());
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (Exception ParseException) { // Ignore }
// in java/org/apache/catalina/ssi/SSIConditional.java
catch (ParseException e) { //throw new SsiCommandException( "Error parsing expression." ); throw new SSIStopProcessingException(); }
// in java/org/apache/catalina/connector/Response.java
catch (ParseException e) { // Invalid - Assume no charset and just pass through whatever // the user provided. coyoteResponse.setContentTypeNoCharset(type); return; }
2
            
// in java/org/apache/el/parser/ELParser.java
catch (ParseException pe) { throw new ELException(pe.getMessage());
// in java/org/apache/catalina/ssi/SSIConditional.java
catch (ParseException e) { //throw new SsiCommandException( "Error parsing expression." ); throw new SSIStopProcessingException(); }
(Lib) RejectedExecutionException 9
            
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (RejectedExecutionException rx) { log.warn("Socket processing request was rejected for:"+socket,rx); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for: "+socket, x); return false; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket reprocessing request was rejected for:"+socket,x); try { //unable to handle connection at this time handler.process(socket, SocketStatus.DISCONNECT); } finally { countDownConnection(); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); return false; }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
catch (RejectedExecutionException rx) { //there could have been contention around the queue if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException("Work queue full."); }
4
            
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
catch (RejectedExecutionException rx) { //there could have been contention around the queue if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException("Work queue full."); }
(Lib) NoSuchElementException 8
            
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
catch (NoSuchElementException x ) { try { synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 s = Selector.open(); } } catch (IOException iox) { } }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "expiresFilter.startingPointNotFound", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException( sm.getString( "Duration unit not found after amount {} in directive '{}'", Integer.valueOf(amount), line)); }
// in java/org/apache/catalina/tribes/transport/RxTaskPool.java
catch (java.util.NoSuchElementException x) { //this means that there are no available workers worker = null; }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
catch (java.util.NoSuchElementException x) { //do nothing, we wanted to remove it anyway }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (NoSuchElementException nse) { // Application does not contain a MANIFEST.MF file }
4
            
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "expiresFilter.startingPointNotFound", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException( sm.getString( "Duration unit not found after amount {} in directive '{}'", Integer.valueOf(amount), line)); }
(Lib) NoSuchFieldException 8
            
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException nfe){ targetField = thread.getClass().getDeclaredField("runnable"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException nfe){ Method cancelMethod = thread.getClass().getDeclaredMethod("cancel"); if (null != cancelMethod){ synchronized(thread) { cancelMethod.setAccessible(true); cancelMethod.invoke(thread); } } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { if (System.getProperty("java.vendor").startsWith("Sun")) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } else { log.debug(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (NoSuchFieldException e) { // Should never happen. On that basis don't log // it. }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (NoSuchFieldException e) { // Should never happen. On that basis don't log it. }
0
(Lib) NullPointerException 7
            
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch ( NullPointerException x ) { //sun bug 5076772 on windows JDK 1.5 if (selector==null) throw x; if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( NullPointerException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.accept.fail"), npe); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NullPointerException e) { /* BZ 42449 - Kludge Sun's LDAP provider with broken SSL */ // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (NullPointerException e) { throw new MBeanException(e); }
3
            
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch ( NullPointerException x ) { //sun bug 5076772 on windows JDK 1.5 if (selector==null) throw x; if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( NullPointerException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (NullPointerException e) { throw new MBeanException(e); }
(Domain) UnavailableException 7
            
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error( sm.getString("standardWrapper.allocateException", wrapper.getName()), e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { // The response is already committed, so it's not possible to do anything }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (UnavailableException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); unavailable(f); throw f; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (UnavailableException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); servletException = e; wrapper.unavailable(e); }
2
            
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (UnavailableException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); unavailable(f); throw f; }
(Lib) AccessControlException 6
            
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (AccessControlException ace) { // No permission to configure logging in context // Log and carry on ClassLoaderLogInfo info = classLoaderLoggers.get(ClassLoader.getSystemClassLoader()); if (info != null) { Logger log = info.loggers.get(""); if (log != null) { Permission perm = ace.getPermission(); if (perm instanceof FilePermission && perm.getActions().equals("read")) { log.warning("Reading " + perm.getName() + " is not permitted. See \"per context logging\" in the default catalina.policy file."); } else { log.warning("Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file."); log.warning("Original error was: " + ace.getMessage()); } } } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (AccessControlException e) { // Some policy files may restrict this, even for the core, // so this exception is ignored }
// in java/org/apache/catalina/core/StandardServer.java
catch (AccessControlException ace) { log.warn("StandardServer.accept security exception: " + ace.getMessage(), ace); continue; }
3
            
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
(Domain) Error 6
            
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Error e) { e.printStackTrace(); if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(" endpoint.poll.limitedpollsize " + size); return 0; } else if (Status.APR_STATUS_IS_ENOTIMPL(e.getError())) { // thread safe not supported log.severe("THREAD SAFE NOT SUPPORTED" + e); threadSafe = false; // try again without the flags continue; } else { log.severe("endpoint.poll.initfail" + e); return 0; } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Error e) { if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(sm.getString("endpoint.poll.limitedpollsize", "" + size)); return 0; } else { log.error(sm.getString("endpoint.poll.initfail"), e); return -1; } }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Finish event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Body event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("End event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Begin event threw error", e); throw e; }
4
            
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Finish event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Body event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("End event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Begin event threw error", e); throw e; }
(Lib) GSSException 6
            
// in java/org/apache/catalina/realm/CombinedRealm.java
catch (GSSException e) { log.warn(sm.getString("realmBase.gssNameFail"), e); return null; }
// in java/org/apache/catalina/realm/LockOutRealm.java
catch (GSSException e) { log.warn(sm.getString("realmBase.gssNameFail"), e); return null; }
// in java/org/apache/catalina/realm/RealmBase.java
catch (GSSException e) { log.warn(sm.getString("realmBase.gssNameFail"), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "realmBase.delegatedCredentialFail", name), e); } }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail", e)); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (GSSException e) { // Ignore }
0
(Domain) PropertyNotFoundException 6
            
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
12
            
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
(Lib) UnknownHostException 6
            
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (UnknownHostException exc) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Unable to resolve host name:" + value); ok = false; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (UnknownHostException exc) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Unable to resolve host name:" + object); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (UnknownHostException exc) { if (isEcho()) handleErrorOutput("Unable to resolve host name:" + value); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (UnknownHostException e) { args[6] = "-"; args[7] = "-"; }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
catch (UnknownHostException e) { args[6] = "-"; args[7] = "-"; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( UnknownHostException x ) { if (cx == null) cx = new ChannelException("Unable to setup NioSender.", x); cx.addFaultyMember(destination[i], x); }
0
(Lib) PartialResultException 5
            
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; else return (null); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
5
            
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; else return (null); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
(Lib) SAXException 5
            
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXException sx) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), sx); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (SAXException s) { // Hack - makes exception handling simpler throw new IOException(s); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (SAXException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch(SAXException saxe) { // Parse error - assume invalid content resp.sendError(WebdavStatus.SC_UNSUPPORTED_MEDIA_TYPE); return; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (SAXException e) { lockRequestType = LOCK_REFRESH; }
2
            
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXException sx) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), sx); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (SAXException s) { // Hack - makes exception handling simpler throw new IOException(s); }
(Lib) SAXParseException 5
            
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (SAXParseException e) { jspDocParser.err.jspError (new Mark(jspDocParser.ctxt, path, e.getLineNumber(), e.getColumnNumber()), e.getMessage()); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXParseException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (SAXParseException e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); log.error(sm.getString("contextConfig.defaultPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (SAXParseException e) { log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e); log.error(sm.getString("contextConfig.applicationPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; }
// in java/org/apache/catalina/startup/Catalina.java
catch (SAXParseException spe) { log.warn("Catalina.start using " + getConfigFile() + ": " + spe.getMessage()); return; }
1
            
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXParseException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); }
(Lib) URISyntaxException 5
            
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
catch (URISyntaxException e) { // Wrap the exception and re-throw IOException ioe = new IOException(); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (URISyntaxException e) { log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName())); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (URISyntaxException e) { log.error(sm.getString("contextConfig.fileUrl", url), e); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch ( URISyntaxException e ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); }
// in java/org/apache/catalina/core/StandardServer.java
catch (URISyntaxException e) { // Ignore }
2
            
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
catch (URISyntaxException e) { // Wrap the exception and re-throw IOException ioe = new IOException(); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch ( URISyntaxException e ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); }
(Lib) CertificateException 4
            
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (java.security.cert.CertificateException e) { getLog().error(sm.getString("ajpprocessor.certs.fail"), e); return; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (CertificateException ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(CertificateException ce) { throw ce; }
// in java/org/apache/catalina/valves/SSLValve.java
catch (java.security.cert.CertificateException e) { log.warn(sm.getString("sslValve.certError", strcerts), e); }
2
            
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (CertificateException ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(CertificateException ce) { throw ce; }
(Domain) ClientAbortException 4
            
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ClientAbortException e) { throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ClientAbortException e) { throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (ClientAbortException e) { // Ignore }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ClientAbortException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); ioException = e; }
0
(Lib) DOMException 4
            
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
4
            
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
(Lib) IntrospectionException 4
            
// in java/org/apache/jasper/compiler/Generator.java
catch (IntrospectionException ie) { err.jspError(n, "jsp.error.introspect.taghandler", tagHandlerClass.getName(), ie); }
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.beans.IntrospectionException ie) { NamingException ne = new NamingException(ie.getMessage()); ne.setRootCause(ie); throw ne; }
// in java/javax/el/BeanELResolver.java
catch (IntrospectionException e) { // }
// in java/javax/el/BeanELResolver.java
catch (IntrospectionException ie) { throw new ELException(ie); }
2
            
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.beans.IntrospectionException ie) { NamingException ne = new NamingException(ie.getMessage()); ne.setRootCause(ie); throw ne; }
// in java/javax/el/BeanELResolver.java
catch (IntrospectionException ie) { throw new ELException(ie); }
(Domain) LookaheadSuccess 4
            
// in java/org/apache/el/parser/ELParser.java
catch(LookaheadSuccess ls) { return true; }
// in java/org/apache/el/parser/ELParser.java
catch(LookaheadSuccess ls) { return true; }
// in java/org/apache/el/parser/ELParser.java
catch(LookaheadSuccess ls) { return true; }
// in java/org/apache/el/parser/ELParser.java
catch(LookaheadSuccess ls) { }
0
(Lib) SocketTimeoutException 4
            
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (SocketTimeoutException ex) { return 0; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (SocketTimeoutException sx) { // Ignore: Normal condition }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( SocketTimeoutException sx) { //do nothing, we couldn't connect }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (SocketTimeoutException x ) { //do nothing, this is normal, we don't want to block forever //since the receive thread is the same thread //that does membership expiration }
0
(Lib) StringIndexOutOfBoundsException 4
            
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should not occur System.err.println(e); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid signature: " + signature, e); }
// in java/javax/servlet/http/HttpUtils.java
catch (StringIndexOutOfBoundsException e) { String rest = s.substring(i); sb.append(rest); if (rest.length()==2) i++; }
2
            
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid signature: " + signature, e); }
(Lib) EOFException 3
            
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch ( EOFException eof ) { nRead = -1; }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
catch ( EOFException eof ) { nRead = -1; }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
catch (EOFException eof) { nRead = -1; }
0
(Lib) LoginException 3
            
// in java/org/apache/catalina/realm/JAASRealm.java
catch (LoginException e) { log.warn(sm.getString("jaasRealm.loginException", username), e); return (null); }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (LoginException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (LoginException e) { // Ignore }
0
(Lib) NameNotFoundException 3
            
// in java/org/apache/catalina/startup/ContextConfig.java
catch (NameNotFoundException ignore) { // Safe to ignore }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NameNotFoundException e) { return (null); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NameNotFoundException e) { return (null); }
0
(Lib) NoClassDefFoundError 3
            
// in java/org/apache/jasper/JspCompilationContext.java
catch (NoClassDefFoundError e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.error.compiler"), e); } }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (NoClassDefFoundError e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); return null; }
// in java/org/apache/catalina/startup/WebAnnotationSet.java
catch (NoClassDefFoundError e) { // We do nothing }
0
(Lib) NoSuchProviderException 3
            
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (NoSuchProviderException e) { getLog().error(sm.getString("ajpprocessor.certs.fail"), e); return; }
// in java/org/apache/catalina/valves/SSLValve.java
catch (NoSuchProviderException e) { log.error(sm.getString( "sslValve.invalidProvider", providerName), e); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (NoSuchProviderException e) { log.error(sm.getString("sessionIdGenerator.randomProvider", secureRandomProvider), e); }
0
(Lib) OutOfMemoryError 3
            
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; socket.getPoller().cancelledKey(key,SocketStatus.ERROR); releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
0
(Lib) ParserConfigurationException 3
            
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (ParserConfigurationException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), ex); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch(ParserConfigurationException e) { throw new ServletException (sm.getString("webdavservlet.jaxpfailed")); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ParserConfigurationException e) { log.error(sm.getString("jreLeakListener.xmlParseFail"), e); }
2
            
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (ParserConfigurationException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), ex); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch(ParserConfigurationException e) { throw new ServletException (sm.getString("webdavservlet.jaxpfailed")); }
(Lib) SSLException 3
            
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch(SSLException sslex) { log.info(sm.getString("jsseSupport.clientCertError"), sslex); throw sslex; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException e){ throw new SocketException("SSL handshake error" + e.toString()); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException ssle) { // SSL configuration is invalid. Possibly cert doesn't match ciphers IOException ioe = new IOException(sm.getString( "jsse.invalid_ssl_conf", ssle.getMessage())); ioe.initCause(ssle); throw ioe; }
3
            
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch(SSLException sslex) { log.info(sm.getString("jsseSupport.clientCertError"), sslex); throw sslex; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException e){ throw new SocketException("SSL handshake error" + e.toString()); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException ssle) { // SSL configuration is invalid. Possibly cert doesn't match ciphers IOException ioe = new IOException(sm.getString( "jsse.invalid_ssl_conf", ssle.getMessage())); ioe.initCause(ssle); throw ioe; }
(Lib) ArithmeticException 2
            
// in java/org/apache/el/parser/AstInteger.java
catch (ArithmeticException e1) { this.number = new BigInteger(this.image); }
// in java/org/apache/el/parser/AstFloatingPoint.java
catch (ArithmeticException e0) { this.number = new BigDecimal(this.image); }
0
(Lib) ArrayIndexOutOfBoundsException 2
            
// in java/org/apache/jasper/compiler/Node.java
catch (ArrayIndexOutOfBoundsException e) { }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( ArrayIndexOutOfBoundsException ax ) { //we can ignore this, as it means we have an invalid package //but we will log it to debug if ( log.isDebugEnabled() ) log.debug("Invalid member mcast package.",ax); }
0
(Lib) BindException 2
            
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (BindException orig) { String msg; if (getAddress() == null) msg = orig.getMessage() + " <null>:" + getPort(); else msg = orig.getMessage() + " " + getAddress().toString() + ":" + getPort(); BindException be = new BindException(msg); be.initCause(orig); throw be; }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (BindException e) { /* * On some platforms (e.g. Linux) it is not possible to bind * to the multicast address. In this case only bind to the * port. */ log.info("Binding to multicast address, failed. Binding to port only."); socket = new MulticastSocket(port); }
1
            
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (BindException orig) { String msg; if (getAddress() == null) msg = orig.getMessage() + " <null>:" + getPort(); else msg = orig.getMessage() + " " + getAddress().toString() + ":" + getPort(); BindException be = new BindException(msg); be.initCause(orig); throw be; }
(Domain) ClassFormatException 2
            
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) { log.error("Compilation error", exc); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassFormatException e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); }
0
(Lib) ClosedSelectorException 2
            
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (java.nio.channels.ClosedSelectorException cse) { // ignore is normal at shutdown or stop listen socket }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch ( ClosedSelectorException ignore){}
0
(Lib) CommunicationException 2
            
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (CommunicationException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (CommunicationException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); }
0
(Domain) FileUploadIOException 2
            
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); }
2
            
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); }
(Lib) InvalidNameException 2
            
// in java/org/apache/naming/resources/WARDirContext.java
catch (InvalidNameException e) { log.info(sm.getString("resources.invalidName", strName), e); return null; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (InvalidNameException ine) { // Log the problem for posterity containerLog.warn(sm.getString("jndiRealm.exception"), ine); // ignore; this is probably due to a name not fitting // the search path format exactly, as in a fully- // qualified name being munged into a search path // that already contains cn= or vice-versa }
0
(Domain) MethodNotFoundException 2
            
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
4
            
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
(Lib) NotSerializableException 2
            
// in java/org/apache/catalina/session/StandardSession.java
catch (NotSerializableException e) { manager.getContainer().getLogger().warn (sm.getString("standardSession.notSerializable", saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug (" storing attribute '" + saveNames.get(i) + "' with value NOT_SERIALIZED"); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
catch (NotSerializableException e) { log.error(sm.getString("standardSession.notSerializable",saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); log.error(" storing attribute '" + saveNames.get(i)+ "' with value NOT_SERIALIZED"); }
0
(Lib) PatternSyntaxException 2
            
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
catch (PatternSyntaxException pse) { log.error(sm.getString("ReplicationValve.filter.failure", filter), pse); }
// in java/org/apache/catalina/ssi/ExpressionParseTree.java
catch (PatternSyntaxException pse) { ssiMediator.log("Invalid expression: " + expr, pse); return 0; }
0
(Lib) SAXNotRecognizedException 2
            
// in java/org/apache/tomcat/util/digester/XercesParser.java
catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); }
// in java/org/apache/tomcat/util/digester/GenericParser.java
catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); }
0
(Lib) ServiceUnavailableException 2
            
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); }
0
(Lib) SocketException 2
            
// in java/org/apache/coyote/AbstractProtocol.java
catch(java.net.SocketException e) { // SocketExceptions are normal getLog().debug(sm.getString( "ajpprotocol.proto.socketexception.debug"), e); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (SocketException s) { //error here is common if the client has reset the connection if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.err.unexpected"), s); } // Close the socket return false; }
0
(Lib) UnsatisfiedLinkError 2
            
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (UnsatisfiedLinkError e) { throw new Exception(sm.getString("endpoint.init.notavail")); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (UnsatisfiedLinkError e) { // Ignore }
1
            
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (UnsatisfiedLinkError e) { throw new Exception(sm.getString("endpoint.init.notavail")); }
(Lib) UnsupportedOperationException 2
            
// in java/javax/el/MapELResolver.java
catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); }
// in java/javax/el/ListELResolver.java
catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); }
2
            
// in java/javax/el/MapELResolver.java
catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); }
// in java/javax/el/ListELResolver.java
catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); }
(Lib) AbstractMethodError 1
            
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (AbstractMethodError ame) { // Almost certainly a pre Tomcat 7.0.17 compiled JSP using the old // version of the interface. Force a re-compile. return ALWAYS_OUTDATED_DEPENDENCIES; }
0
(Lib) AccountExpiredException 1
            
// in java/org/apache/catalina/realm/JAASRealm.java
catch (AccountExpiredException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.accountExpired", username)); return (null); }
0
(Lib) AuthenticationException 1
            
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (AuthenticationException e) { if (containerLog.isTraceEnabled()) { containerLog.trace(" bind attempt failed"); } }
0
(Lib) BuildException 1
            
// in java/org/apache/jasper/compiler/AntCompiler.java
catch (BuildException e) { be = e; log.error(Localizer.getMessage("jsp.error.javac"), e); log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString()); }
0
(Lib) CRLException 1
            
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(CRLException crle) { throw crle; }
1
            
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(CRLException crle) { throw crle; }
(Lib) ClassFormatError 1
            
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassFormatError e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); return null; }
0
(Lib) ClosedChannelException 1
            
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (ClosedChannelException cx) { cancel(sk,key,ops); }
0
(Lib) ConnectException 1
            
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( ConnectException cx) { //do nothing, we couldn't connect }
0
(Lib) CredentialExpiredException 1
            
// in java/org/apache/catalina/realm/JAASRealm.java
catch (CredentialExpiredException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.credentialExpired", username)); return (null); }
0
(Lib) DataFormatException 1
            
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
catch (DataFormatException e) { throw new IOException(e); }
1
            
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
catch (DataFormatException e) { throw new IOException(e); }
(Domain) EnableDTDValidationException 1
            
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (EnableDTDValidationException e) { saxParser = getSAXParser(true, jspDocParser); jspDocParser.isValidating = true; if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } inStream = JspUtil.getInputStream(path, jarFile, jspDocParser.ctxt); saxParser.parse(new InputSource(inStream), jspDocParser); }
0
(Lib) FailedLoginException 1
            
// in java/org/apache/catalina/realm/JAASRealm.java
catch (FailedLoginException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.failedLogin", username)); return (null); }
0
(Domain) FileUploadException 1
            
// in java/org/apache/catalina/connector/Request.java
catch (FileUploadException e) { partsParseException = new IOException(e); }
0
(Lib) IllegalThreadStateException 1
            
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IllegalThreadStateException e) { try { Thread.sleep(500); } catch (InterruptedException ignored) { // Ignore } }
0
(Lib) IndexOutOfBoundsException 1
            
// in java/javax/el/ListELResolver.java
catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); }
1
            
// in java/javax/el/ListELResolver.java
catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); }
(Lib) InvalidAttributeValueException 1
            
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvalidAttributeValueException e) { throw new MBeanException(e); }
1
            
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvalidAttributeValueException e) { throw new MBeanException(e); }
(Domain) InvalidContentTypeException 1
            
// in java/org/apache/catalina/connector/Request.java
catch (InvalidContentTypeException e) { partsParseException = new ServletException(e); }
0
(Lib) JMRuntimeException 1
            
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (JMRuntimeException rme) { Throwable cause = rme.getCause(); if (cause instanceof UnsupportedOperationException) { if (log.isDebugEnabled()) { log.debug("Error getting attribute " + oname + " " + attName, rme); } } else if (cause instanceof NullPointerException) { if (log.isDebugEnabled()) { log.debug("Error getting attribute " + oname + " " + attName, rme); } } else { log.error("Error getting attribute " + oname + " " + attName, rme); } continue; }
0
(Lib) KeyManagementException 1
            
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (KeyManagementException e) { // Assume no RFC 5746 support }
0
(Lib) MBeanRegistrationException 1
            
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (MBeanRegistrationException e) { log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", on), e); }
0
(Lib) MalformedInputException 1
            
// in java/org/apache/catalina/websocket/StreamInbound.java
catch (MalformedInputException mie) { // Invalid UTF-8 closeOutboundConnection(Constants.STATUS_BAD_DATA, null); return SocketState.CLOSED; }
0
(Domain) MalformedStreamException 1
            
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (MalformedStreamException e) { return false; }
0
(Lib) NameAlreadyBoundException 1
            
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NameAlreadyBoundException e) { // Ignore because UserTransaction was obviously // added via ResourceLink }
0
(Lib) OperationNotSupportedException 1
            
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
catch( OperationNotSupportedException ex) { log.error("Operation not supported " + ex); }
0
(Domain) PropertyNotWritableException 1
            
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); }
2
            
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); }
(Lib) RemoteException 1
            
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (RemoteException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.createRegistryFailed", serverName, Integer.toString(theRmiRegistryPort)), e); return null; }
0
(Domain) RemoteProcessException 1
            
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( RemoteProcessException e ) { if ( log.isDebugEnabled() ) log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); }
0
(Domain) SSIStopProcessingException 1
            
// in java/org/apache/catalina/ssi/SSIProcessor.java
catch (SSIStopProcessingException e) { //If we are here, then we have already stopped processing, so all // is good }
0
(Domain) SizeException 1
            
// in java/org/apache/catalina/connector/Request.java
catch (FileUploadBase.SizeException e) { checkSwallowInput(); partsParseException = new IllegalStateException(e); }
0
(Lib) TransformerException 1
            
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (TransformerException e) { throw new ServletException("XSL transformer error", e); }
1
            
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (TransformerException e) { throw new ServletException("XSL transformer error", e); }
(Lib) UnmappableCharacterException 1
            
// in java/org/apache/catalina/websocket/StreamInbound.java
catch (UnmappableCharacterException uce) { // Invalid UTF-8 closeOutboundConnection(Constants.STATUS_BAD_DATA, null); return SocketState.CLOSED; }
0
(Lib) UnsupportedCallbackException 1
            
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (UnsupportedCallbackException e) { throw new LoginException(e.toString()); }
1
            
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (UnsupportedCallbackException e) { throw new LoginException(e.toString()); }
(Lib) UnsupportedClassVersionError 1
            
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); }
1
            
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); }
(Lib) ZipException 1
            
// in java/org/apache/naming/resources/WARDirContext.java
catch (ZipException e) { throw new IOException(e.getMessage(), e); }
1
            
// in java/org/apache/naming/resources/WARDirContext.java
catch (ZipException e) { throw new IOException(e.getMessage(), e); }

Exception Recast Summary

There is a common practice of throwing exceptions from within a catch block (e.g. for wrapping a low-level exception). The following table summarizes the usage of this practice in the application. The last column gives the number of times it happens for a pair of exceptions. The graph below the table graphically renders the same information. For a given node, its color represents its origin (blue means library exception, orange means domain exception); the left-most number is the number of times it is thrown, the right-most is the number of times it is caught.

Catch Throw
(Lib) IllegalStateException
Unknown
6
                    
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IllegalStateException e) { throw e; }
(Lib) IOException
(Domain) JasperException
(Domain) ServletException
(Lib) RuntimeException
(Lib) IllegalStateException
(Lib) BuildException
(Domain) MalformedStreamException
(Domain) IOFileUploadException
(Domain) FileUploadException
(Domain) ClassFormatException
(Lib) IllegalArgumentException
(Lib) LoginException
(Domain) ChannelException
(Domain) ClientAbortException
(Lib) SecurityException
(Domain) Error
(Domain) ELException
Unknown
3
                    
// in java/org/apache/jasper/compiler/TagFileProcessor.java
catch (IOException ioe) { throw new JasperException(ioe); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (IOException io) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), io); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { throw new JasperException(ioe); }
1
                    
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IOException e) { throw new ServletException("Could not precompile jsp: " + jspFile, e); }
8
                    
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
catch ( IOException x ) { throw new RuntimeException("Unable to open NIO selector.",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( IOException x ) { throw new RuntimeException(x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { throw new RuntimeException(x); }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
catch ( IOException x ) { throw new RuntimeException("Unable to parse hostname.",x); }
// in java/org/apache/catalina/tribes/membership/StaticMember.java
catch (IOException x) { throw new RuntimeException(x);}
1
                    
// in java/org/apache/coyote/http11/filters/BufferedInputFilter.java
catch(IOException ioe) { // No need for i18n - this isn't going to get logged anywhere throw new IllegalStateException( "Request body too large for buffer"); }
4
                    
// in java/org/apache/tomcat/buildutil/CheckEol.java
catch (IOException e) { throw new BuildException("Could not check file '" + file.getAbsolutePath() + "'", e); }
// in java/org/apache/tomcat/buildutil/Txt2Html.java
catch( IOException e ) { throw new BuildException( "Could not convert '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath() + "'", e ); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (IOException e) { throw new BuildException(e); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (IOException e) { throw new BuildException(e); }
2
                    
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); }
1
                    
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); }
1
                    
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new FileUploadException(e.getMessage(), e); }
1
                    
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (IOException e) { System.out.println(buf.toString()); e.printStackTrace(); throw new ClassFormatException("Byte code error: " + e, e); }
4
                    
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { throw new IllegalArgumentException( sm.getString("webappClassLoader.validationErrorJarPath", jarEntry2.getName()), ioe); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( IOException x ) { throw new IllegalArgumentException(x); }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { throw new IllegalArgumentException(cc.toString(), e); }
// in java/javax/servlet/http/HttpUtils.java
catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); }
1
                    
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (IOException e) { throw new LoginException(e.toString()); }
1
                    
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
catch ( IOException x ) { log.error("Unable to compress byte contents"); throw new ChannelException(x); }
1
                    
// in java/org/apache/catalina/connector/OutputBuffer.java
catch (IOException e) { // An IOException on a write is almost always due to // the remote client aborting the request. Wrap this // so that it can be handled better by the error dispatcher. throw new ClientAbortException(e); }
1
                    
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { throw new SecurityException(sm.getString( "coyoteRequest.sendfileNotCanonical", value), e); }
1
                    
// in java/javax/servlet/jsp/tagext/BodyContent.java
catch (IOException ex) { // TODO -- clean this one up. throw new Error("internal error!;"); }
2
                    
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { throw new ELException("Failed to read " + SERVICE_RESOURCE_NAME, e); }
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { throw new ELException("Failed to read " + PROPERTY_FILE, e); }
48
                    
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer.getMessage("jsp.error.flush"), ex); throw ise; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer .getMessage("jsp.error.attempt_to_clear_flushed_buffer")); ise.initCause(ex); throw ise; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IOException e) { throw e; }
// in java/org/apache/jasper/JspC.java
catch (IOException ex) { fis.close(); throw ex; }
// in java/org/apache/jasper/JspC.java
catch (IOException ex) { fos.close(); throw ex; }
// in java/org/apache/naming/resources/FileDirContext.java
catch (IOException e) { NamingException ne = new NamingException (sm.getString("resources.bindFailed", e)); ne.initCause(e); throw ne; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (IOException e) { apr.reset(); throw e; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (IOException e) { throw e; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException e) { throw e; }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (IOException ex) { ex.printStackTrace(); throw ex; }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
catch (IOException x) { throw x; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw ioe; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (IOException ioe) { countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw ioe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { Throwable cause = ioe.getCause(); if (cause instanceof UnrecoverableKeyException) { // Log a warning we had a password issue log.warn(sm.getString("jsse.invalid_truststore_password"), cause); // Re-try trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, null); } else { // Something else went wrong - re-throw throw ioe; } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { // May be expected when working with a trust store // Re-throw. Caller will catch and log as required throw ioe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(IOException iex) { throw iex; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
catch( IOException ex) { if(log.isDebugEnabled()) { log.debug("B2CConverter: Reseting the converter " + ex.toString()); } reset(); throw ex; }
// in java/org/apache/el/parser/SimpleCharStream.java
catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { throw e; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { throw e; }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
catch (IOException e) { if (writer != null) { writer.close(); } fileNew.delete(); throw e; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { if (war.exists() && !war.delete()) { writer.println( smClient.getString("managerServlet.deleteFail", war)); } throw e; }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind server socket to:" + addr + " throwing error."); throw x; } port++; }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (IOException iox) { log.error("Unable to join multicast group, make sure your system has multicasting enabled."); throw iox; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { error = true; log.error(sm.getString("standardManager.unloading.ioe", e), e); throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.unloading.ioe", e), e); try { oos.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException e) { if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException e) { if (fos != null) { try { fos.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error(sm.getString ("persistentManager.serializeError", session.getIdInternal(), e)); throw e; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException e){ log ("Caught exception " + e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.loading.ioe", e), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.unloading.ioe", e), e); throw e; }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; }
(Domain) FileUploadIOException
Unknown
2
                    
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); }
(Lib) NullPointerException
(Lib) MBeanException
Unknown
1
                    
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (NullPointerException e) { throw new MBeanException(e); }
2
                    
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch ( NullPointerException x ) { //sun bug 5076772 on windows JDK 1.5 if (selector==null) throw x; if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( NullPointerException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; }
(Lib) IndexOutOfBoundsException
(Domain) PropertyNotFoundException
1
                    
// in java/javax/el/ListELResolver.java
catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); }
(Lib) Exception
(Domain) JspException
(Domain) JasperException
(Lib) SAXException
(Lib) ServiceException
(Lib) NamingException
(Lib) IllegalArgumentException
(Lib) IOException
(Lib) MalformedURLException
(Lib) ClassNotFoundException
(Lib) MBeanException
(Domain) ELException
(Domain) LifecycleException
(Lib) BuildException
(Domain) ServletException
(Domain) ChannelException
(Domain) RemoteProcessException
(Lib) Exception
(Lib) RuntimeException
Unknown
1
                    
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JspException(e.getMessage(), t); }
25
                    
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException ("error in invoking method", ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage( "jsp.error.internal.tldinit", ex.getMessage()), ex); }
// in java/org/apache/jasper/compiler/TagPluginManager.java
catch (Exception e) { throw new JasperException(e); }
// in java/org/apache/jasper/compiler/JspConfig.java
catch (Exception ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JasperException(t); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); }
// in java/org/apache/jasper/JspC.java
catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); }
3
                    
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { throw new SAXException( Localizer.getMessage("jsp.error.loadclass.taghandler", handlerClassName, qName), e); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { throw new SAXException(e); }
// in java/org/apache/catalina/util/SchemaResolver.java
catch (Exception e) { throw new SAXException(e); }
1
                    
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
catch (Exception e) { throw new ServiceException(e); }
1
                    
// in java/org/apache/naming/NamingContext.java
catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); }
2
                    
// in java/org/apache/naming/resources/WARDirContext.java
catch (Exception e) { throw new IllegalArgumentException (sm.getString("warResources.invalidWar", e.getMessage())); }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (Exception e) { throw new IllegalArgumentException(sm.getString( "resources.invalidCache", cacheClassName), e); }
20
                    
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception e) { if( e instanceof IOException ) throw (IOException)e; throw new IOException(e.getMessage(), e); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/core/ApplicationPart.java
catch (Exception e) { throw new IOException(e); }
1
                    
// in java/org/apache/tomcat/util/net/URL.java
catch (Exception e) { throw new MalformedURLException(e.toString()); }
2
                    
// in java/org/apache/tomcat/util/net/SSLImplementation.java
catch (Exception e) { if (logger.isDebugEnabled()) logger .debug("Error loading SSL Implementation " + className, e); throw new ClassNotFoundException( "Error loading SSL Implementation " + className + " :" + e.toString()); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); }
4
                    
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (Exception e) { throw new MBeanException (e, "Cannot instantiate ModelMBean of class " + getClassName()); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
3
                    
// in java/org/apache/el/lang/ExpressionBuilder.java
catch (Exception e) { throw new ELException( MessageFactory.get("error.parseFail", expr), e); }
// in java/javax/el/BeanELResolver.java
catch (Exception e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (Exception e) { throw new ELException(e); }
9
                    
// in java/org/apache/catalina/realm/MemoryRealm.java
catch (Exception e) { throw new LifecycleException (sm.getString("memoryRealm.readXml"), e); }
// in java/org/apache/catalina/ha/context/ReplicatedContext.java
catch ( Exception x ) { log.error("Unable to start ReplicatedContext",x); throw new LifecycleException("Failed to start ReplicatedContext",x); }
// in java/org/apache/catalina/ha/session/BackupManager.java
catch ( Exception x ) { log.error(sm.getString("backupManager.startUnable", getName()),x); throw new LifecycleException(sm.getString("backupManager.startFailed", getName()),x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to start cluster.", x); throw new LifecycleException(x); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerInitializationFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { String errPrefix = ""; if(this.service != null) { errPrefix += "service.getName(): \"" + this.service.getName() + "\"; "; } throw new LifecycleException (errPrefix + " " + sm.getString ("coyoteConnector.protocolHandlerStartFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerStopFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerDestroyFailed"), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { String message = sm.getString( "standardService.connector.initFailed", connector); log.error(message, e); if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) throw new LifecycleException(message); }
3
                    
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/ValidatorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException("Validation failure", e); } else { handleErrorOutput("Validation failure: " + e); } }
1
                    
// in java/org/apache/catalina/manager/StatusManagerServlet.java
catch (Exception e) { throw new ServletException(e); }
6
                    
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { if ( x instanceof ChannelException ) throw (ChannelException)x; throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch (Exception x) { throw new ChannelException("Unable to add MessageDispatchInterceptor to interceptor chain.",x); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( Exception x ) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( Exception x ) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x ) { try { this.disconnect(); } catch (Exception e) {/*Ignore*/} if ( x instanceof ChannelException ) throw (ChannelException)x; else throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch (Exception x) { throw new ChannelException(x); }
1
                    
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { //this could be the channel listener throwing an exception, we should log it //as a warning. if ( log.isWarnEnabled() ) log.warn("Error receiving message:",x); throw new RemoteProcessException("Exception:"+x.getMessage(),x); }
1
                    
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (Exception e) { throw new Exception("bad ProxyList"); }
2
                    
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (Exception x) { //log.error("Async.dispatch",x); throw new RuntimeException(x); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; }
51
                    
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (writer != null) { try { writer.close(); writer = null; } catch (Exception e1) { // do nothing } } // Remove the generated .java file File file = new File(javaFileName); if (file.exists()) { if (!file.delete()) { log.warn(Localizer.getMessage( "jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath())); } } throw e; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (Exception ex) { JasperException je = new JasperException( Localizer.getMessage("jsp.error.unable.compile"), ex); // Cache compilation exception jsw.setCompilationException(je); throw je; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { if (e instanceof InvocationTargetException) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } } NamingException ex = new NamingException ("Error while reading Wsdl File"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
catch (Exception x) { if (x instanceof InvocationTargetException) { Throwable cause = x.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } if (cause instanceof Exception) { x = (Exception) cause; } } if (x instanceof NamingException) throw (NamingException)x; else { NamingException nx = new NamingException(x.getMessage()); nx.initCause(x); throw nx; } }
// in java/org/apache/naming/factory/ResourceFactory.java
catch (Exception e) { if (e instanceof NamingException) throw (NamingException) e; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (Exception e) { NamingException ne = new NamingException(e.getMessage()); ne.initCause(e); throw ne; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.initError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.startError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.pauseError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.resumeError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.stopError", getName()), ex); throw ex; }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
catch (Exception cx) { IOException x = new IOException(cx); throw x; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw e; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception e) { if( e instanceof IOException ) throw (IOException)e; throw new IOException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsSerSource.java
catch( Exception ex ) { log.error( "Error reading descriptors " + source + " " + ex.toString(), ex); throw ex; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java
catch (Exception e) { log.error("Error digesting Registry data", e); throw e; }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Exception t ) { if( failFirst ) throw t; log.info("Error initializing " + current + " " + t.toString()); }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Exception ex) { log.error("Error registering " + oname, ex ); throw ex; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Finish event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Body event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("End event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Begin event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { throw createSAXException(e); }
// in java/org/apache/el/lang/ExpressionBuilder.java
catch (Exception e) { if (e instanceof ELException) { throw (ELException) e; } else { throw (new ELException(e)); } }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating group [" + groupname + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating role [" + rolename + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating user [" + username + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying group [" + groupname + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying role [" + rolename + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying user [" + username + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { if ( x instanceof ChannelException ) throw (ChannelException)x; throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch ( Exception x ) { if ( doListen() ) throw x; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x ) { try { this.disconnect(); } catch (Exception e) {/*Ignore*/} if ( x instanceof ChannelException ) throw (ChannelException)x; else throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
(Domain) JasperException
(Lib) RuntimeException
(Lib) IOException
(Lib) SAXParseException
Unknown
1
                    
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
catch (JasperException je) { throw new RuntimeException(je.toString(), je); }
1
                    
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (JasperException e) { // Hack - makes exception handling simpler throw new IOException(e); }
1
                    
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (JasperException je) { throw new SAXParseException( Localizer.getMessage("jsp.error.could.not.add.taglibraries"), locator, je); }
3
                    
// in java/org/apache/jasper/JspCompilationContext.java
catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { rootCause.printStackTrace(); } throw je; }
(Domain) Error
Unknown
4
                    
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Finish event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Body event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("End event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Begin event threw error", e); throw e; }
(Domain) ParseException
(Domain) ELException
(Domain) SSIStopProcessingException
1
                    
// in java/org/apache/el/parser/ELParser.java
catch (ParseException pe) { throw new ELException(pe.getMessage());
1
                    
// in java/org/apache/catalina/ssi/SSIConditional.java
catch (ParseException e) { //throw new SsiCommandException( "Error parsing expression." ); throw new SSIStopProcessingException(); }
(Domain) ChannelException
(Lib) RuntimeException
Unknown
1
                    
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.warn("Unable to send map start message."); // remove listener from channel this.rpcChannel.breakdown(); this.channel.removeChannelListener(this); this.channel.removeMembershipListener(this); throw new RuntimeException("Unable to start replicated map.",x); }
5
                    
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( ChannelException cx ) { throw cx; }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( ChannelException cx ) { FaultyMember[] mbrs = cx.getFaultyMembers(); for ( int i=0; i<mbrs.length; i++ ) { if ( mbrs[i].getCause()!=null && (!(mbrs[i].getCause() instanceof RemoteProcessException)) ) {//RemoteProcessException's are ok this.memberDisappeared(mbrs[i].getMember()); }//end if }//for throw cx; }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.warn("Unable to send election message to:"+msg.getMembers()[current]); current = Arrays.nextIndex(msg.getMembers()[current],msg.getMembers()); if ( current == next ) throw x; }
// in java/org/apache/catalina/tribes/group/interceptors/ThroughputInterceptor.java
catch ( ChannelException x ) { msgTxErr.addAndGet(1); if ( access.get() == 1 ) access.addAndGet(-1); throw x; }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
catch (ChannelException x) { sender.disconnect(); throw x; }
(Domain) LifecycleException
(Domain) Error
(Lib) MBeanException
(Lib) IllegalStateException
1
                    
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) { throw new java.lang.Error(e); } else { log.error("Catalina.start", e); } }
1
                    
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (LifecycleException e){ throw new MBeanException(e); }
1
                    
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.addChild: start: ", e); throw new IllegalStateException ("ContainerBase.addChild: start: " + e); }
(Domain) UnavailableException
Unknown
2
                    
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (UnavailableException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); unavailable(f); throw f; }
(Domain) ServletException
(Lib) IOException
(Lib) IllegalArgumentException
Unknown
1
                    
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
catch (ServletException e) { throw new IOException("Couldn't include file: " + originalPath + " because of ServletException: " + e.getMessage()); }
1
                    
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ServletException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.init", listenerClass.getName()), e); }
12
                    
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (ServletException e) { throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { throw e; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { throw e; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw f; }
(Lib) PrivilegedActionException
(Lib) RuntimeException
(Domain) ELException
(Domain) ServletException
Unknown
8
                    
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage() ,e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); }
1
                    
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } }
4
                    
// in java/org/apache/jasper/servlet/JspServlet.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ServletException) throw (ServletException)t; throw new ServletException("Could not precompile jsp: " + jspFile, e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/security/SecurityUtil.java
catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
39
                    
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); throw (JasperException)e; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ServletException) throw (ServletException)t; throw new ServletException("Could not precompile jsp: " + jspFile, e); }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof ClassNotFoundException){ throw (ClassNotFoundException)exception; } else if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in load() " + exception); }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in unLoad() " + exception); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (PrivilegedActionException ex) { Exception e = ex.getException(); log.error(sm.getString( "persistentManager.swapInException", id), e); if (e instanceof IOException){ throw (IOException)e; } else if (e instanceof ClassNotFoundException) { throw (ClassNotFoundException)e; } }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException) { throw (IOException) exception; } log.error("Exception in the Store during writeSession: " + exception, exception); }
// in java/org/apache/catalina/connector/OutputBuffer.java
catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } }
// in java/org/apache/catalina/connector/Response.java
catch (PrivilegedActionException pae){ IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(pae.getException()); throw iae; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage() ,e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/InputBuffer.java
catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } }
// in java/org/apache/catalina/connector/ResponseFacade.java
catch(PrivilegedActionException e){ Exception ex = e.getException(); if (ex instanceof IOException){ throw (IOException)ex; } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; }
// in java/org/apache/catalina/security/SecurityUtil.java
catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
(Lib) RuntimeException
(Domain) DecodeException
(Domain) ServletException
Unknown
1
                    
// in java/org/apache/tomcat/util/buf/UDecoder.java
catch (RuntimeException ex) { throw new DecodeException(ex.getMessage()); }
2
                    
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (RuntimeException e) { throw new ServletException(sm.getString( "expiresFilter.exceptionProcessingParameter", name, value), e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); }
10
                    
// in java/org/apache/jasper/servlet/JspServlet.java
catch (RuntimeException e) { throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); }
(Domain) PropertyNotFoundException
(Domain) JspPropertyNotFoundException
Unknown
6
                    
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
6
                    
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
(Domain) PropertyNotWritableException
(Domain) JspPropertyNotWritableException
Unknown
1
                    
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); }
1
                    
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); }
(Domain) MethodNotFoundException
(Domain) JspMethodNotFoundException
Unknown
2
                    
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
2
                    
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
(Domain) ELException
(Domain) ELException
(Lib) ELParseException
(Domain) JspELException
Unknown
3
                    
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/el/parser/AstFunction.java
catch (ELException ele) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), ele); }
1
                    
// in java/org/apache/jasper/el/ExpressionEvaluatorImpl.java
catch (javax.el.ELException e) { throw new ELParseException(e.getMessage()); }
6
                    
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
6
                    
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
(Lib) NoSuchMethodException
(Lib) RuntimeException
(Domain) MethodNotFoundException
2
                    
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
1
                    
// in java/javax/el/BeanELResolver.java
catch (NoSuchMethodException e) { throw new MethodNotFoundException(e); }
(Lib) IllegalArgumentException
(Domain) JasperException
(Domain) ELException
(Lib) ClassNotFoundException
Unknown
1
                    
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
4
                    
// in java/org/apache/el/lang/ELSupport.java
catch (IllegalArgumentException iae) { throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/parser/AstValue.java
catch (IllegalArgumentException iae) { throw new ELException(iae); }
// in java/javax/el/ExpressionFactory.java
catch (IllegalArgumentException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalArgumentException e) { throw new ELException(e); }
2
                    
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); }
1
                    
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalArgumentException biae) { //the boolean method had the wrong //parameter types. lets try the other if (setPropertyMethodVoid!=null) { setPropertyMethodVoid.invoke(o, params); return true; }else { throw biae; } }
(Lib) UnsupportedEncodingException
(Lib) RuntimeException
(Lib) IllegalArgumentException
(Lib) BuildException
4
                    
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/el/parser/ELParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/el/parser/ELParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
4
                    
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/javax/servlet/http/HttpUtils.java
catch (java.io.UnsupportedEncodingException e) { // XXX function should accept an encoding parameter & throw this // exception. Otherwise throw something expected. throw new IllegalArgumentException(e.getMessage(), e); }
7
                    
// in java/org/apache/catalina/ant/JMXSetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/ResourcesTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JMXGetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/AbstractCatalinaCommandTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JKStatusUpdateTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JMXQueryTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
(Lib) Throwable
(Domain) ServletException
(Lib) IOException
(Domain) Error
(Domain) LifecycleException
(Lib) SQLException
(Lib) RuntimeException
(Lib) IllegalArgumentException
Unknown
11
                    
// in java/org/apache/jasper/servlet/JspServlet.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
3
                    
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable e) { apr.reset(); e.printStackTrace(); throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable t) { throw new IOException(t); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable t) { throw new IOException(t); }
2
                    
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
// in java/org/apache/el/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
6
                    
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error( "LifecycleException ", t ); throw new LifecycleException("start: ", t); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOn.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new LifecycleException( "ClusterSingleSignOn exception during clusterLoad " + t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.startFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.stopFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); }
2
                    
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
2
                    
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch(Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage(), t); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); }
1
                    
// in java/org/apache/catalina/util/CharsetMapper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new IllegalArgumentException(t.toString()); }
99
                    
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
catch (Throwable t) { if (t instanceof InvocationTargetException && t.getCause() != null) { throw t.getCause(); } else { throw t; } }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(Throwable t) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(Throwable t) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/tomcat/jni/Library.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } String name = System.mapLibraryName(NAMES[i]); String path = System.getProperty("java.library.path"); String sep = System.getProperty("path.separator"); String [] paths = path.split(sep); for (int j=0; j<paths.length; j++) { java.io.File fd = new java.io.File(paths[j] , name); if (fd.exists()) { t.printStackTrace(); } } if ( i > 0) err.append(", "); err.append(t.getMessage()); }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte004) { if (jjtc004) { jjtree.clearNodeScope(jjtn004); jjtc004 = false; } else { jjtree.popNode(); } if (jjte004 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte004;} } if (jjte004 instanceof ParseException) { {if (true) throw (ParseException)jjte004;} } {if (true) throw (Error)jjte004;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } log.error("Unable to process request in NioReceiver", t); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } log.error("Unable to receive broadcast message.",t); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch(Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof MalformedURLException){ throw (MalformedURLException)t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
(Lib) FileNotFoundException
(Domain) JasperException
(Lib) SAXParseException
Unknown
2
                    
// in java/org/apache/jasper/compiler/ParserController.java
catch (FileNotFoundException ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (FileNotFoundException ex) { throw new JasperException(ex); }
1
                    
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (FileNotFoundException fnfe) { throw new SAXParseException( Localizer.getMessage("jsp.error.file.not.found", fname), locator, fnfe); }
3
                    
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (FileNotFoundException fnfe) { // Re-throw to let caller handle this - will result in a 404 throw fnfe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (FileNotFoundException fnfe) { log.error(sm.getString("jsse.keystore_load_failed", type, path, fnfe.getMessage()), fnfe); throw fnfe; }
(Lib) NumberFormatException
(Lib) MalformedURLException
(Domain) ELException
(Lib) RuntimeException
(Lib) IllegalStateException
(Lib) NumberFormatException
(Lib) IllegalArgumentException
1
                    
// in java/org/apache/tomcat/util/net/URL.java
catch (NumberFormatException e) { throw new MalformedURLException(e.toString()); }
8
                    
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
1
                    
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { throw new RuntimeException("Exception parsing number '" + i + "' (zero based) of comma delimited list '" + commaDelimitedInts + "'"); }
1
                    
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { throw new IllegalStateException(sm.getString( "Invalid duration (number) '{}' in directive '{}'", currentToken, line)); }
2
                    
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTP_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTPS_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
1
                    
// in java/javax/servlet/http/HttpUtils.java
catch (NumberFormatException e) { // XXX // need to be more specific about illegal arg throw new IllegalArgumentException(); }
(Lib) ClassNotFoundException
(Domain) JasperException
(Lib) IllegalStateException
(Lib) ReflectionException
(Lib) IOException
(Domain) LifecycleException
(Lib) MBeanException
(Domain) ServletException
(Lib) IllegalArgumentException
(Domain) ELException
Unknown
3
                    
// in java/org/apache/jasper/compiler/BeanRepository.java
catch (ClassNotFoundException ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
catch (ClassNotFoundException e) { throw new JasperException(e); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (ClassNotFoundException cex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.load"), cex); }
2
                    
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch (ClassNotFoundException ex) { throw new IllegalStateException(ex); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (ClassNotFoundException e) { String msg = sm.getString( "persistentManager.deserializeError", id); log.error(msg, e); throw new IllegalStateException(msg, e); }
1
                    
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (ClassNotFoundException e) { throw new ReflectionException (e, "Cannot find Class for " + signature); }
1
                    
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassNotFoundException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
1
                    
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassNotFoundException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassNotFoundException", className), e); }
4
                    
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
3
                    
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
2
                    
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException(cnfe.getMessage()); }
1
                    
// in java/javax/el/ExpressionFactory.java
catch (ClassNotFoundException e) { throw new ELException( "Unable to find ExpressionFactory of type: " + className, e); }
17
                    
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load service Interface"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(ClassNotFoundException cnfe) { if (!hasExternalRepositories || searchExternalFirst) { throw cnfe; } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { if (log.isTraceEnabled()) log.trace(" --> Passing on ClassNotFoundException"); throw e; }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (ClassNotFoundException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/session/StandardManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/ha/session/SerializablePrincipal.java
catch (ClassNotFoundException e) { log.error(sm.getString( "serializablePrincipal.readPrincipal.cnfe"), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("deltaManager.loading.cnfe", e), e); throw e; }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (ClassNotFoundException e) { ServletException se = new ServletException(e); throw se; }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (ClassNotFoundException e) { try { // Try also the superclass because of primitive types return super.resolveClass(classDesc); } catch (ClassNotFoundException e2) { // Rethrow original exception, as it can have more information // about why the class was not found. BZ 48007 throw e; } }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (ClassNotFoundException e2) { // Rethrow original exception, as it can have more information // about why the class was not found. BZ 48007 throw e; }
(Lib) MalformedURLException
(Lib) RuntimeException
(Domain) ServletException
(Lib) IllegalStateException
Unknown
1
                    
// in java/org/apache/jasper/compiler/JarURLResource.java
catch (MalformedURLException e) { throw new RuntimeException("", e); }
1
                    
// in java/org/apache/jasper/servlet/JspServlet.java
catch (MalformedURLException e) { throw new ServletException("Can not locate jsp file", e); }
1
                    
// in java/org/apache/jasper/JspCompilationContext.java
catch (MalformedURLException e) { throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"), e); }
2
                    
// in java/org/apache/tomcat/util/net/URL.java
catch (MalformedURLException e) { throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { IllegalArgumentException iae = new IllegalArgumentException ("Invalid repository: " + repository); iae.initCause(e); throw iae; }
(Lib) IntrospectionException
(Domain) ELException
Unknown
1
                    
// in java/javax/el/BeanELResolver.java
catch (IntrospectionException ie) { throw new ELException(ie); }
1
                    
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.beans.IntrospectionException ie) { NamingException ne = new NamingException(ie.getMessage()); ne.setRootCause(ie); throw ne; }
(Lib) SAXParseException
(Domain) JasperException
1
                    
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXParseException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); }
(Lib) SAXException
(Domain) JasperException
(Lib) IOException
1
                    
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXException sx) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), sx); }
1
                    
// in java/org/apache/catalina/startup/TldConfig.java
catch (SAXException s) { // Hack - makes exception handling simpler throw new IOException(s); }
(Lib) SecurityException
(Lib) ClassNotFoundException
(Domain) ELException
2
                    
// in java/org/apache/jasper/servlet/JasperLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; se.printStackTrace(); throw new ClassNotFoundException(error); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); }
1
                    
// in java/javax/el/ExpressionFactory.java
catch (SecurityException se) { throw new ELException(se); }
(Lib) InstantiationException
(Lib) IOException
(Domain) ServletException
(Domain) LifecycleException
(Lib) MBeanException
(Lib) IllegalArgumentException
(Domain) ELException
Unknown
1
                    
// in java/org/apache/catalina/startup/ContextConfig.java
catch (InstantiationException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
4
                    
// in java/org/apache/catalina/startup/Tomcat.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
1
                    
// in java/org/apache/catalina/realm/RealmBase.java
catch (InstantiationException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.InstantiationException", className), e); }
4
                    
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
1
                    
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
1
                    
// in java/javax/el/ExpressionFactory.java
catch (InstantiationException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
3
                    
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.InstantiationException ie2) { NamingException ne = new NamingException(ie2.getMessage()); ne.setRootCause(ie2); throw ne; }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (InstantiationException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (InstantiationException e) { ServletException se = new ServletException(e); throw se; }
(Lib) IllegalAccessException
(Domain) ELException
(Lib) IOException
(Domain) ServletException
(Domain) LifecycleException
(Lib) MBeanException
(Lib) IllegalArgumentException
Unknown
6
                    
// in java/org/apache/el/parser/AstFunction.java
catch (IllegalAccessException iae) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), iae); }
// in java/org/apache/el/parser/AstValue.java
catch (IllegalAccessException iae) { throw new ELException(iae); }
// in java/javax/el/ExpressionFactory.java
catch (IllegalAccessException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
1
                    
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IllegalAccessException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
4
                    
// in java/org/apache/catalina/startup/Tomcat.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
1
                    
// in java/org/apache/catalina/realm/RealmBase.java
catch (IllegalAccessException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.IllegalAccessException", className), e); }
4
                    
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
1
                    
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
3
                    
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.IllegalAccessException iae) { NamingException ne = new NamingException(iae.getMessage()); ne.setRootCause(iae); throw ne; }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (IllegalAccessException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IllegalAccessException e) { ServletException se = new ServletException(e); throw se; }
(Lib) ParserConfigurationException
(Domain) JasperException
(Domain) ServletException
1
                    
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (ParserConfigurationException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), ex); }
1
                    
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch(ParserConfigurationException e) { throw new ServletException (sm.getString("webdavservlet.jaxpfailed")); }
(Lib) NamingException
(Lib) RuntimeException
(Lib) FileNotFoundException
(Domain) LifecycleException
(Domain) ServletException
(Lib) IllegalArgumentException
Unknown
1
                    
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (NamingException e) { throw new RuntimeException(e.getMessage(), e); }
1
                    
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException e) { // Unexpected exception throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); }
1
                    
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { throw new LifecycleException(sm.getString("jndiRealm.open"), e); }
6
                    
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Failed throw new ServletException("No resources", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
1
                    
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
5
                    
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (NamingException e) { throw e; }
// in java/org/apache/naming/NamingContext.java
catch (NamingException e) { throw e; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", libPath)); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", filename)); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (NamingException e) { ServletException se = new ServletException(e); throw se; }
(Lib) InvocationTargetException
(Lib) RuntimeOperationsException
(Lib) RuntimeErrorException
(Lib) MBeanException
(Domain) ELException
(Domain) ServletException
(Lib) IllegalArgumentException
Unknown
3
                    
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
3
                    
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
3
                    
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
6
                    
// in java/org/apache/el/parser/AstFunction.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(MessageFactory.get("error.function", this .getOutputName()), cause); }
// in java/org/apache/el/parser/AstValue.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
// in java/javax/el/ExpressionFactory.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
3
                    
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
1
                    
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
19
                    
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.reflect.InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } NamingException ne = new NamingException(ite.getMessage()); ne.setRootCause(ite); throw ne; }
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
catch (InvocationTargetException ite) { throw ite.getTargetException(); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; }
// in java/org/apache/el/parser/AstFunction.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(MessageFactory.get("error.function", this .getOutputName()), cause); }
// in java/org/apache/el/parser/AstValue.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); ServletException se = new ServletException(e); throw se; }
// in java/javax/el/ExpressionFactory.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
(Lib) SQLException
(Domain) LifecycleException
1
                    
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { throw new LifecycleException(e); }
(Lib) ZipException
(Lib) IOException
1
                    
// in java/org/apache/naming/resources/WARDirContext.java
catch (ZipException e) { throw new IOException(e.getMessage(), e); }
(Lib) AccessControlException
(Lib) ClassNotFoundException
3
                    
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
(Lib) InterruptedException
(Lib) RejectedExecutionException
1
                    
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); }
(Lib) CertificateException
(Lib) IOException
Unknown
1
                    
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (CertificateException ex) { throw new IOException(ex); }
1
                    
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(CertificateException ce) { throw ce; }
(Lib) UnsatisfiedLinkError
(Lib) Exception
1
                    
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (UnsatisfiedLinkError e) { throw new Exception(sm.getString("endpoint.init.notavail")); }
(Lib) DataFormatException
(Lib) IOException
1
                    
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
catch (DataFormatException e) { throw new IOException(e); }
(Lib) NoSuchAlgorithmException
(Lib) IOException
(Domain) LifecycleException
(Lib) IllegalStateException
(Domain) ServletException
(Domain) UnavailableException
1
                    
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (NoSuchAlgorithmException e) { throw new IOException(e); }
1
                    
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { throw new LifecycleException (sm.getString("realmBase.algorithm", digest), e); }
2
                    
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { log.error("Couldn't get MD5 digest: ", e); throw new IllegalStateException(e.getMessage()); }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new IllegalStateException(); }
1
                    
// in java/org/apache/catalina/websocket/WebSocketServlet.java
catch (NoSuchAlgorithmException e) { throw new ServletException(e); }
1
                    
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NoSuchAlgorithmException e) { throw new UnavailableException("No MD5"); }
(Lib) CancelledKeyException
Unknown
1
                    
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( CancelledKeyException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; }
(Lib) RejectedExecutionException
(Lib) RejectedExecutionException
Unknown
3
                    
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
catch (RejectedExecutionException rx) { //there could have been contention around the queue if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException("Work queue full."); }
1
                    
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
(Lib) BindException
Unknown
1
                    
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (BindException orig) { String msg; if (getAddress() == null) msg = orig.getMessage() + " <null>:" + getPort(); else msg = orig.getMessage() + " " + getAddress().toString() + ":" + getPort(); BindException be = new BindException(msg); be.initCause(orig); throw be; }
(Lib) SSLException
(Lib) SocketException
Unknown
1
                    
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException e){ throw new SocketException("SSL handshake error" + e.toString()); }
2
                    
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch(SSLException sslex) { log.info(sm.getString("jsseSupport.clientCertError"), sslex); throw sslex; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException ssle) { // SSL configuration is invalid. Possibly cert doesn't match ciphers IOException ioe = new IOException(sm.getString( "jsse.invalid_ssl_conf", ssle.getMessage())); ioe.initCause(ssle); throw ioe; }
(Lib) CRLException
Unknown
1
                    
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(CRLException crle) { throw crle; }
(Lib) NoSuchElementException
(Lib) IllegalStateException
4
                    
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "expiresFilter.startingPointNotFound", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException( sm.getString( "Duration unit not found after amount {} in directive '{}'", Integer.valueOf(amount), line)); }
(Lib) CloneNotSupportedException
(Lib) RuntimeException
1
                    
// in java/javax/servlet/http/Cookie.java
catch (CloneNotSupportedException e) { throw new RuntimeException(e.getMessage()); }
(Lib) URISyntaxException
(Lib) InvalidNameException
Unknown
1
                    
// in java/org/apache/catalina/realm/JNDIRealm.java
catch ( URISyntaxException e ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); }
1
                    
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
catch (URISyntaxException e) { // Wrap the exception and re-throw IOException ioe = new IOException(); ioe.initCause(e); throw ioe; }
(Lib) RuntimeOperationsException
(Lib) MBeanException
Unknown
21
                    
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
1
                    
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (RuntimeOperationsException e) { throw e; }
(Lib) InstanceNotFoundException
(Lib) MBeanException
Unknown
28
                    
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
1
                    
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (InstanceNotFoundException e) { throw e; }
(Lib) InvalidAttributeValueException
(Lib) MBeanException
1
                    
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvalidAttributeValueException e) { throw new MBeanException(e); }
(Lib) MalformedObjectNameException
(Lib) MBeanException
Unknown
1
                    
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (MalformedObjectNameException e) { throw new MBeanException(e); }
10
                    
// in java/org/apache/catalina/mbeans/UserMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for group " + group); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/UserMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role " + role); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for group [" + groupname + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role [" + rolename + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for user [" + username + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/GroupMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role " + role); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/GroupMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for user " + user); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for environment " + envs[i]); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for resource " + resources[i]); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for resource " + resourceLinks[i]); iae.initCause(e); throw iae; }
(Lib) EmptyStackException
Unknown
1
                    
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { throw createSAXException("endPrefixMapping popped too many times"); }
(Lib) DOMException
(Lib) SAXException
4
                    
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
(Lib) StringIndexOutOfBoundsException
(Domain) ClassFormatException
2
                    
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid signature: " + signature, e); }
(Lib) UnsupportedOperationException
(Domain) PropertyNotWritableException
2
                    
// in java/javax/el/MapELResolver.java
catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); }
// in java/javax/el/ListELResolver.java
catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); }
(Lib) ClassCastException
(Domain) LifecycleException
(Domain) ServletException
1
                    
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassCastException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e); }
2
                    
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ClassCastException e) { unavailable(null); // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.notServlet", servletClass), e); }
// in java/javax/servlet/http/HttpServlet.java
catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); }
(Lib) UnsupportedClassVersionError
(Lib) UnsupportedClassVersionError
1
                    
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); }
(Lib) PartialResultException
Unknown
5
                    
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; else return (null); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
(Lib) UnsupportedCallbackException
(Lib) LoginException
1
                    
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (UnsupportedCallbackException e) { throw new LoginException(e.toString()); }
(Lib) InvalidTargetObjectTypeException
(Lib) MBeanException
28
                    
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
(Lib) TransformerException
(Domain) ServletException
1
                    
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (TransformerException e) { throw new ServletException("XSL transformer error", e); }

Caught / Thrown Exception

Not all exceptions are thrown AND caught in the same project. The following table gives the exceptions types with respect to this. The lower left hand side sell lists all exceptions thrown but not caught (prevalent for libraries), the upper right-hand side lists all exceptions caught but not thrown (usually coming from external dependencies).

Thrown Not Thrown
Caught
Type Name
(Lib) IllegalStateException
(Lib) IOException
(Domain) MalformedStreamException
(Domain) FileUploadIOException
(Domain) ClientAbortException
(Lib) NullPointerException
(Lib) IndexOutOfBoundsException
(Lib) Exception
(Domain) JasperException
(Domain) Error
(Domain) ParseException
(Domain) FileUploadException
(Domain) InvalidContentTypeException
(Domain) ChannelException
(Domain) LifecycleException
(Domain) SSIStopProcessingException
(Domain) UnavailableException
(Domain) ServletException
(Lib) RuntimeException
(Domain) ClassFormatException
(Domain) RemoteProcessException
(Domain) PropertyNotFoundException
(Domain) PropertyNotWritableException
(Domain) MethodNotFoundException
(Domain) ELException
(Lib) NoSuchMethodException
(Lib) IllegalArgumentException
(Lib) UnsupportedEncodingException
(Lib) FileNotFoundException
(Lib) NumberFormatException
(Lib) ArrayIndexOutOfBoundsException
(Lib) ClassNotFoundException
(Lib) MalformedURLException
(Lib) SAXParseException
(Lib) SAXException
(Lib) BuildException
(Lib) SecurityException
(Lib) InstantiationException
(Lib) EOFException
(Lib) NamingException
(Lib) SQLException
(Lib) NameNotFoundException
(Lib) OperationNotSupportedException
(Lib) NameAlreadyBoundException
(Lib) InvalidNameException
(Lib) ZipException
(Lib) SocketException
(Lib) SocketTimeoutException
(Lib) UnsatisfiedLinkError
(Lib) RejectedExecutionException
(Lib) SSLException
(Lib) CRLException
(Lib) NoSuchElementException
(Lib) CloneNotSupportedException
(Lib) RuntimeOperationsException
(Lib) EmptyStackException
(Lib) UnsupportedOperationException
(Lib) ArithmeticException
(Lib) ClassCastException
(Lib) UnsupportedClassVersionError
(Lib) LoginException
(Lib) UnsupportedCallbackException
Type Name
(Domain) SizeException
(Domain) LookaheadSuccess
(Lib) PrivilegedActionException
(Lib) Throwable
(Lib) MissingResourceException
(Lib) IntrospectionException
(Domain) EnableDTDValidationException
(Lib) AbstractMethodError
(Lib) IllegalAccessException
(Lib) NoClassDefFoundError
(Lib) ParserConfigurationException
(Lib) InvocationTargetException
(Lib) AccessControlException
(Lib) InterruptedException
(Lib) InterruptedIOException
(Lib) CertificateException
(Lib) NoSuchProviderException
(Lib) DataFormatException
(Lib) NoSuchAlgorithmException
(Lib) CancelledKeyException
(Lib) ClosedChannelException
(Lib) OutOfMemoryError
(Lib) BindException
(Lib) KeyManagementException
(Lib) URISyntaxException
(Lib) InstanceNotFoundException
(Lib) InvalidAttributeValueException
(Lib) MalformedObjectNameException
(Lib) UnknownHostException
(Lib) SAXNotRecognizedException
(Lib) DOMException
(Lib) StringIndexOutOfBoundsException
(Lib) ClassFormatError
(Lib) NoSuchFieldException
(Lib) GSSException
(Lib) CommunicationException
(Lib) ServiceUnavailableException
(Lib) PartialResultException
(Lib) AuthenticationException
(Lib) AccountExpiredException
(Lib) CredentialExpiredException
(Lib) FailedLoginException
(Lib) InvalidTargetObjectTypeException
(Lib) JMRuntimeException
(Lib) RemoteException
(Lib) MalformedInputException
(Lib) UnmappableCharacterException
(Lib) ConnectException
(Lib) ClosedSelectorException
(Lib) NotSerializableException
(Lib) TransformerException
(Lib) IllegalThreadStateException
(Lib) PatternSyntaxException
(Lib) MBeanRegistrationException
Not caught
Type Name
(Domain) JspTagException
(Domain) JspException
(Lib) ELParseException
(Domain) JspMethodNotFoundException
(Domain) JspPropertyNotFoundException
(Domain) JspELException
(Domain) JspPropertyNotWritableException
(Lib) UTFDataFormatException
(Lib) ServiceException
(Lib) NotContextException
(Lib) TokenMgrError
(Domain) IllegalBoundaryException
(Domain) ItemSkippedException
(Domain) IOFileUploadException
(Domain) SizeLimitExceededException
(Domain) InvalidFileNameException
(Domain) DecodeException
(Lib) MBeanException
(Lib) AttributeNotFoundException
(Lib) ReflectionException
(Lib) RuntimeErrorException
(Lib) IllegalAccessError
(Lib) CharConversionException

Methods called in Catch and Finally Blocks

The following shows the methods that are called inside catch blocks (first column) and finally blocks (second column). For each method, we give the number of times it is called in a catch block (second sub-column), and the total number of calls (third sub-column). If the method name is red, it means that it is only called from catch/finally blocks. Hovering over a number triggers showing code snippets from the application code.

Catch Finally
Method Nbr Nbr total
log 882
                  
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); jsw.getServletContext().log("Background compile failed", t); }
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch(Exception e) { context.log("Security Init for context failed",e); }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), t); } // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug(sm.getString( "http11processor.request.prepare"), t); } // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString( "http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error t.printStackTrace(); response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable t) { log.log(Level.SEVERE, "endpoint.poll.error", t); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException e) { log.log(Level.SEVERE, this + " error ", e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable e) { log.log(Level.SEVERE, this + " error ", e); reset(); // no notifyIO - just did it. }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { log.log(Level.SEVERE, "Error parsing head SYN_STREAM", t); abort("Error reading headers " + t); return CLOSE; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (ClassCastException cce) { project.log("wrong object reference " + refId + " - " + pref.getClass()); return null; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (ClassCastException cce) { getProject().log( "Wrong object reference " + getRef() + " - " + pref.getClass()); return null; }
// in java/org/apache/catalina/ant/BaseRedirectorHelperTask.java
catch (IOException ioe) { log("Error closing redirector: " + ioe.getMessage(), Project.MSG_ERR); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (Exception e) { log("HTMLManagerServlet.sessions[" + cn + "]", e); message = smClient.getString("managerServlet.exception", e.toString()); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch(Exception e) { message = smClient.getString ("htmlManagerServlet.deployUploadFail", e.getMessage()); log(message, e); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (NumberFormatException e) { log("Could not parse idle parameter to an int: " + idleParam); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (IllegalStateException ise) { if (debug >= 1) { log("Can't invalidate already invalidated session id " + sessionId); } }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (IllegalStateException ise) { if (debug >= 1) { log("Can't remote attribute '" + attributeName + "' for invalidated session id " + sessionId); } }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { getServletContext().log (sm.getString("hostManagerServlet.startFailed", name), e); writer.println(smClient.getString( "hostManagerServlet.startFailed", name)); writer.println(smClient.getString( "hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { getServletContext().log(sm.getString( "hostManagerServlet.stopFailed", name), e); writer.println(smClient.getString("hostManagerServlet.stopFailed", name)); writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log(sm.getString("managerServlet.objectNameFail", name), e); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.storeConfig", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.save[" + path + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.check[" + displayPath + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.check[" + displayPath + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.install[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.reload[" + cn.getDisplayName() + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.resources[" + type + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.resources[" + type + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log("ManagerServlet.serverinfo",t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.sessions[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (NumberFormatException e) { log("Could not parse idle parameter to an int: " + idleParam); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log(sm.getString("managerServlet.startFailed", displayPath), t); writer.println(smClient.getString("managerServlet.startFailed", displayPath)); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.stop[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.undeploy[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { if (debug > 10) log("readme '" + readmeFile + "' not found", e); return null; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { if (debug > 10) log("localXsltFile '" + localXsltFile + "' not found", e); }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException ioe) { // delete in case file is corrupted if (f.exists()) { if (!f.delete() && debug >= 2) { log("expandCGIScript: failed to delete '" + f.getAbsolutePath() + "'"); } } }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException e){ log ("Caught exception " + e); throw e; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException ioe) { log ("Exception closing header reader " + ioe); }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException ioe) { log ("Exception closing output stream " + ioe); }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (InterruptedException e) { log ("Interupted waiting for stderr reader thread"); }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (NumberFormatException nfe) { // Not a valid status code log ("runCGI: invalid status code:" + status); return HttpServletResponse.SC_INTERNAL_SERVER_ERROR; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (NumberFormatException nfe) { // Not a valid status code log ("runCGI: invalid status code:" + status); return HttpServletResponse.SC_INTERNAL_SERVER_ERROR; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException e) { log("sendToLog error", e) ; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException ce) { log("sendToLog error", ce) ; }
// in java/org/apache/catalina/ssi/ExpressionParseTree.java
catch (PatternSyntaxException pse) { ssiMediator.log("Invalid expression: " + expr, pse); return 0; }
// in java/org/apache/catalina/ssi/SSIInclude.java
catch (IOException e) { ssiMediator.log("#include--Couldn't include file: " + substitutedValue, e); writer.write(configErrMsg); }
// in java/org/apache/catalina/ssi/SSIFlastmod.java
catch (IOException e) { ssiMediator.log( "#flastmod--Couldn't get last modified for file: " + substitutedValue, e); writer.write(configErrMsg); }
// in java/org/apache/catalina/ssi/SSIExec.java
catch (InterruptedException e) { ssiMediator.log("Couldn't exec file: " + substitutedValue, e); writer.write(configErrMsg); }
// in java/org/apache/catalina/ssi/SSIExec.java
catch (IOException e) { if (!foundProgram) { //apache doesn't output an error message if it can't find // a program } ssiMediator.log("Couldn't exec file: " + substitutedValue, e); }
// in java/org/apache/catalina/ssi/SSIFsize.java
catch (IOException e) { ssiMediator.log("#fsize--Couldn't get size for file: " + substitutedValue, e); writer.write(configErrMsg); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Exception e) { // Should never happen log(sm.getString("applicationContext.mapping.error"), e); return (null); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Exception e) { // Unexpected log(sm.getString("applicationContext.lookup.error", path, getContextPath()), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Exception e) { // Unexpected log(sm.getString("applicationContext.lookup.error", path, getContextPath()), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.fireContainerEvent("afterContextAttributeRemoved", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (replaced) context.fireContainerEvent("afterContextAttributeReplaced", listener); else context.fireContainerEvent("afterContextAttributeAdded", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { getServletContext().log(sm.getString ("standardWrapper.unloadException", getName()), e); }
2765
getString 570
                  
// in java/org/apache/naming/NamingContext.java
catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); }
// in java/org/apache/naming/resources/WARDirContext.java
catch (Exception e) { throw new IllegalArgumentException (sm.getString("warResources.invalidWar", e.getMessage())); }
// in java/org/apache/naming/resources/WARDirContext.java
catch (InvalidNameException e) { log.info(sm.getString("resources.invalidName", strName), e); return null; }
// in java/org/apache/naming/resources/FileDirContext.java
catch (IOException e) { NamingException ne = new NamingException (sm.getString("resources.bindFailed", e)); ne.initCause(e); throw ne; }
// in java/org/apache/naming/resources/BaseDirContext.java
catch (IOException ioe) { log.warn(sm.getString("resources.addResourcesJarFail", url), ioe); }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (Exception e) { throw new IllegalArgumentException(sm.getString( "resources.invalidCache", cacheClassName), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().error(sm.getString( "abstractProtocolHandler.mbeanRegistrationFailed", tpOname, getName()), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.initError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.startError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.pauseError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.resumeError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.stopError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().error(sm.getString("abstractProtocolHandler.destroyError", getName()), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch(java.net.SocketException e) { // SocketExceptions are normal getLog().debug(sm.getString( "ajpprotocol.proto.socketexception.debug"), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (java.io.IOException e) { // IOExceptions are normal getLog().debug(sm.getString( "ajpprotocol.proto.ioexception.debug"), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); // any other exception or error is odd. Here we log it // with "ERROR" level, so it will show up even on // less-than-verbose logs. getLog().error(sm.getString("ajpprotocol.proto.error"), e); }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (java.security.cert.CertificateException e) { getLog().error(sm.getString("ajpprocessor.certs.fail"), e); return; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (NoSuchProviderException e) { getLog().error(sm.getString("ajpprocessor.certs.fail"), e); return; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (IOException ioe) { log.warn(sm.getString("http11processor.socket.sslreneg",ioe)); }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), e); } error = true; break; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), t); } // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug(sm.getString( "http11processor.request.prepare"), t); } // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString( "http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.finish"), t); // 500 - Internal Server Error // Can't add a 500 to the access log since that has already been // written in the Adapter.service method. response.setStatus(500); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.response.finish"), t); error = true; }
// in java/org/apache/coyote/http11/Http11Processor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11Processor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException x) { if (running) { log.error(sm.getString("endpoint.accept.fail"), x); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.accept.fail"), t); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "endpoint.debug.channelCloseFail"), e); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception e){ if (log.isDebugEnabled()) { log.debug(sm.getString( "endpoint.debug.socketCloseFail"), e); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { log.error(sm.getString( "endpoint.nio.selectorCloseFail"), ioe); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { log.error(sm.getString( "endpoint.nio.selectorCloseFail"), ioe); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (UnsatisfiedLinkError e) { throw new Exception(sm.getString("endpoint.init.notavail")); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { if (step == 2) { log.debug(sm.getString("endpoint.err.handshake"), t); } else { log.debug(sm.getString("endpoint.err.unexpected"), t); } } // Tell to close the socket return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Error e) { if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(sm.getString("endpoint.poll.limitedpollsize", "" + size)); return 0; } else { log.error(sm.getString("endpoint.poll.initfail"), e); return -1; } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (running) { String msg = sm.getString("endpoint.accept.fail"); if (t instanceof Error) { Error e = (Error) t; if (e.getError() == 233) { // Not an error on HP-UX so log as a warning // so it can be filtered out on that platform // See bug 50273 log.warn(msg, t); } else { log.error(msg, t); } } else { log.error(msg, t); } } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.poll.error"), t); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { // Pool not created so no need to destroy it. log.error(sm.getString("endpoint.sendfile.error"), e); data.socket = 0; return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { log.error(sm.getString("endpoint.sendfile.error"), e); Pool.destroy(data.fdpool); data.socket = 0; return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.poll.error"), t); }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
catch(Exception e) { if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("endpoint.debug.unlock", "" + getPort()), e); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (IOException x) { if (running) { log.error(sm.getString("endpoint.accept.fail"), x); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.accept.fail"), npe); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.accept.fail"), t); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.err.handshake"), t); } // Tell to close the socket state = SocketState.CLOSED; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Exception e) { log.error(sm.getString("endpoint.err.close"), e); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (SocketException s) { //error here is common if the client has reset the connection if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.err.unexpected"), s); } // Close the socket return false; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.err.unexpected"), t); // Close the socket return false; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch( Throwable t ) { log.debug(sm.getString("jsseSupport.clientCertError"), t); return null; }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch(Exception ex) { log.info(sm.getString( "jseeSupport.certTranslationError", certs[i]), ex); return null; }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch(SSLException sslex) { log.info(sm.getString("jsseSupport.clientCertError"), sslex); throw sslex; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { Throwable cause = ioe.getCause(); if (cause instanceof UnrecoverableKeyException) { // Log a warning we had a password issue log.warn(sm.getString("jsse.invalid_truststore_password"), cause); // Re-try trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, null); } else { // Something else went wrong - re-throw throw ioe; } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (FileNotFoundException fnfe) { log.error(sm.getString("jsse.keystore_load_failed", type, path, fnfe.getMessage()), fnfe); throw fnfe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException ssle) { // SSL configuration is invalid. Possibly cert doesn't match ciphers IOException ioe = new IOException(sm.getString( "jsse.invalid_ssl_conf", ssle.getMessage())); ioe.initCause(ssle); throw ioe; }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException ioe) { // Should never happen... log.error(sm.getString("parameters.copyFail"), ioe); }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IllegalStateException ise) { // Hitting limit stops processing further params but does // not cause request to fail. parseFailed = true; UserDataHelper.Mode logMode = maxParamCountLog.getNextMode(); if (logMode != null) { String message = ise.getMessage(); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString( "parameters.maxCountFail.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } break; }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException e) { parseFailed = true; decodeFailCount++; if (decodeFailCount == 1 || log.isDebugEnabled()) { if (log.isDebugEnabled()) { log.debug(sm.getString("parameters.decodeFail.debug", origName.toString(), origValue.toString()), e); } else if (log.isInfoEnabled()) { UserDataHelper.Mode logMode = userDataLog.getNextMode(); if (logMode != null) { String message = sm.getString( "parameters.decodeFail.info", tmpName.toString(), tmpValue.toString()); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString("parameters.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } } } }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
catch (IOException e) { log.warn(sm.getString("c2bConverter.recycleFailed"), e); try { init(); } catch (IOException ignore) { // Should never happen since this means encoding is invalid and // in that case, the constructor will have failed. } }
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
catch (IOException e) { log.warn(sm.getString("jarScan.webinflibFail", url), e); }
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
catch (IOException ioe) { log.warn(sm.getString( "jarScan.classloaderFail",urls[i]), ioe); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassCastException e) { log.error(sm.getString("contextConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString( "contextConfig.authenticatorInstantiate", authenticatorName), t); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.badUrl", defaultContextFile), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.badUrl", hostContextFile), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString("contextConfig.contextMissing", contextXml) , e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (SAXParseException e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); log.error(sm.getString("contextConfig.defaultPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.contextClose"), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString( "contextConfig.fixDocBase", context.getName()), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.webinfClassesUrl", resource), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (NamingException e) { log.error(sm.getString( "contextConfig.webinfClassesUrl", "/WEB-INF/classes"), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException ioe) { log.error(sm.getString( "contextConfig.servletContainerInitializerFail", url, context.getName())); ok = false; return; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassNotFoundException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (InstantiationException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IllegalAccessException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException ioe) { log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName())); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (URISyntaxException e) { log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName())); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.baseError"), e); return null; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (FileNotFoundException e) { log.error(sm.getString("contextConfig.altDDNotFound", altDDName)); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString("contextConfig.applicationUrl")); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString("contextConfig.applicationUrl")); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString( "contextConfig.defaultError", filename, file), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (SAXParseException e) { log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e); log.error(sm.getString("contextConfig.applicationPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (URISyntaxException e) { log.error(sm.getString("contextConfig.fileUrl", url), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamJar", entryName, url),e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.jarFile", url), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamJndi", url),e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.jndiUrl", url), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamFile", file.getAbsolutePath()),e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassFormatException e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (NoClassDefFoundError e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); return null; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassNotFoundException e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); return null; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassFormatError e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); return null; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), t); return null; }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.webxmlFail", resourcePath, descriptor.getTaglibURI()), ioe); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.webinfFail", path), ioe); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.dirFail", fileList[i].getAbsolutePath()), ioe); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.jarFail", jarConn.getURL()), ioe); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (ClassCastException e) { log.error(sm.getString("tldConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/TldConfig.java
catch (Exception e) { log.error(sm.getString( "tldConfig.execute", context.getName()), e); }
// in java/org/apache/catalina/startup/EngineConfig.java
catch (ClassCastException e) { log.error(sm.getString("engineConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/HostConfig.java
catch (ClassCastException e) { log.error(sm.getString("hostConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.threaded.error"), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", contextXml.getAbsolutePath())); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployDescriptor.error", contextXml.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployWar.threaded.error"), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", war.getAbsolutePath())); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", war.getAbsolutePath())); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployWar.error", war.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDir.threaded.error"), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", xml)); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployDir.error", dir.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString ("hostConfig.context.remove", app.name), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { log.warn(sm.getString ("hostConfig.canonicalizing", app.name), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString ("hostConfig.context.remove", app.name), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { log.warn(sm.getString ("hostConfig.canonicalizing", app.name), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { log.warn(sm.getString ("hostConfig.canonicalizing", app.name), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.warn(sm.getString ("hostConfig.context.restart", app.name), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString("hostConfig.jmx.register", oname), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString("hostConfig.jmx.unregister", oname), e); }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { log.error(sm.getString ("expandWar.copy", fileSrc, fileDest), e); result = false; }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage())); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", file), e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", getConfigFile()), e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", "server-embed.xml"), e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.error(sm.getString("catalina.shutdownHookFail"), ex); }
// in java/org/apache/catalina/startup/UserConfig.java
catch (ClassCastException e) { log.error(sm.getString("hostConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/UserConfig.java
catch (Exception e) { host.getLogger().error(sm.getString("userConfig.database"), e); return; }
// in java/org/apache/catalina/startup/UserConfig.java
catch (Exception e) { host.getLogger().error(sm.getString("userConfig.deploy.threaded.error"), e); }
// in java/org/apache/catalina/startup/UserConfig.java
catch (Exception e) { host.getLogger().error(sm.getString("userConfig.error", user), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalStateException e) { log.info(sm.getString("webappClassLoader.stopped", name), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.jdbcRemoveFailed", contextName), t); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { log.warn(sm.getString( "webappClassLoader.jdbcRemoveStreamError", contextName), ioe); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.stopTimerThreadFail", thread.getName(), contextName), t); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (InvocationTargetException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchMethodException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badKey", args[1]), e); args[2] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badValue", args[3]), e); args[4] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { log.info(sm.getString("webappClassLoader.clearRmiInfo", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { if (System.getProperty("java.vendor").startsWith("Sun")) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } else { log.debug(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { throw new IllegalArgumentException( sm.getString("webappClassLoader.validationErrorJarPath", jarEntry2.getName()), ioe); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { log.error(sm.getString("webappClassLoader.readError", name), e); return null; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NumberFormatException e) { log.error(sm.getString("webappLoader.reloadable", event.getNewValue().toString())); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", libPath)); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", filename)); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/realm/MemoryRealm.java
catch (Exception e) { log.warn(sm.getString("memoryRealm.xmlFeatureEncoding"), e); }
// in java/org/apache/catalina/realm/MemoryRealm.java
catch (Exception e) { throw new LifecycleException (sm.getString("memoryRealm.readXml"), e); }
// in java/org/apache/catalina/realm/CombinedRealm.java
catch (LifecycleException e) { // If realm doesn't start can't authenticate against it iter.remove(); log.error(sm.getString("combinedRealm.realmStartFail", realm.getClass().getName()), e); }
// in java/org/apache/catalina/realm/CombinedRealm.java
catch (GSSException e) { log.warn(sm.getString("realmBase.gssNameFail"), e); return null; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NullPointerException e) { /* BZ 42449 - Kludge Sun's LDAP provider with broken SSL */ // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (CommunicationException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Log the problem for posterity containerLog.error(sm.getString("jndiRealm.exception"), e); // Close the connection so that it gets reopened next time if (context != null) close(context); // Return "not authenticated" for this request if (containerLog.isDebugEnabled()) containerLog.debug("Returning null principal."); return (null); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (InvalidNameException ine) { // Log the problem for posterity containerLog.warn(sm.getString("jndiRealm.exception"), ine); // ignore; this is probably due to a name not fitting // the search path format exactly, as in a fully- // qualified name being munged into a search path // that already contains cn= or vice-versa }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { containerLog.error(sm.getString("jndiRealm.close"), e); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (CommunicationException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Log the problem for posterity containerLog.error(sm.getString("jndiRealm.exception"), e); // Close the connection so that it gets reopened next time if (context != null) close(context); // Return "not authenticated" for this request return (null); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (Exception e) { connectionAttempt = 1; // log the first exception. containerLog.warn(sm.getString("jndiRealm.exception"), e); // Try connecting to the alternate url. context = new InitialDirContext(getDirectoryContextEnvironment()); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { throw new LifecycleException(sm.getString("jndiRealm.open"), e); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (SQLException e) { containerLog.error(sm.getString("dataSourceRealm.close"), e); // Just log it here }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (Exception e) { // Log the problem for posterity containerLog.error(sm.getString("dataSourceRealm.exception"), e); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch(SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getPassword.exception", username)); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getPassword.exception", username)); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch(SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getRoles.exception", username)); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getRoles.exception", username)); }
// in java/org/apache/catalina/realm/UserDatabaseRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); containerLog.error(sm.getString("userDatabaseRealm.lookup", resourceName), e); database = null; }
// in java/org/apache/catalina/realm/LockOutRealm.java
catch (GSSException e) { log.warn(sm.getString("realmBase.gssNameFail"), e); return null; }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("jaasRealm.unexpectedError"), e); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (AccountExpiredException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.accountExpired", username)); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (CredentialExpiredException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.credentialExpired", username)); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (FailedLoginException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.failedLogin", username)); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (LoginException e) { log.warn(sm.getString("jaasRealm.loginException", username), e); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("jaasRealm.unexpectedError"), e); return (null); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (GSSException e) { log.warn(sm.getString("realmBase.gssNameFail"), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "realmBase.delegatedCredentialFail", name), e); } }
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { throw new LifecycleException (sm.getString("realmBase.algorithm", digest), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (Exception e) { log.error(sm.getString("realmBase.digest"), e); return (credentials); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassNotFoundException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassNotFoundException", className), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (InstantiationException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.InstantiationException", className), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (IllegalAccessException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.IllegalAccessException", className), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassCastException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { // Log the problem for posterity containerLog.error(sm.getString("jdbcRealm.exception"), e); // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { containerLog.warn(sm.getString("jdbcRealm.close"), e); // Just log it here }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { // Log the problem for posterity containerLog.error(sm.getString("jdbcRealm.exception"), e); // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { // Log the problem for posterity containerLog.error(sm.getString("jdbcRealm.exception"), e); // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { containerLog.error(sm.getString("jdbcRealm.open"), e); }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (RemoteException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.createRegistryFailed", serverName, Integer.toString(theRmiRegistryPort)), e); return null; }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (MalformedURLException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.invalidURL", serverName, url.toString()), e); return null; }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (IOException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.createServerFailed", serverName), e); }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (IOException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.destroyServerFailed", serverName),e); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (RuntimeException e) { throw new ServletException(sm.getString( "expiresFilter.exceptionProcessingParameter", name, value), e); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "expiresFilter.startingPointNotFound", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { throw new IllegalStateException(sm.getString( "Invalid duration (number) '{}' in directive '{}'", currentToken, line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException( sm.getString( "Duration unit not found after amount {} in directive '{}'", Integer.valueOf(amount), line)); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (ClassNotFoundException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (InstantiationException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (IllegalAccessException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
catch (Exception e) { log.warn(sm.getString("memoryUserDatabase.xmlFeatureEncoding"), e); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (Exception e) { log("HTMLManagerServlet.sessions[" + cn + "]", e); message = smClient.getString("managerServlet.exception", e.toString()); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch(Exception e) { message = smClient.getString ("htmlManagerServlet.deployUploadFail", e.getMessage()); log(message, e); }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (IOException e) { writer.println(smClient.getString( "hostManagerServlet.managerXml")); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { getServletContext().log (sm.getString("hostManagerServlet.startFailed", name), e); writer.println(smClient.getString( "hostManagerServlet.startFailed", name)); writer.println(smClient.getString( "hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { getServletContext().log(sm.getString( "hostManagerServlet.stopFailed", name), e); writer.println(smClient.getString("hostManagerServlet.stopFailed", name)); writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log(sm.getString("managerServlet.objectNameFail", name), e); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.storeConfig", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.save[" + path + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.check[" + displayPath + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.check[" + displayPath + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.install[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.reload[" + cn.getDisplayName() + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.resources[" + type + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.resources[" + type + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log("ManagerServlet.serverinfo",t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.sessions[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log(sm.getString("managerServlet.startFailed", displayPath), t); writer.println(smClient.getString("managerServlet.startFailed", displayPath)); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.stop[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.undeploy[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { if (war.exists() && !war.delete()) { writer.println( smClient.getString("managerServlet.deleteFail", war)); } throw e; }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
// in java/org/apache/catalina/tribes/transport/PooledSender.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "PooledSender.senderDisconnectFail"), e); } }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { error = true; log.error(sm.getString("standardManager.unloading.ioe", e), e); throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.unloading.ioe", e), e); try { oos.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardManager.managerLoad"), t); }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardManager.managerUnload"), t); }
// in java/org/apache/catalina/session/ManagerBase.java
catch (NumberFormatException e) { log.error(sm.getString("managerBase.sessionTimeout", event.getNewValue())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); keys = new String[0]; // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionSQLException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (NamingException e) { manager.getContainer().getLogger().error( sm.getString(getStoreName() + ".wrongDataSource", this.dataSourceName), e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (ClassNotFoundException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (InstantiationException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (IllegalAccessException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".commitSQLException"), e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".close", e.toString())); // Just log it here }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (PrivilegedActionException ex) { Exception e = ex.getException(); log.error(sm.getString( "persistentManager.swapInException", id), e); if (e instanceof IOException){ throw (IOException)e; } else if (e instanceof ClassNotFoundException) { throw (ClassNotFoundException)e; } }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (ClassNotFoundException e) { String msg = sm.getString( "persistentManager.deserializeError", id); log.error(msg, e); throw new IllegalStateException(msg, e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error(sm.getString ("persistentManager.serializeError", session.getIdInternal(), e)); throw e; }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionCreated", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent( "afterSessionDestroyed", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Exception e) { manager.getContainer().getLogger().error( sm.getString("standardSession.logoutfail"), e); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t){ manager.getContainer().getLogger().error (sm.getString("standardSession.bindingEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.bindingEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { if (unbound != null) { context.fireContainerEvent( "afterSessionAttributeReplaced", listener); } else { context.fireContainerEvent("afterSessionAttributeAdded", listener); } } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (NotSerializableException e) { manager.getContainer().getLogger().warn (sm.getString("standardSession.notSerializable", saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug (" storing attribute '" + saveNames.get(i) + "' with value NOT_SERIALIZED"); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionAttributeRemoved", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (Exception e) { container.getLogger().warn( sm.getString("cometConnectionManagerValve.event"), e); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (IOException e) { container.getLogger().warn(sm.getString( "cometConnectionManagerValve.event"), e); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (Exception e) { req.getWrapper().getParent().getLogger().warn(sm.getString( "cometConnectionManagerValve.listenerEvent"), e); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { // Log the problem for posterity container.getLogger().error(sm.getString("jdbcAccessLogValve.exception"), e); // Close the connection so that it gets reopened next time if (conn != null) { close(); } }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { container.getLogger().error(sm.getString("jdbcAccessLogValeve.close"), e); // Just log it here }
// in java/org/apache/catalina/valves/SSLValve.java
catch (java.security.cert.CertificateException e) { log.warn(sm.getString("sslValve.certError", strcerts), e); }
// in java/org/apache/catalina/valves/SSLValve.java
catch (NoSuchProviderException e) { log.error(sm.getString( "sslValve.invalidProvider", providerName), e); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("accessLogValve.rotateFail"), e); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.info(sm.getString("accessLogValve.closeFail"), e); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (UnsupportedEncodingException ex) { log.error(sm.getString( "accessLogValve.unsupportedEncoding", encoding), ex); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (IOException e) { writer = null; currentLogFile = null; log.error(sm.getString("accessLogValve.openFail", pathname), e); }
// in java/org/apache/catalina/valves/RemoteIpValve.java
catch (NumberFormatException nfe) { if (log.isDebugEnabled()) { log.debug(sm.getString( "remoteIpValve.invalidPortHeader", portHeaderValue, portHeader), nfe); } }
// in java/org/apache/catalina/authenticator/SSLAuthenticator.java
catch (IllegalStateException ise) { // Request body was too large for save buffer response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.certificates")); return false; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (LoginException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail", e)); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (PrivilegedActionException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail", e)); response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (IOException ioe) { log.debug("Request body too big to save during authentication"); response.sendError(HttpServletResponse.SC_FORBIDDEN, sm.getString("authenticator.requestBodyTooBig")); return (false); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardLoginFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardErrorFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", environment.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", resource.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", resourceLink.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", environment.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", resource.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", resourceLink.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", cr.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", ce.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", crl.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (NamingException e) { log.warn(sm.getString("namingResources.cleanupNoContext", container), e); return; }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (NamingException e) { log.warn(sm.getString( "namingResources.cleanupNoResource", cr.getName(), container), e); continue; }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (SecurityException e) { log.debug(sm.getString("namingResources.cleanupCloseSecurity", closeMethod, name, container)); return; }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (NoSuchMethodException e) { log.debug(sm.getString("namingResources.cleanupNoClose", name, container, closeMethod)); return; }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (IllegalArgumentException e) { log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (IllegalAccessException e) { log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (InvocationTargetException e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), t); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", crl.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", ce.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", cr.getName()), e); }
// in java/org/apache/catalina/deploy/WebXml.java
catch (NumberFormatException nfe) { log.warn(sm.getString("webXml.version.nfe", major, version), nfe); majorVersion = 0; }
// in java/org/apache/catalina/deploy/WebXml.java
catch (NumberFormatException nfe) { log.warn(sm.getString("webXml.version.nfe", minor, version), nfe); minorVersion = 0; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch(ParserConfigurationException e) { throw new ServletException (sm.getString("webdavservlet.jaxpfailed")); }
// in java/org/apache/catalina/ha/session/SerializablePrincipal.java
catch (ClassNotFoundException e) { log.error(sm.getString( "serializablePrincipal.readPrincipal.cnfe"), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaSession.java
catch (NotSerializableException e) { log.error(sm.getString("standardSession.notSerializable",saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); log.error(" storing attribute '" + saveNames.get(i)+ "' with value NOT_SERIALIZED"); }
// in java/org/apache/catalina/ha/session/BackupManager.java
catch ( Exception x ) { log.error(sm.getString("backupManager.startUnable", getName()),x); throw new LifecycleException(sm.getString("backupManager.startFailed", getName()),x); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.unableSerializeSessionID", newSessionID), e); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("deltaManager.loading.cnfe", e), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.loading.ioe", e), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.unloading.ioe", e), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("deltaManager.managerLoad"), t); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException x) { log.error(sm.getString("deltaManager.createMessage.unableCreateDeltaRequest",sessionId), x); return null; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Exception x) { log.error(sm.getString("deltaManager.receiveMessage.error",getName()), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception e) { log.error(sm.getString("farmWarDeployer.mbeanNameFail", engine.getName(), hostname),e); return; }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (java.io.IOException x) { log.error(sm.getString("farmWarDeployer.msgIoe"), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception ex) { log.error(sm.getString("farmWarDeployer.removeFailLocal", contextName), ex); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception x) { log.error(sm.getString("farmWarDeployer.modRemoveFail"), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception x) { log.error(sm.getString("farmWarDeployer.modInstallFail"), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception x) { log.error(sm.getString("farmWarDeployer.removeLocalFail"), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (IOException e) { log.error(sm.getString("farmWarDeployer.fileCopyFail", from, to), e); return false; }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
catch (PatternSyntaxException pse) { log.error(sm.getString("ReplicationValve.filter.failure", filter), pse); }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
catch (Exception x) { // FIXME we have a lot of sends, but the trouble with one node stops the correct replication to other nodes! log.error(sm.getString("ReplicationValve.send.failure"), x); }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
catch ( Exception x ) { log.error(sm.getString("ReplicationValve.send.invalid.failure",invalidIds[i]),x); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { log.error(sm.getString( "coyoteConnector.protocolHandlerInstantiationFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { log.error(sm.getString ("coyoteConnector.protocolHandlerPauseFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { log.error(sm.getString ("coyoteConnector.protocolHandlerResumeFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerInitializationFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { String errPrefix = ""; if(this.service != null) { errPrefix += "service.getName(): \"" + this.service.getName() + "\"; "; } throw new LifecycleException (errPrefix + " " + sm.getString ("coyoteConnector.protocolHandlerStartFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerStopFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerDestroyFailed"), e); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("coyoteRequest.sessionEndAccessFail"), t); }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { throw new SecurityException(sm.getString( "coyoteRequest.sendfileNotCanonical", value), e); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); }
// in java/org/apache/catalina/connector/Request.java
catch (UnsupportedEncodingException uee) { try { value = part.getString(Parameters.DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { // Should not be possible } }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Client disconnect if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Client disconnect or chunkedPostTooLarge error if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (!(t instanceof IOException)) { log.error(sm.getString("coyoteAdapter.service"), t); } error = true; return false; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); success = false; log.error(sm.getString("coyoteAdapter.service"), t); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("coyoteAdapter.accesslogFail"), t); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (UnsupportedEncodingException e1) { log.warn(sm.getString("coyoteAdapter.parsePathParam", enc)); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error(sm.getString("aprListener.sslInit"), t); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.info(sm.getString("aprListener.aprDestroy")); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.info(sm.getString("aprListener.aprInit", System.getProperty("java.library.path"))); return; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error( sm.getString("standardWrapper.allocateException", wrapper.getName()), e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception ex) { log.info(sm.getString("applicationFilterConfig.jmxRegisterFail", getFilterClass(), getFilterName()), ex); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch(Exception ex) { log.error(sm.getString( "applicationFilterConfig.jmxUnregisterFail", getFilterClass(), getFilterName()), ex); }
// in java/org/apache/catalina/core/StandardHost.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString( "standardHost.invalidErrorReportValveClass", errorValve), t); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Exception e) { // Should never happen log(sm.getString("applicationContext.mapping.error"), e); return (null); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Exception e) { // Unexpected log(sm.getString("applicationContext.lookup.error", path, getContextPath()), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Exception e) { // Unexpected log(sm.getString("applicationContext.lookup.error", path, getContextPath()), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.fireContainerEvent("afterContextAttributeRemoved", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (replaced) context.fireContainerEvent("afterContextAttributeReplaced", listener); else context.fireContainerEvent("afterContextAttributeAdded", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ServletException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.init", listenerClass.getName()), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.error(sm.getString("containerBase.threadedStartFailed"), e); fail = true; }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.error(sm.getString("containerBase.threadedStopFailed"), e); fail = true; }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.cluster", cluster), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.loader", loader), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.manager", manager), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.realm", realm), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.valve", current), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedServletsResource"), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedListenersResources"), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedServletsResources"), e); }
// in java/org/apache/catalina/core/StandardContextValve.java
catch (IOException ioe) { container.getLogger().error(sm.getString( "standardContextValve.acknowledgeException"), ioe); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error (sm.getString("naming.namingContextCreationFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NumberFormatException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", env.getName())); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (IllegalArgumentException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", env.getName())); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { logger.error(sm.getString("naming.wsdlFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { logger.error(sm.getString("naming.wsdlFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (Exception e) { logger.warn(sm.getString("naming.jmxRegistrationFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException e) { log.error(sm.getString( "standardService.connector.startFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException e) { log.error(sm.getString( "standardService.connector.stopFailed", connectors[j]), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.startFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.pauseFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.stopFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { String message = sm.getString( "standardService.connector.initFailed", connector); log.error(message, e); if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) throw new LifecycleException(message); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.destroyfailed", connector), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException e) { log.warn(sm.getString("standardContext.workPath", getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.error( sm.getString("standardContext.stoppingContext", getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.error( sm.getString("standardContext.startingContext", getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.filterStart", name), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.applicationListener", listeners[i]), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextInitialized", listener); getLogger().error (sm.getString("standardContext.listenerStart", instances[i].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextDestroyed", listener); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardContext.resourcesStart"), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardContext.resourcesStop"), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (ServletException e) { getLogger().error(sm.getString("standardWrapper.loadException", getName()), StandardWrapper.getRootCause(e)); // NOTE: load errors (including a servlet that throws // UnavailableException from tht init() method) are NOT // fatal to application startup }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[i].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[j].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException e) { log.warn(sm.getString("standardContext.workCreateException", workDir, catalinaHomePath, getName()), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ClassCastException e) { unavailable(null); // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.notServlet", servletClass), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { getServletContext().log(sm.getString ("standardWrapper.unloadException", getName()), e); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servlet = null; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); ioException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (UnavailableException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); servletException = e; wrapper.unavailable(e); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause); } servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); runtimeException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e); // FIXME: Exception handling needs to be similar to what is in the StandardWrapperValue }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { if (System.getProperty("java.vendor").startsWith( "Sun")) { log.error(sm.getString( "jreLeakListener.gcDaemonFail"), e); } else { log.debug(sm.getString( "jreLeakListener.gcDaemonFail"), e); } }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (SecurityException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (NoSuchMethodException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalArgumentException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalAccessException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (NoSuchMethodException e) { log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalArgumentException e) { log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalAccessException e) { log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (MalformedURLException e) { log.error(sm.getString( "jreLeakListener.jarUrlConnCacheFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IOException e) { log.error(sm.getString( "jreLeakListener.jarUrlConnCacheFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ParserConfigurationException e) { log.error(sm.getString("jreLeakListener.xmlParseFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { if (System.getProperty("java.vendor").startsWith( "Sun")) { log.error(sm.getString( "jreLeakListener.ldapPoolManagerFail"), e); } else { log.debug(sm.getString( "jreLeakListener.ldapPoolManagerFail"), e); } }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { log.error( sm.getString("jreLeakListener.classToInitializeFail", classNameToLoad), e); // continue with next class to load }
// in java/org/apache/catalina/core/StandardEngine.java
catch(Exception ex) { log.warn(sm.getString("standardEngine.jvmRouteFail")); }
// in java/org/apache/catalina/core/ThreadLocalLeakPreventionListener.java
catch (Exception e) { String msg = sm.getString( "threadLocalLeakPreventionListener.lifecycleEvent.error", event); log.error(msg, e); }
// in java/org/apache/catalina/core/ThreadLocalLeakPreventionListener.java
catch (Exception e) { String msg = sm.getString( "threadLocalLeakPreventionListener.containerEvent.error", event); log.error(msg, e); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (Exception e) { log.error(sm.getString("sessionIdGenerator.random", secureRandomClass), e); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (NoSuchAlgorithmException e) { log.error(sm.getString("sessionIdGenerator.randomAlgorithm", secureRandomAlgorithm), e); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (NoSuchProviderException e) { log.error(sm.getString("sessionIdGenerator.randomProvider", secureRandomProvider), e); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (NoSuchAlgorithmException e) { log.error(sm.getString("sessionIdGenerator.randomAlgorithm", secureRandomAlgorithm), e); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (MalformedObjectNameException e) { log.warn(sm.getString("lifecycleMBeanBase.registerFail", obj, name), e); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (Exception e) { log.warn(sm.getString("lifecycleMBeanBase.registerFail", obj, name), e); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (MBeanRegistrationException e) { log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", on), e); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (InstanceNotFoundException e) { log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", on), e); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.startFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.stopFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (LifecycleException e) { // Just log. Still want to destroy. log.warn(sm.getString("lifecycleBase.destroyStopFail"), e); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); }
// in java/org/apache/catalina/util/RequestUtil.java
catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.parseParameters.uee", encoding), uee); } }
// in java/org/apache/catalina/util/RequestUtil.java
catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee); } }
// in java/org/apache/catalina/util/RequestUtil.java
catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee); } return null; }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (IOException e) { log.error(sm.getString ("extensionValidator.failload", item), e); }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (IOException e) { log.error (sm.getString ("extensionValidator.failload", files[i]), e); }
// in java/org/apache/catalina/security/SecurityUtil.java
catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/security/SecurityListener.java
catch (NumberFormatException nfe) { log.warn(sm.getString("SecurityListener.checkUmaskParseFail", prop)); }
1667
error 512
                  
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException e) { log.error("Compilation error", e); }
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException exc) { log.error("Compilation error", exc); }
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) { log.error("Compilation error", exc); }
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (JasperException e) { log.error("Error visiting node", e); }
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException exc) { log.error("Compilation error", exc); }
// in java/org/apache/jasper/compiler/WebXml.java
catch (IOException e) { log.error(Localizer.getMessage( "jsp.error.stream.close.failed")); }
// in java/org/apache/jasper/compiler/JspReader.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.error("Exception parsing file ", ex); // Pop state being constructed: popFile(); err.jspError("jsp.error.file.cannot.read", file); }
// in java/org/apache/jasper/compiler/AntCompiler.java
catch (BuildException e) { be = e; log.error(Localizer.getMessage("jsp.error.javac"), e); log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString()); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); // Log any exception, since it can't be passed along log.error(Localizer.getMessage("jsp.error.file.not.found", e.getMessage()), t); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IllegalStateException ise) { log.error(Localizer.getMessage("jsp.error.file.not.found", jspUri)); }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } }
// in java/org/apache/jasper/security/SecurityClassLoad.java
catch (ClassNotFoundException ex) { log.error("SecurityClassLoad", ex); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().error(sm.getString( "abstractProtocolHandler.mbeanRegistrationFailed", tpOname, getName()), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.initError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.startError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.pauseError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.resumeError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.stopError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().error(sm.getString("abstractProtocolHandler.destroyError", getName()), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); // any other exception or error is odd. Here we log it // with "ERROR" level, so it will show up even on // less-than-verbose logs. getLog().error(sm.getString("ajpprotocol.proto.error"), e); }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (java.security.cert.CertificateException e) { getLog().error(sm.getString("ajpprocessor.certs.fail"), e); return; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (NoSuchProviderException e) { getLog().error(sm.getString("ajpprocessor.certs.fail"), e); return; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString( "http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.finish"), t); // 500 - Internal Server Error // Can't add a 500 to the access log since that has already been // written in the Adapter.service method. response.setStatus(500); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.response.finish"), t); error = true; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (Throwable x) { ExceptionUtils.handleThrowable(x); log.error("",x); continue; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch ( Throwable t ) { log.error("",t); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Exception x ) { log.error("Unable to set attribute \""+name+"\" to \""+value+"\"",x); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { log.error("",t); } catch (Throwable tt) { ExceptionUtils.handleThrowable(t); } // Tell to close the socket return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException x) { if (running) { log.error(sm.getString("endpoint.accept.fail"), x); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.accept.fail"), t); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception x) { log.error("", x); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable x ) { log.error("",x); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); if (log.isDebugEnabled()) log.error("",e); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { log.error(sm.getString( "endpoint.nio.selectorCloseFail"), ioe); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { log.error(sm.getString( "endpoint.nio.selectorCloseFail"), ioe); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable x) { ExceptionUtils.handleThrowable(x); log.error("",x); continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("",t); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable t ) { log.error("",t); cancelledKey(sk, SocketStatus.ERROR); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Exception x ) { log.error("",x); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; socket.getPoller().cancelledKey(key,SocketStatus.ERROR); releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable t ) { log.error("",t); socket.getPoller().cancelledKey(key,SocketStatus.ERROR); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Error e) { if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(sm.getString("endpoint.poll.limitedpollsize", "" + size)); return 0; } else { log.error(sm.getString("endpoint.poll.initfail"), e); return -1; } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (running) { String msg = sm.getString("endpoint.accept.fail"); if (t instanceof Error) { Error e = (Error) t; if (e.getError() == 233) { // Not an error on HP-UX so log as a warning // so it can be filtered out on that platform // See bug 50273 log.warn(msg, t); } else { log.error(msg, t); } } else { log.error(msg, t); } } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.poll.error"), t); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { // Pool not created so no need to destroy it. log.error(sm.getString("endpoint.sendfile.error"), e); data.socket = 0; return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { log.error(sm.getString("endpoint.sendfile.error"), e); Pool.destroy(data.fdpool); data.socket = 0; return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.poll.error"), t); }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
catch ( Exception x ) { getLog().error("Unable to set attribute \""+name+"\" to \""+value+"\"",x); return false; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (IOException x) { if (running) { log.error(sm.getString("endpoint.accept.fail"), x); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.accept.fail"), npe); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.accept.fail"), t); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Exception e) { log.error(sm.getString("endpoint.err.close"), e); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.err.unexpected"), t); // Close the socket return false; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (FileNotFoundException fnfe) { log.error(sm.getString("jsse.keystore_load_failed", type, path, fnfe.getMessage()), fnfe); throw fnfe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException ioe) { // Should never happen... log.error(sm.getString("parameters.copyFail"), ioe); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch(Exception ex) { log.error("Error sending notification " + name, ex); }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsSerSource.java
catch( Exception ex ) { log.error( "Error reading descriptors " + source + " " + ex.toString(), ex); throw ex; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java
catch (Exception e) { log.error("Error digesting Registry data", e); throw e; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsIntrospectionSource.java
catch( Exception ex ) { log.error( "Error reading descriptors ", ex); }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Throwable t ) { log.error( "Error unregistering mbean ", t); }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Exception ex) { log.error("Error registering " + oname, ex ); throw ex; }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch(Exception ex ) { log.error("Error loading " + dURL); }
// in java/org/apache/tomcat/util/digester/CallMethodRule.java
catch (ClassNotFoundException e) { // use the digester log digester.getLogger().error("(CallMethodRule) Cannot load class " + this.paramClassNames[i], e); this.paramTypes[i] = null; // Will cause NPE later }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); LogFactory.getLog("org.apache.tomcat.util.digester.Digester"). error("Unable to load property source["+className+"].",t); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Digester.getParser: ", e); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Finish event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Finish event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Body event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Body event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("End event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("End event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Begin event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Begin event threw error", e); throw e; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassCastException e) { log.error(sm.getString("contextConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString( "contextConfig.authenticatorInstantiate", authenticatorName), t); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.badUrl", defaultContextFile), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.badUrl", hostContextFile), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString("contextConfig.contextMissing", contextXml) , e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (SAXParseException e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); log.error(sm.getString("contextConfig.defaultPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.contextClose"), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString( "contextConfig.fixDocBase", context.getName()), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.webinfClassesUrl", resource), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (NamingException e) { log.error(sm.getString( "contextConfig.webinfClassesUrl", "/WEB-INF/classes"), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException ioe) { log.error(sm.getString( "contextConfig.servletContainerInitializerFail", url, context.getName())); ok = false; return; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassNotFoundException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (InstantiationException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IllegalAccessException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException ioe) { log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName())); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (URISyntaxException e) { log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName())); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.baseError"), e); return null; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (FileNotFoundException e) { log.error(sm.getString("contextConfig.altDDNotFound", altDDName)); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString("contextConfig.applicationUrl")); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString("contextConfig.applicationUrl")); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString( "contextConfig.defaultError", filename, file), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (SAXParseException e) { log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e); log.error(sm.getString("contextConfig.applicationPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (URISyntaxException e) { log.error(sm.getString("contextConfig.fileUrl", url), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamJar", entryName, url),e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.jarFile", url), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamJndi", url),e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.jndiUrl", url), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamFile", file.getAbsolutePath()),e); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (ClassCastException e) { log.error(sm.getString("tldConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/TldConfig.java
catch (Exception e) { log.error(sm.getString( "tldConfig.execute", context.getName()), e); }
// in java/org/apache/catalina/startup/EngineConfig.java
catch (ClassCastException e) { log.error(sm.getString("engineConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/HostConfig.java
catch (ClassCastException e) { log.error(sm.getString("hostConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.threaded.error"), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", contextXml.getAbsolutePath())); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployDescriptor.error", contextXml.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployWar.threaded.error"), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", war.getAbsolutePath())); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", war.getAbsolutePath())); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployWar.error", war.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDir.threaded.error"), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", xml)); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployDir.error", dir.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString("hostConfig.jmx.register", oname), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString("hostConfig.jmx.unregister", oname), e); }
// in java/org/apache/catalina/startup/WebRuleSet.java
catch (NoSuchMethodException e) { digester.getLogger().error("Can't find method " + method + " in " + top + " CLASS " + top.getClass()); return; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { log.error(sm.getString ("expandWar.copy", fileSrc, fileDest), e); result = false; }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { log.error("Catalina.stop: ", e); System.exit(1); }
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { log.error("Catalina.stop: ", e); }
// in java/org/apache/catalina/startup/Catalina.java
catch (IOException e) { log.error("Catalina.stop: ", e); System.exit(1); }
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) { throw new java.lang.Error(e); } else { log.error("Catalina.start", e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { log.error("Catalina.start: ", e); }
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { log.error("Catalina.stop", e); }
// in java/org/apache/catalina/startup/Catalina.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.error(sm.getString("catalina.shutdownHookFail"), ex); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (Throwable t) { handleThrowable(t); log.error("Class loader creation threw exception", t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Class loader creation threw exception", t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Exception creating instance of " + className, t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Exception locating main() method", t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error("Exception calling main() method", t); System.exit(1); }
// in java/org/apache/catalina/startup/UserConfig.java
catch (ClassCastException e) { log.error(sm.getString("hostConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/UserConfig.java
catch (Exception e) { host.getLogger().error(sm.getString("userConfig.database"), e); return; }
// in java/org/apache/catalina/startup/UserConfig.java
catch (Exception e) { host.getLogger().error(sm.getString("userConfig.deploy.threaded.error"), e); }
// in java/org/apache/catalina/startup/UserConfig.java
catch (Exception e) { host.getLogger().error(sm.getString("userConfig.error", user), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NamingException e) { log.error(" Resource '" + paths[i] + "' is missing"); return (true); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassCastException e) { log.error(" Failed tracking modifications of '" + getJarPath() + "' : " + e.getMessage()); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badKey", args[1]), e); args[2] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badValue", args[3]), e); args[4] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { if (System.getProperty("java.vendor").startsWith("Sun")) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } else { log.debug(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { log.error(sm.getString("webappClassLoader.readError", name), e); return null; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Exception e) { // Log and continue anyway, this is not critical log.error("Error registering jndi stream handler", e); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error( "LifecycleException ", t ); throw new LifecycleException("start: ", t); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Exception e) { log.error("LifecycleException ", e); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NumberFormatException e) { log.error(sm.getString("webappLoader.reloadable", event.getNewValue().toString())); }
// in java/org/apache/catalina/realm/CombinedRealm.java
catch (LifecycleException e) { // If realm doesn't start can't authenticate against it iter.remove(); log.error(sm.getString("combinedRealm.realmStartFail", realm.getClass().getName()), e); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Log the problem for posterity containerLog.error(sm.getString("jndiRealm.exception"), e); // Close the connection so that it gets reopened next time if (context != null) close(context); // Return "not authenticated" for this request if (containerLog.isDebugEnabled()) containerLog.debug("Returning null principal."); return (null); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (IOException e) { // Should never happen containerLog.error("Could not append password bytes to chunk: ", e); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { containerLog.error(sm.getString("jndiRealm.close"), e); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Log the problem for posterity containerLog.error(sm.getString("jndiRealm.exception"), e); // Close the connection so that it gets reopened next time if (context != null) close(context); // Return "not authenticated" for this request return (null); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (SQLException e) { containerLog.error("Exception committing connection before closing:", e); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (SQLException e) { containerLog.error(sm.getString("dataSourceRealm.close"), e); // Just log it here }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (Exception e) { // Log the problem for posterity containerLog.error(sm.getString("dataSourceRealm.exception"), e); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch(SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getPassword.exception", username)); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getPassword.exception", username)); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch(SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getRoles.exception", username)); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getRoles.exception", username)); }
// in java/org/apache/catalina/realm/UserDatabaseRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); containerLog.error(sm.getString("userDatabaseRealm.lookup", resourceName), e); database = null; }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (ClassNotFoundException e) { log.error("Class "+classNames[i]+" not found! Class not added."); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("jaasRealm.unexpectedError"), e); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("jaasRealm.unexpectedError"), e); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch( Throwable t) { log.error( "error ", t); return null; }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (Exception e) { log.error(sm.getString("realmBase.digest"), e); return (credentials); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { log.error("Couldn't get MD5 digest: ", e); throw new IllegalStateException(e.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch(Exception ex) { log.error(ex); return credentials; }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { // Log the problem for posterity containerLog.error(sm.getString("jdbcRealm.exception"), e); // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { // Log the problem for posterity containerLog.error(sm.getString("jdbcRealm.exception"), e); // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { // Log the problem for posterity containerLog.error(sm.getString("jdbcRealm.exception"), e); // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { containerLog.error(sm.getString("jdbcRealm.open"), e); }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
catch (NamingException e) { log.error("No global naming context defined for server"); return; }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
catch (NamingException e) { log.error("Exception processing Global JNDI Resources", e); }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
catch (Exception e) { log.error("Exception creating UserDatabase MBeans for " + name, e); }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
catch( RuntimeException ex) { log.error("RuntimeException " + ex); }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
catch( OperationNotSupportedException ex) { log.error("Operation not supported " + ex); }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (JMRuntimeException rme) { Throwable cause = rme.getCause(); if (cause instanceof UnsupportedOperationException) { if (log.isDebugEnabled()) { log.debug("Error getting attribute " + oname + " " + attName, rme); } } else if (cause instanceof NullPointerException) { if (log.isDebugEnabled()) { log.debug("Error getting attribute " + oname + " " + attName, rme); } } else { log.error("Error getting attribute " + oname + " " + attName, rme); } continue; }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Error getting attribute " + oname + " " + attName, t); continue; }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (RemoteException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.createRegistryFailed", serverName, Integer.toString(theRmiRegistryPort)), e); return null; }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (MalformedURLException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.invalidURL", serverName, url.toString()), e); return null; }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (IOException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.createServerFailed", serverName), e); }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (IOException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.destroyServerFailed", serverName),e); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch (Exception sx) { log.error("Unable to deserialize message:"+msg,sx); return; }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { log.error("Unable to find rpc channel, failed to send NoRpcChannelReply.",x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { log.error("Unable to send heartbeat through Tribes interceptor stack. Will try to sleep again.",x); }
// in java/org/apache/catalina/tribes/group/RpcChannel.java
catch ( Exception x ) { if (excallback != null && !asyncReply) { excallback.replyFailed(rmsg.message, reply, sender, x); } else { log.error("Unable to send back reply in RpcChannel.",x); } }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch (Exception x ) { log.error("Unable to perform failure detection check, assuming member down.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.error("Error processing coordination message. Could be fatal.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.error("Unable to start election when member was added.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.error("Unable to start election when member was removed.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( Exception x ){ log.error("Unable to perform heartbeat.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/FragmentationInterceptor.java
catch ( Exception x ) { if ( log.isErrorEnabled() ) { log.error("Unable to perform heartbeat clean up in the frag interceptor",x); } }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
catch ( IOException x ) { log.error("Unable to compress byte contents"); throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
catch ( IOException x ) { log.error("Unable to decompress byte contents",x); }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
catch ( Exception ex ) { log.error("Unable to report back completed message.",ex); }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
catch ( Exception x ) { ChannelException cx = null; if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException(x); if ( log.isDebugEnabled() ) log.debug("Error while processing async message.",x); try { if (link.getHandler() != null) link.getHandler().handleError(cx, new UniqueId(msg.getUniqueId())); } catch ( Exception ex ) { log.error("Unable to report back error message.",ex); } }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
catch ( Exception ex ) { log.error("Unable to report back error message.",ex); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.error("Unable to run replication listener.", x); }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch ( Exception x ) { log.error("Unable to service bio socket", x); }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch ( Exception x ) { if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(Constants.FAIL_ACK_COMMAND); log.error("Error thrown from messageDataReceived.",x); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch (IOException ioe) { log.error("Failed bind replication listener on address:"+ host, ioe); }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
catch ( Exception x ) { log.error("Unable to disconnect NioSender. msg="+x.getMessage()); if ( log.isDebugEnabled() ) log.debug("Unable to disconnect NioSender. msg="+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (Exception e) { //this is common, since the sockets on the other //end expire after a certain time. if ( e instanceof CancelledKeyException ) { //do nothing } else if ( e instanceof IOException ) { //dont spew out stack traces for IO exceptions unless debug is enabled. if (log.isDebugEnabled()) log.debug ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"].", e); else log.warn ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"]."); } else if ( log.isErrorEnabled() ) { //this is a real error, log it. log.error("Exception caught in TcpReplicationThread.drainChannel.",e); } cancelKey(key); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( RemoteProcessException e ) { if ( log.isDebugEnabled() ) log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( Exception e ) { log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (Exception x) { log.error("Error registering key for read:"+key,x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch ( Exception x ) { log.error("",x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } log.error("Unable to process request in NioReceiver", t); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.error("Unable to close cluster receiver selector.", x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.error("Unable to run replication listener.", x); }
// in java/org/apache/catalina/tribes/tipis/LazyReplicatedMap.java
catch ( ChannelException x ) { log.error("Unable to replicate backup key:"+key+" to backup:"+next+". Reason:"+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/tipis/LazyReplicatedMap.java
catch ( ChannelException x ) { //log the error, but proceed, this should only happen if a node went down, //and if the node went down, then it can't receive the message, the others //should still get it. log.error("Unable to replicate proxy key:"+key+" to backup:"+next+". Reason:"+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { log.error("Unable to diff object. Will replicate the entire object instead.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to replicate data.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to transfer LazyReplicatedMap state.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { log.error("Unable to transfer LazyReplicatedMap state.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ClassNotFoundException x) { log.error("Unable to transfer LazyReplicatedMap state.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x ) { log.error("Unable to deserialize MapMessage.",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ClassNotFoundException x ) { log.error("Unable to deserialize MapMessage.",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { log.error("Unable to deserialize MapMessage.", x); return; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ClassNotFoundException x) { log.error("Unable to deserialize MapMessage.", x); return; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (Exception x) { log.error("Unable to apply diff to key:" + entry.getKey(), x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to select backup node.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to relocate[" + entry.getKey() + "] to a new backup node", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to relocate[" + entry.getKey() + "] to a new backup node", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( Exception x ) { log.error("Unable to send AbstractReplicatedMap.ping message",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( ChannelException x ) { log.error("Unable to replicate out data for a LazyReplicatedMap.remove operation",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (Exception x) { log.error("Unable to replicate out data for a LazyReplicatedMap.get operation", x); return null; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to replicate out data for a LazyReplicatedMap.put operation", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( Exception x ) { log.error("Deserialization error of the MapMessage.key",x); return null; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( Exception x ) { log.error("Deserialization error of the MapMessage.value",x); return null; }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x ) { log.error("Unable to parse mcastTTL="+properties.getProperty("mcastTTL"),x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x ) { log.error("Unable to parse mcastSoTimeout="+properties.getProperty("mcastSoTimeout"),x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x) { log.error("Unable to stop the mcast service, level:"+svc+".",x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x ) { log.error("Unable to send payload update.",x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x ) { log.error("Unable to send domain update.",x); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (IOException iox) { log.error("Unable to join multicast group, make sure your system has multicasting enabled."); throw iox; }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } log.error("Unable to receive broadcast message.",t); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (Exception x) { log.error("Unable to process member disappeared message.", x); }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { error = true; log.error(sm.getString("standardManager.unloading.ioe", e), e); throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.unloading.ioe", e), e); try { oos.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardManager.managerLoad"), t); }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardManager.managerUnload"), t); }
// in java/org/apache/catalina/session/StoreBase.java
catch (IOException e) { manager.getContainer().getLogger().error("Error getting keys", e); return; }
// in java/org/apache/catalina/session/StoreBase.java
catch (Exception e) { manager.getContainer().getLogger().error("Session: "+keys[i]+"; ", e); try { remove(keys[i]); } catch (IOException e2) { manager.getContainer().getLogger().error("Error removing key", e2); } }
// in java/org/apache/catalina/session/StoreBase.java
catch (IOException e2) { manager.getContainer().getLogger().error("Error removing key", e2); }
// in java/org/apache/catalina/session/ManagerBase.java
catch (NumberFormatException e) { log.error(sm.getString("managerBase.sessionTimeout", event.getNewValue())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); keys = new String[0]; // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionSQLException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (NamingException e) { manager.getContainer().getLogger().error( sm.getString(getStoreName() + ".wrongDataSource", this.dataSourceName), e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (ClassNotFoundException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (InstantiationException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (IllegalAccessException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".commitSQLException"), e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".close", e.toString())); // Just log it here }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("checking isLoaded for id, " + id + ", "+e.getMessage(), e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); log.error("Exception clearing the Store: " + exception, exception); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("Exception clearing the Store: " + e, e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); log.error("Exception in the Store during load: " + exception, exception); return; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("Can't load sessions from store, " + e.getMessage(), e); return; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("Failed load session from store, " + e.getMessage(), e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); log.error("Exception in the Store during removeSession: " + exception, exception); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("Exception removing session " + e.getMessage(), e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (PrivilegedActionException ex) { Exception e = ex.getException(); log.error(sm.getString( "persistentManager.swapInException", id), e); if (e instanceof IOException){ throw (IOException)e; } else if (e instanceof ClassNotFoundException) { throw (ClassNotFoundException)e; } }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (ClassNotFoundException e) { String msg = sm.getString( "persistentManager.deserializeError", id); log.error(msg, e); throw new IllegalStateException(msg, e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException) { throw (IOException) exception; } log.error("Exception in the Store during writeSession: " + exception, exception); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error(sm.getString ("persistentManager.serializeError", session.getIdInternal(), e)); throw e; }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionCreated", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent( "afterSessionDestroyed", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Exception e) { manager.getContainer().getLogger().error( sm.getString("standardSession.logoutfail"), e); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t){ manager.getContainer().getLogger().error (sm.getString("standardSession.bindingEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.bindingEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { if (unbound != null) { context.fireContainerEvent( "afterSessionAttributeReplaced", listener); } else { context.fireContainerEvent("afterSessionAttributeAdded", listener); } } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionAttributeRemoved", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { // Log the problem for posterity container.getLogger().error(sm.getString("jdbcAccessLogValve.exception"), e); // Close the connection so that it gets reopened next time if (conn != null) { close(); } }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { container.getLogger().error(sm.getString("jdbcAccessLogValeve.close"), e); // Just log it here }
// in java/org/apache/catalina/valves/SSLValve.java
catch (NoSuchProviderException e) { log.error(sm.getString( "sslValve.invalidProvider", providerName), e); }
// in java/org/apache/catalina/valves/PersistentValve.java
catch (Exception e) { container.getLogger().error("deserializeError"); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("accessLogValve.rotateFail"), e); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (UnsupportedEncodingException ex) { log.error(sm.getString( "accessLogValve.unsupportedEncoding", encoding), ex); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (IOException e) { writer = null; currentLogFile = null; log.error(sm.getString("accessLogValve.openFail", pathname), e); }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
catch (IOException e) { log.error("parse error", e); return null; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (LoginException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (PrivilegedActionException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail", e)); response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
// in java/org/apache/catalina/ha/context/ReplicatedContext.java
catch ( Exception x ) { log.error("Unable to start ReplicatedContext",x); throw new LifecycleException("Failed to start ReplicatedContext",x); }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (Exception ex) { log.error("Unable to connect to proxy: " + ex); close(i); }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (Exception ex) { log.error("Unable to send collected load information to proxy: " + ex); close(i); }
// in java/org/apache/catalina/ha/backend/HeartbeatListener.java
catch (Exception ex) { log.error("Unable to initialize info collection: " + ex); coll = null; return; }
// in java/org/apache/catalina/ha/backend/HeartbeatListener.java
catch (Exception ex) { log.error("Unable to initialize Sender: " + ex); sender = null; return; }
// in java/org/apache/catalina/ha/backend/HeartbeatListener.java
catch (Exception ex) { log.error("Unable to collect load information: " + ex); coll = null; return; }
// in java/org/apache/catalina/ha/backend/HeartbeatListener.java
catch (Exception ex) { log.error("Unable to send colllected load information: " + ex); }
// in java/org/apache/catalina/ha/backend/MultiCastSender.java
catch (Exception ex) { log.error("Unable to use multicast: " + ex); s = null; return -1; }
// in java/org/apache/catalina/ha/backend/MultiCastSender.java
catch (Exception ex) { log.error("Unable to send colllected load information: " + ex); s.close(); s = null; return -1; }
// in java/org/apache/catalina/ha/session/SerializablePrincipal.java
catch (ClassNotFoundException e) { log.error(sm.getString( "serializablePrincipal.readPrincipal.cnfe"), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaSession.java
catch (NotSerializableException e) { log.error(sm.getString("standardSession.notSerializable",saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); log.error(" storing attribute '" + saveNames.get(i)+ "' with value NOT_SERIALIZED"); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
catch ( Exception x ) { log.error("Unable to remove element:",x); info = new AttributeInfo(type, action, name, value); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
catch ( Exception x ) { log.error("Unable to remove element",x); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
catch ( Exception x ) { log.error("Unable to remove element",x); info = new AttributeInfo(); }
// in java/org/apache/catalina/ha/session/BackupManager.java
catch ( Exception x ) { log.error(sm.getString("backupManager.startUnable", getName()),x); throw new LifecycleException(sm.getString("backupManager.startFailed", getName()),x); }
// in java/org/apache/catalina/ha/session/JvmRouteSessionIDBinderListener.java
catch (IOException e) { log.error(e); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.unableSerializeSessionID", newSessionID), e); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("deltaManager.loading.cnfe", e), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.loading.ioe", e), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.unloading.ioe", e), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("deltaManager.managerLoad"), t); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException x) { log.error(sm.getString("deltaManager.createMessage.unableCreateDeltaRequest",sessionId), x); return null; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Exception x) { log.error(sm.getString("deltaManager.receiveMessage.error",getName()), x); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOnListener.java
catch (IOException io) { log.error("Session doesn't exist:" + io); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOnListener.java
catch (IOException io) { log.error("Session doesn't exist:" + io); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception e) { log.error(sm.getString("farmWarDeployer.mbeanNameFail", engine.getName(), hostname),e); return; }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception ex) { log.error(ex); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception ex) { log.error(ex); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (java.io.IOException x) { log.error(sm.getString("farmWarDeployer.msgIoe"), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception ex) { log.error(sm.getString("farmWarDeployer.removeFailLocal", contextName), ex); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception x) { log.error(sm.getString("farmWarDeployer.modRemoveFail"), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception x) { log.error(sm.getString("farmWarDeployer.modInstallFail"), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception x) { log.error(sm.getString("farmWarDeployer.removeLocalFail"), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (IOException e) { log.error(sm.getString("farmWarDeployer.fileCopyFail", from, to), e); return false; }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to clone cluster manager, defaulting to org.apache.catalina.ha.session.DeltaManager", x); manager = new org.apache.catalina.ha.session.DeltaManager(); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to start cluster.", x); throw new LifecycleException(x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to stop cluster valve.", x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to send message through cluster sender.", x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to connect to replication system.", x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable remove cluster node from replication system.", x); }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
catch (PatternSyntaxException pse) { log.error(sm.getString("ReplicationValve.filter.failure", filter), pse); }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
catch (Exception x) { // FIXME we have a lot of sends, but the trouble with one node stops the correct replication to other nodes! log.error(sm.getString("ReplicationValve.send.failure"), x); }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
catch ( Exception x ) { log.error(sm.getString("ReplicationValve.send.invalid.failure",invalidIds[i]),x); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { log.error(sm.getString( "coyoteConnector.protocolHandlerInstantiationFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { log.error(sm.getString ("coyoteConnector.protocolHandlerPauseFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { log.error(sm.getString ("coyoteConnector.protocolHandlerResumeFailed"), e); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (!(t instanceof IOException)) { log.error(sm.getString("coyoteAdapter.service"), t); } error = true; return false; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); success = false; log.error(sm.getString("coyoteAdapter.service"), t); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException e) { // Ignore log.error("Invalid URI encoding; using HTTP default"); connector.setURIEncoding(null); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException e) { log.error("Invalid URI character encoding; trying ascii"); cc.recycle(); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error(sm.getString("aprListener.sslInit"), t); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error( sm.getString("standardWrapper.allocateException", wrapper.getName()), e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch(Exception ex) { log.error(sm.getString( "applicationFilterConfig.jmxUnregisterFail", getFilterClass(), getFilterName()), ex); }
// in java/org/apache/catalina/core/StandardHost.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString( "standardHost.invalidErrorReportValveClass", errorValve), t); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setLoader: stop: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setLoader: start: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setManager: stop: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setManager: start: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setCluster: stop: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setCluster: start: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setRealm: stop: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setRealm: start: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.addChild: start: ", e); throw new IllegalStateException ("ContainerBase.addChild: start: " + e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.removeChild: stop: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.removeChild: destroy: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.error(sm.getString("containerBase.threadedStartFailed"), e); fail = true; }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.error(sm.getString("containerBase.threadedStopFailed"), e); fail = true; }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Exception invoking periodic operation: ", t); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedServletsResource"), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedListenersResources"), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedServletsResources"), e); }
// in java/org/apache/catalina/core/StandardContextValve.java
catch (IOException ioe) { container.getLogger().error(sm.getString( "standardContextValve.acknowledgeException"), ioe); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { log.error("StandardServer.await: create[" + address + ":" + port + "]: ", e); return; }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { if (stopAwait) { // Wait was aborted with socket.close() break; } log.error("StandardServer.await: accept: ", e); break; }
// in java/org/apache/catalina/core/StandardServer.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(t); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error (sm.getString("naming.namingContextCreationFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NumberFormatException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", env.getName())); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (IllegalArgumentException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", env.getName())); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { logger.error(sm.getString("naming.wsdlFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { logger.error(sm.getString("naming.wsdlFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException e) { log.error(sm.getString( "standardService.connector.startFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException e) { log.error(sm.getString( "standardService.connector.stopFailed", connectors[j]), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException x) { log.error("Executor.start", x); }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException e) { log.error("Executor.stop", e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.startFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.pauseFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.stopFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { String message = sm.getString( "standardService.connector.initFailed", connector); log.error(message, e); if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) throw new LifecycleException(message); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.destroyfailed", connector), e); }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // Report our failure to process this custom page container.getLogger().error("Exception Processing " + errorPage, t); return (false); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.error( sm.getString("standardContext.stoppingContext", getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.error( sm.getString("standardContext.startingContext", getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.filterStart", name), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.applicationListener", listeners[i]), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextInitialized", listener); getLogger().error (sm.getString("standardContext.listenerStart", instances[i].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextDestroyed", listener); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardContext.resourcesStart"), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardContext.resourcesStop"), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (ServletException e) { getLogger().error(sm.getString("standardWrapper.loadException", getName()), StandardWrapper.getRootCause(e)); // NOTE: load errors (including a servlet that throws // UnavailableException from tht init() method) are NOT // fatal to application startup }
// in java/org/apache/catalina/core/StandardContext.java
catch (IllegalArgumentException e) { log.error("Error initializing resources: " + e.getMessage()); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException ioe) { log.error("Error in dependencyCheck", ioe); dependencyCheck = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Exception ex) { log.error("standardContext.clusterFail", ex); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch(Exception e) { log.error("Error manager.start()", e); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch( Exception ex ) { log.error( "Error reseting context " + this + " " + ex, ex ); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[i].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[j].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (LifecycleException e) { log.error("StandardPipeline.setBasic: stop", e); }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (LifecycleException e) { log.error("StandardPipeline.setBasic: start", e); return; }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (LifecycleException e) { log.error("StandardPipeline.addValve: start: ", e); }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (LifecycleException e) { log.error("StandardPipeline.removeValve: stop: ", e); }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (LifecycleException e) { log.error("StandardPipeline.removeValve: destroy: ", e); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servlet = null; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); ioException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (UnavailableException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); servletException = e; wrapper.unavailable(e); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause); } servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); runtimeException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e); // FIXME: Exception handling needs to be similar to what is in the StandardWrapperValue }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { if (System.getProperty("java.vendor").startsWith( "Sun")) { log.error(sm.getString( "jreLeakListener.gcDaemonFail"), e); } else { log.debug(sm.getString( "jreLeakListener.gcDaemonFail"), e); } }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (SecurityException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (NoSuchMethodException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalArgumentException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalAccessException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (MalformedURLException e) { log.error(sm.getString( "jreLeakListener.jarUrlConnCacheFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IOException e) { log.error(sm.getString( "jreLeakListener.jarUrlConnCacheFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ParserConfigurationException e) { log.error(sm.getString("jreLeakListener.xmlParseFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { if (System.getProperty("java.vendor").startsWith( "Sun")) { log.error(sm.getString( "jreLeakListener.ldapPoolManagerFail"), e); } else { log.debug(sm.getString( "jreLeakListener.ldapPoolManagerFail"), e); } }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { log.error( sm.getString("jreLeakListener.classToInitializeFail", classNameToLoad), e); // continue with next class to load }
// in java/org/apache/catalina/core/ThreadLocalLeakPreventionListener.java
catch (Exception e) { String msg = sm.getString( "threadLocalLeakPreventionListener.lifecycleEvent.error", event); log.error(msg, e); }
// in java/org/apache/catalina/core/ThreadLocalLeakPreventionListener.java
catch (Exception e) { String msg = sm.getString( "threadLocalLeakPreventionListener.containerEvent.error", event); log.error(msg, e); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (Exception e) { log.error(sm.getString("sessionIdGenerator.random", secureRandomClass), e); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (NoSuchAlgorithmException e) { log.error(sm.getString("sessionIdGenerator.randomAlgorithm", secureRandomAlgorithm), e); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (NoSuchProviderException e) { log.error(sm.getString("sessionIdGenerator.randomProvider", secureRandomProvider), e); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (NoSuchAlgorithmException e) { log.error(sm.getString("sessionIdGenerator.randomAlgorithm", secureRandomAlgorithm), e); }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (IOException e) { log.error(sm.getString ("extensionValidator.failload", item), e); }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (IOException e) { log.error (sm.getString ("extensionValidator.failload", files[i]), e); }
637
handleThrowable
273
                  
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JspException(e.getMessage(), t); }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn("Error processing preDestroy on tag instance of " + handler.getClass().getName(), t); }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn("Error processing preDestroy on tag instance of " + handler.getClass().getName(), t); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException ("error in invoking method", ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspFactoryImpl.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.fatal("Exception initializing page context", ex); return null; }
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/jasper/compiler/ParserController.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/jasper/compiler/Localizer.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); t.printStackTrace(); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/jasper/compiler/JspReader.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.error("Exception parsing file ", ex); // Pop state being constructed: popFile(); err.jspError("jsp.error.file.cannot.read", file); }
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); jsw.getServletContext().log("Background compile failed", t); }
// in java/org/apache/jasper/servlet/JspCServletContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (null); }
// in java/org/apache/jasper/servlet/JspCServletContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); url = null; }
// in java/org/apache/jasper/servlet/JspCServletContext.java
catch (Throwable t2) { ExceptionUtils.handleThrowable(t2); }
// in java/org/apache/jasper/servlet/JspCServletContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (null); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JasperException(t); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); // Log any exception, since it can't be passed along log.error(Localizer.getMessage("jsp.error.file.not.found", e.getMessage()), t); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); // Need to localize this. log.warn("Failed to load engineOptionsClass", e); // Use the default Options implementation options = new EmbeddedServletOptions(config, context); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException(e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); // any other exception or error is odd. Here we log it // with "ERROR" level, so it will show up even on // less-than-verbose logs. getLog().error(sm.getString("ajpprotocol.proto.error"), e); }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), t); } // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug(sm.getString( "http11processor.request.prepare"), t); } // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString( "http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.finish"), t); // 500 - Internal Server Error // Can't add a 500 to the access log since that has already been // written in the Adapter.service method. response.setStatus(500); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.response.finish"), t); error = true; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error t.printStackTrace(); response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (Throwable x) { ExceptionUtils.handleThrowable(x); log.error("",x); continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); System.err.println(oomParachuteMsg); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { log.error("",t); } catch (Throwable tt) { ExceptionUtils.handleThrowable(t); } // Tell to close the socket return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable tt) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable oomt ) { try { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.accept.fail"), t); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); if (log.isDebugEnabled()) log.error("",e); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable x) { ExceptionUtils.handleThrowable(x); log.error("",x); continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("",t); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; socket.getPoller().cancelledKey(key,SocketStatus.ERROR); releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { if (step == 2) { log.debug(sm.getString("endpoint.err.handshake"), t); } else { log.debug(sm.getString("endpoint.err.unexpected"), t); } } // Tell to close the socket return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (running) { String msg = sm.getString("endpoint.accept.fail"); if (t instanceof Error) { Error e = (Error) t; if (e.getError() == 233) { // Not an error on HP-UX so log as a warning // so it can be filtered out on that platform // See bug 50273 log.warn(msg, t); } else { log.error(msg, t); } } else { log.error(msg, t); } } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.poll.error"), t); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.poll.error"), t); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.accept.fail"), t); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.err.handshake"), t); } // Tell to close the socket state = SocketState.CLOSED; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.err.unexpected"), t); // Close the socket return false; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); if (log.isDebugEnabled()) log.debug("IntrospectionUtils: InvocationTargetException for " + o.getClass() + " " + name + "=" + value + ")", ie); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); if (log.isDebugEnabled()) log.debug("IntrospectionUtils: InvocationTargetException for " + o.getClass() + " " + name + ")"); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); LogFactory.getLog("org.apache.tomcat.util.digester.Digester"). error("Unable to load property source["+className+"].",t); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString( "contextConfig.authenticatorInstantiate", authenticatorName), t); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), t); return null; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployDescriptor.error", contextXml.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployWar.error", war.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployDir.error", dir.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString ("hostConfig.context.remove", app.name), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString ("hostConfig.context.remove", app.name), t); }
// in java/org/apache/catalina/startup/CatalinaProperties.java
catch (Throwable t) { handleThrowable(t); }
// in java/org/apache/catalina/startup/CatalinaProperties.java
catch (Throwable t) { handleThrowable(t); }
// in java/org/apache/catalina/startup/CatalinaProperties.java
catch (Throwable t) { handleThrowable(t); }
// in java/org/apache/catalina/startup/CatalinaProperties.java
catch (Throwable t) { handleThrowable(t); error = t; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/Catalina.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This will fail on JDK 1.2. Ignoring, as Tomcat can run // fine without the shutdown hook. }
// in java/org/apache/catalina/startup/Catalina.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.error(sm.getString("catalina.shutdownHookFail"), ex); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (Throwable t) { handleThrowable(t); log.error("Class loader creation threw exception", t); System.exit(1); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (Throwable t) { handleThrowable(t); t.printStackTrace(); return; }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (Throwable t) { // Unwrap the Exception for clearer error reporting if (t instanceof InvocationTargetException && t.getCause() != null) { t = t.getCause(); } handleThrowable(t); t.printStackTrace(); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Class loader creation threw exception", t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Exception creating instance of " + className, t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Exception locating main() method", t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error("Exception calling main() method", t); System.exit(1); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.jdbcRemoveFailed", contextName), t); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in class " + clazz.getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not clean fields for class " + clazz.getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in object instance of class " + instance.getClass().getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.stopTimerThreadFail", thread.getName(), contextName), t); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This is likely a dual registration log.info("Dual registration of jndi stream handler: " + t.getMessage()); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error( "LifecycleException ", t ); throw new LifecycleException("start: ", t); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch( Exception ex ) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) log.debug("getClasspath ", ex); }
// in java/org/apache/catalina/realm/UserDatabaseRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); containerLog.error(sm.getString("userDatabaseRealm.lookup", resourceName), e); database = null; }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("jaasRealm.unexpectedError"), e); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("jaasRealm.unexpectedError"), e); return (null); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Error getting attribute " + oname + " " + attName, t); continue; }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); sb.append("NON-STRINGABLE VALUE"); }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/StatusTransformer.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.install[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.reload[" + cn.getDisplayName() + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.resources[" + type + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.resources[" + type + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log("ManagerServlet.serverinfo",t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.sessions[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log(sm.getString("managerServlet.startFailed", displayPath), t); writer.println(smClient.getString("managerServlet.startFailed", displayPath)); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.stop[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.undeploy[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/util/SessionUtils.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); // stay silent }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardManager.managerLoad"), t); }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardManager.managerUnload"), t); }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionCreated", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent( "afterSessionDestroyed", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.bindingEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { if (unbound != null) { context.fireContainerEvent( "afterSessionAttributeReplaced", listener); } else { context.fireContainerEvent("afterSessionAttributeAdded", listener); } } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionAttributeRemoved", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (Throwable tt) { ExceptionUtils.handleThrowable(tt); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("status.setContentType", t); } }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("accessLogValve.rotateFail"), e); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.info(sm.getString("accessLogValve.closeFail"), e); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); init = "127.0.0.1"; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* Log error */ return "-"; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); value = "localhost"; }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardLoginFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardErrorFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (InvocationTargetException e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), t); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("deltaManager.managerLoad"), t); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOn.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new LifecycleException( "ClusterSingleSignOn exception during clusterLoad " + t); }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
catch (Throwable ignore) { ExceptionUtils.handleThrowable(ignore); }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
catch (Throwable ignore) { ExceptionUtils.handleThrowable(ignore); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("coyoteRequest.sessionEndAccessFail"), t); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (!(t instanceof IOException)) { log.error(sm.getString("coyoteAdapter.service"), t); } error = true; return false; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); success = false; log.error(sm.getString("coyoteAdapter.service"), t); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("coyoteAdapter.accesslogFail"), t); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error(sm.getString("aprListener.sslInit"), t); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.info(sm.getString("aprListener.aprDestroy")); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.info(sm.getString("aprListener.aprInit", System.getProperty("java.library.path"))); return; }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); }
// in java/org/apache/catalina/core/StandardHost.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString( "standardHost.invalidErrorReportValveClass", errorValve), t); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (null); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.fireContainerEvent("afterContextAttributeRemoved", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (replaced) context.fireContainerEvent("afterContextAttributeReplaced", listener); else context.fireContainerEvent("afterContextAttributeAdded", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Exception invoking periodic operation: ", t); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); ServletException se = new ServletException(e); throw se; }
// in java/org/apache/catalina/core/JasperListener.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // Should not occur, obviously log.warn("Couldn't initialize Jasper", t); }
// in java/org/apache/catalina/core/ApplicationFilterFactory.java
catch (Exception e) { // Note: The try catch is there because getFilter has a lot of // declared exceptions. However, the filter is allocated much // earlier Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/StandardServer.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(t); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch(Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof MalformedURLException){ throw (MalformedURLException)t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch(Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage(), t); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); throwable(request, response, t); }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // Report our failure to process this custom page container.getLogger().error("Exception Processing " + errorPage, t); return (false); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); this.charsetMapper = new CharsetMapper(); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.filterStart", name), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.applicationListener", listeners[i]), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextInitialized", listener); getLogger().error (sm.getString("standardContext.listenerStart", instances[i].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextDestroyed", listener); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardContext.resourcesStart"), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardContext.resourcesStop"), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[i].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[j].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (false); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servlet = null; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e); // FIXME: Exception handling needs to be similar to what is in the StandardWrapperValue }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/org/apache/catalina/util/CharsetMapper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new IllegalArgumentException(t.toString()); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.startFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.stopFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/util/ServerInfo.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/security/SecurityUtil.java
catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
273
warn 189
                  
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn("Error processing preDestroy on tag instance of " + handler.getClass().getName(), t); }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn("Error processing preDestroy on tag instance of " + handler.getClass().getName(), t); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (writer != null) { try { writer.close(); writer = null; } catch (Exception e1) { // do nothing } } // Remove the generated .java file File file = new File(javaFileName); if (file.exists()) { if (!file.delete()) { log.warn(Localizer.getMessage( "jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath())); } } throw e; }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { // Remove as much as possible, log possible exceptions log.warn(Localizer.getMessage("jsp.warning.compiler.classfile.delete.fail.unknown"), e); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { // Remove as much as possible, log possible exceptions log.warn(Localizer.getMessage("jsp.warning.compiler.classfile.delete.fail.unknown"), e); }
// in java/org/apache/jasper/compiler/WebXml.java
catch (MalformedURLException e) { log.warn(Localizer.getMessage( "jsp.error.internal.filenotfound", altDDName)); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); // Need to localize this. log.warn("Failed to load engineOptionsClass", e); // Use the default Options implementation options = new EmbeddedServletOptions(config, context); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (InstantiationException e) { log.warn(Localizer.getMessage("jsp.error.compiler"), e); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (IllegalAccessException e) { log.warn(Localizer.getMessage("jsp.error.compiler"), e); }
// in java/org/apache/jasper/JspC.java
catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.checkInterval")); } }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval")); } }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.maxLoadedJsps", ""+this.maxLoadedJsps)); } }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.jspIdleTimeout", ""+this.jspIdleTimeout)); } }
// in java/org/apache/naming/NamingContext.java
catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); }
// in java/org/apache/naming/resources/WARDirContext.java
catch (IOException e) { log.warn ("Exception closing WAR File " + base.getName(), e); }
// in java/org/apache/naming/resources/BaseDirContext.java
catch (IOException ioe) { log.warn(sm.getString("resources.addResourcesJarFail", url), ioe); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().warn("Error registering request"); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().warn("Error unregistering request", e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (IOException ioe) { log.warn(sm.getString("http11processor.socket.sslreneg",ioe)); }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11Processor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11Processor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/AbstractHttp11Protocol.java
catch (Exception ex) { getLog().warn("Failed to init light protocol " + impl, ex); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (RejectedExecutionException rx) { log.warn("Socket processing request was rejected for:"+socket,rx); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for: "+socket, x); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (running) { String msg = sm.getString("endpoint.accept.fail"); if (t instanceof Error) { Error e = (Error) t; if (e.getError() == 233) { // Not an error on HP-UX so log as a warning // so it can be filtered out on that platform // See bug 50273 log.warn(msg, t); } else { log.error(msg, t); } } else { log.error(msg, t); } } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket reprocessing request was rejected for:"+socket,x); try { //unable to handle connection at this time handler.process(socket, SocketStatus.DISCONNECT); } finally { countDownConnection(); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); return false; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { Throwable cause = ioe.getCause(); if (cause instanceof UnrecoverableKeyException) { // Log a warning we had a password issue log.warn(sm.getString("jsse.invalid_truststore_password"), cause); // Re-try trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, null); } else { // Something else went wrong - re-throw throw ioe; } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception ex) { log.warn("Bad maxCertLength: "+trustLength); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
catch (IOException e) { log.warn(sm.getString("c2bConverter.recycleFailed"), e); try { init(); } catch (IOException ignore) { // Should never happen since this means encoding is invalid and // in that case, the constructor will have failed. } }
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
catch (IOException e) { log.warn(sm.getString("jarScan.webinflibFail", url), e); }
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
catch (IOException ioe) { log.warn(sm.getString( "jarScan.classloaderFail",urls[i]), ioe); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalArgumentException ex2) { log.warn("IAE " + o + " " + name + " " + value, ex2); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalArgumentException ex2) { log.warn("IAE " + o + " " + name, ex2); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.webxmlFail", resourcePath, descriptor.getTaglibURI()), ioe); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.webinfFail", path), ioe); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.dirFail", fileList[i].getAbsolutePath()), ioe); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.jarFail", jarConn.getURL()), ioe); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString ("hostConfig.context.remove", app.name), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { log.warn(sm.getString ("hostConfig.canonicalizing", app.name), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString ("hostConfig.context.remove", app.name), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { log.warn(sm.getString ("hostConfig.canonicalizing", app.name), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { log.warn(sm.getString ("hostConfig.canonicalizing", app.name), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.warn(sm.getString ("hostConfig.context.restart", app.name), e); }
// in java/org/apache/catalina/startup/Catalina.java
catch (SAXParseException spe) { log.warn("Catalina.start using " + getConfigFile() + ": " + spe.getMessage()); return; }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { log.warn("Catalina.start using " + getConfigFile() + ": " , e); return; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.jdbcRemoveFailed", contextName), t); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { log.warn(sm.getString( "webappClassLoader.jdbcRemoveStreamError", contextName), ioe); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.stopTimerThreadFail", thread.getName(), contextName), t); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (InvocationTargetException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchMethodException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/realm/MemoryRealm.java
catch (Exception e) { log.warn(sm.getString("memoryRealm.xmlFeatureEncoding"), e); }
// in java/org/apache/catalina/realm/CombinedRealm.java
catch (GSSException e) { log.warn(sm.getString("realmBase.gssNameFail"), e); return null; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NullPointerException e) { /* BZ 42449 - Kludge Sun's LDAP provider with broken SSL */ // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (CommunicationException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (InvalidNameException ine) { // Log the problem for posterity containerLog.warn(sm.getString("jndiRealm.exception"), ine); // ignore; this is probably due to a name not fitting // the search path format exactly, as in a fully- // qualified name being munged into a search path // that already contains cn= or vice-versa }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (CommunicationException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (Exception e) { connectionAttempt = 1; // log the first exception. containerLog.warn(sm.getString("jndiRealm.exception"), e); // Try connecting to the alternate url. context = new InitialDirContext(getDirectoryContextEnvironment()); }
// in java/org/apache/catalina/realm/LockOutRealm.java
catch (GSSException e) { log.warn(sm.getString("realmBase.gssNameFail"), e); return null; }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (LoginException e) { log.warn(sm.getString("jaasRealm.loginException", username), e); return (null); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (GSSException e) { log.warn(sm.getString("realmBase.gssNameFail"), e); }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (Exception e) { log.warn("Error processing configuration file " + file.getAbsolutePath(), e); return; }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { containerLog.warn(sm.getString("jdbcRealm.close"), e); // Just log it here }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
catch (Exception e) { log.warn("Error during context [" + context.getName() + "] destroy ", e); }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
catch (Exception e) { log.warn(sm.getString("memoryUserDatabase.xmlFeatureEncoding"), e); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { //this could be the channel listener throwing an exception, we should log it //as a warning. if ( log.isWarnEnabled() ) log.warn("Error receiving message:",x); throw new RemoteProcessException("Exception:"+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpPingInterceptor.java
catch (ChannelException x) { log.warn("Unable to send TCP ping.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpPingInterceptor.java
catch ( Exception x ) { log.warn("Unable to send ping from TCP ping thread.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( Exception x ) { log.warn("Unable to perform heartbeat on the TcpFailureDetector.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/TwoPhaseCommitInterceptor.java
catch ( Exception x ) { log.warn("Unable to perform heartbeat on the TwoPhaseCommit interceptor.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.warn("Unable to send election message to:"+msg.getMembers()[current]); current = Arrays.nextIndex(msg.getMembers()[current],msg.getMembers()); if ( current == next ) throw x; }
// in java/org/apache/catalina/tribes/io/BufferPool.java
catch ( Throwable x ) { log.warn("Unable to initilize BufferPool, not pooling XByteBuffer objects:"+x.getMessage()); if ( log.isDebugEnabled() ) log.debug("Unable to initilize BufferPool, not pooling XByteBuffer objects:",x); }
// in java/org/apache/catalina/tribes/io/ObjectReader.java
catch ( IOException x ) { //unable to get buffer size log.warn("Unable to retrieve the socket receiver buffer size, setting to default 43800 bytes."); this.buffer = new XByteBuffer(43800,true); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch ( java.io.IOException x ) { log.warn("Unable to send ACK back through channel, channel disconnected?: "+x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( Exception x ) { log.warn("Error during keepalive test for sender:"+sender,x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (Exception e) { //this is common, since the sockets on the other //end expire after a certain time. if ( e instanceof CancelledKeyException ) { //do nothing } else if ( e instanceof IOException ) { //dont spew out stack traces for IO exceptions unless debug is enabled. if (log.isDebugEnabled()) log.debug ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"].", e); else log.warn ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"]."); } else if ( log.isErrorEnabled() ) { //this is a real error, log it. log.error("Exception caught in TcpReplicationThread.drainChannel.",e); } cancelKey(key); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( java.io.IOException x ) { log.warn("Unable to send ACK back through channel, channel disconnected?: "+x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (java.nio.channels.CancelledKeyException nx) { log.warn("Replication client disconnected, error when polling key. Ignoring client."); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch ( IOException ignore ){ if (log.isWarnEnabled()) { log.warn("Unable to cleanup on selector close.",ignore); } }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.warn("Unable to send map start message."); // remove listener from channel this.rpcChannel.breakdown(); this.channel.removeChannelListener(this); this.channel.removeMembershipListener(this); throw new RuntimeException("Unable to start replicated map.",x); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception x ) { if (x instanceof InterruptedException) interrupted(); else { if (errorCounter==0 && doRunReceiver) log.warn("Error receiving mcast package. Sleeping 500ms",x); else if (log.isDebugEnabled()) log.debug("Error receiving mcast package"+(doRunReceiver?". Sleeping 500ms":"."),x); if (doRunReceiver) { try { Thread.sleep(500); } catch ( Exception ignore ){} if ( (++errorCounter)>=recoveryCounter ) { errorCounter=0; RecoveryThread.recover(McastServiceImpl.this); } } } }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception x ) { if (errorCounter==0) log.warn("Unable to send mcast message.",x); else log.debug("Unable to send mcast message.",x); if ( (++errorCounter)>=recoveryCounter ) { errorCounter=0; RecoveryThread.recover(McastServiceImpl.this); } }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (Exception x) { log.warn("Recovery thread failed to stop membership service.", x); return false; }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (Exception x) { log.warn("Recovery thread failed to start membership service.", x); return false; }
// in java/org/apache/catalina/session/StandardSession.java
catch (NotSerializableException e) { manager.getContainer().getLogger().warn (sm.getString("standardSession.notSerializable", saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug (" storing attribute '" + saveNames.get(i) + "' with value NOT_SERIALIZED"); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (Exception e) { container.getLogger().warn( sm.getString("cometConnectionManagerValve.event"), e); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (IOException e) { container.getLogger().warn(sm.getString( "cometConnectionManagerValve.event"), e); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (Exception e) { req.getWrapper().getParent().getLogger().warn(sm.getString( "cometConnectionManagerValve.listenerEvent"), e); }
// in java/org/apache/catalina/valves/SSLValve.java
catch (java.security.cert.CertificateException e) { log.warn(sm.getString("sslValve.certError", strcerts), e); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardLoginFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardErrorFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", environment.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", resource.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", resourceLink.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", environment.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", resource.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", resourceLink.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", cr.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", ce.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", crl.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (NamingException e) { log.warn(sm.getString("namingResources.cleanupNoContext", container), e); return; }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (NamingException e) { log.warn(sm.getString( "namingResources.cleanupNoResource", cr.getName(), container), e); continue; }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (IllegalArgumentException e) { log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (IllegalAccessException e) { log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (InvocationTargetException e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), t); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", crl.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", ce.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", cr.getName()), e); }
// in java/org/apache/catalina/deploy/WebXml.java
catch (NumberFormatException nfe) { log.warn(sm.getString("webXml.version.nfe", major, version), nfe); majorVersion = 0; }
// in java/org/apache/catalina/deploy/WebXml.java
catch (NumberFormatException nfe) { log.warn(sm.getString("webXml.version.nfe", minor, version), nfe); minorVersion = 0; }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
catch (Exception x) { log.warn("Unable to load meta data for class:"+clazz.getName()); return false; }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
catch ( Exception x ) { log.warn("Unable to register default cluster implementation with JMX",x); return false; }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
catch ( Exception x ) { log.warn("Unable to unregister default cluster implementation with JMX",x); return false; }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("coyoteRequest.sessionEndAccessFail"), t); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("coyoteAdapter.accesslogFail"), t); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (UnsupportedEncodingException e1) { log.warn(sm.getString("coyoteAdapter.parsePathParam", enc)); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.cluster", cluster), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.loader", loader), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.manager", manager), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.realm", realm), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.valve", current), e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IOException ioe) { log.warn("onComplete() failed for listener of type [" + listener.getClass().getName() + "]", ioe); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IOException ioe) { log.warn("onStartAsync() failed for listener of type [" + listener.getClass().getName() + "]", ioe); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IOException ioe) { log.warn("onStartAsync() failed for listener of type [" + listener.getClass().getName() + "]", ioe); }
// in java/org/apache/catalina/core/JasperListener.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // Should not occur, obviously log.warn("Couldn't initialize Jasper", t); }
// in java/org/apache/catalina/core/StandardServer.java
catch (AccessControlException ace) { log.warn("StandardServer.accept security exception: " + ace.getMessage(), ace); continue; }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { log.warn("StandardServer.await: read: ", e); ch = -1; }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (Exception e) { logger.warn(sm.getString("naming.jmxRegistrationFailed", e)); }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (IOException e) { container.getLogger().warn("Exception Processing " + errorPage, e); }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (IOException e) { container.getLogger().warn("Exception Processing " + errorPage, e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.warn("standardContext.namingResource.destroy.fail", e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.warn("standardContext.namingResource.init.fail", e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException e) { log.warn(sm.getString("standardContext.workPath", getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException e) { log.warn(sm.getString("standardContext.workCreateException", workDir, catalinaHomePath, getName()), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (NoSuchMethodException e) { log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalArgumentException e) { log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalAccessException e) { log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/org/apache/catalina/core/StandardEngine.java
catch(Exception ex) { log.warn(sm.getString("standardEngine.jvmRouteFail")); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (MalformedObjectNameException e) { log.warn(sm.getString("lifecycleMBeanBase.registerFail", obj, name), e); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (Exception e) { log.warn(sm.getString("lifecycleMBeanBase.registerFail", obj, name), e); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (MBeanRegistrationException e) { log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", on), e); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (InstanceNotFoundException e) { log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", on), e); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (LifecycleException e) { // Just log. Still want to destroy. log.warn(sm.getString("lifecycleBase.destroyStopFail"), e); }
// in java/org/apache/catalina/security/SecurityListener.java
catch (NumberFormatException nfe) { log.warn(sm.getString("SecurityListener.checkUmaskParseFail", prop)); }
306
getMessage 150
                  
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JspException(e.getMessage(), t); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer.getMessage("jsp.error.flush"), ex); throw ise; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer .getMessage("jsp.error.attempt_to_clear_flushed_buffer")); ise.initCause(ex); throw ise; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (writer != null) { try { writer.close(); writer = null; } catch (Exception e1) { // do nothing } } // Remove the generated .java file File file = new File(javaFileName); if (file.exists()) { if (!file.delete()) { log.warn(Localizer.getMessage( "jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath())); } } throw e; }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { // Remove as much as possible, log possible exceptions log.warn(Localizer.getMessage("jsp.warning.compiler.classfile.delete.fail.unknown"), e); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { // Remove as much as possible, log possible exceptions log.warn(Localizer.getMessage("jsp.warning.compiler.classfile.delete.fail.unknown"), e); }
// in java/org/apache/jasper/compiler/Parser.java
catch (IllegalArgumentException iae) { err.jspError(start, iae.getMessage()); }
// in java/org/apache/jasper/compiler/Parser.java
catch (Exception ex) { err.jspError(start, ex.getMessage()); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage( "jsp.error.internal.tldinit", ex.getMessage()), ex); }
// in java/org/apache/jasper/compiler/WebXml.java
catch (MalformedURLException e) { log.warn(Localizer.getMessage( "jsp.error.internal.filenotfound", altDDName)); }
// in java/org/apache/jasper/compiler/WebXml.java
catch (IOException e) { log.error(Localizer.getMessage( "jsp.error.stream.close.failed")); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (SAXParseException e) { jspDocParser.err.jspError (new Mark(jspDocParser.ctxt, path, e.getLineNumber(), e.getColumnNumber()), e.getMessage()); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (JasperException je) { throw new SAXParseException( Localizer.getMessage("jsp.error.could.not.add.taglibraries"), locator, je); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { throw new SAXException( Localizer.getMessage("jsp.error.loadclass.taghandler", handlerClassName, qName), e); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (FileNotFoundException fnfe) { throw new SAXParseException( Localizer.getMessage("jsp.error.file.not.found", fname), locator, fnfe); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError("jsp.error.function.classnotfound", n .getFunctionInfo().getFunctionClass(), n .getPrefix() + ':' + n.getName(), e.getMessage()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError("jsp.error.signature.classnotfound", paramTypes[i], n.getPrefix() + ':' + n.getName(), e.getMessage()); }
// in java/org/apache/jasper/compiler/AntCompiler.java
catch (BuildException e) { be = e; log.error(Localizer.getMessage("jsp.error.javac"), e); log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString()); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); // Log any exception, since it can't be passed along log.error(Localizer.getMessage("jsp.error.file.not.found", e.getMessage()), t); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IllegalStateException ise) { log.error(Localizer.getMessage("jsp.error.file.not.found", jspUri)); }
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/jasper/el/ExpressionEvaluatorImpl.java
catch (javax.el.ELException e) { throw new ELParseException(e.getMessage()); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (InstantiationException e) { log.warn(Localizer.getMessage("jsp.error.compiler"), e); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (IllegalAccessException e) { log.warn(Localizer.getMessage("jsp.error.compiler"), e); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (NoClassDefFoundError e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.error.compiler"), e); } }
// in java/org/apache/jasper/JspCompilationContext.java
catch (ClassNotFoundException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.error.compiler"), e); } }
// in java/org/apache/jasper/JspCompilationContext.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (Exception ex) { JasperException je = new JasperException( Localizer.getMessage("jsp.error.unable.compile"), ex); // Cache compilation exception jsw.setCompilationException(je); throw je; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (ClassNotFoundException cex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.load"), cex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (MalformedURLException e) { throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"), e); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (ParserConfigurationException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), ex); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXParseException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXException sx) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), sx); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (IOException io) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), io); }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } }
// in java/org/apache/jasper/JspC.java
catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.checkInterval")); } }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval")); } }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.maxLoadedJsps", ""+this.maxLoadedJsps)); } }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.jspIdleTimeout", ""+this.jspIdleTimeout)); } }
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.beans.IntrospectionException ie) { NamingException ne = new NamingException(ie.getMessage()); ne.setRootCause(ie); throw ne; }
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.IllegalAccessException iae) { NamingException ne = new NamingException(iae.getMessage()); ne.setRootCause(iae); throw ne; }
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.InstantiationException ie2) { NamingException ne = new NamingException(ie2.getMessage()); ne.setRootCause(ie2); throw ne; }
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.reflect.InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } NamingException ne = new NamingException(ite.getMessage()); ne.setRootCause(ite); throw ne; }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
catch (Exception x) { if (x instanceof InvocationTargetException) { Throwable cause = x.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } if (cause instanceof Exception) { x = (Exception) cause; } } if (x instanceof NamingException) throw (NamingException)x; else { NamingException nx = new NamingException(x.getMessage()); nx.initCause(x); throw nx; } }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (NamingException e) { throw new RuntimeException(e.getMessage(), e); }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (Exception e) { NamingException ne = new NamingException(e.getMessage()); ne.initCause(e); throw ne; }
// in java/org/apache/naming/NamingContext.java
catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); }
// in java/org/apache/naming/resources/WARDirContext.java
catch (Exception e) { throw new IllegalArgumentException (sm.getString("warResources.invalidWar", e.getMessage())); }
// in java/org/apache/naming/resources/WARDirContext.java
catch (ZipException e) { throw new IOException(e.getMessage(), e); }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (AccessControlException ace) { // No permission to configure logging in context // Log and carry on ClassLoaderLogInfo info = classLoaderLoggers.get(ClassLoader.getSystemClassLoader()); if (info != null) { Logger log = info.loggers.get(""); if (log != null) { Permission perm = ace.getPermission(); if (perm instanceof FilePermission && perm.getActions().equals("read")) { log.warning("Reading " + perm.getName() + " is not permitted. See \"per context logging\" in the default catalina.policy file."); } else { log.warning("Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file."); log.warning("Original error was: " + ace.getMessage()); } } } }
// in java/org/apache/tomcat/jni/Library.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } String name = System.mapLibraryName(NAMES[i]); String path = System.getProperty("java.library.path"); String sep = System.getProperty("path.separator"); String [] paths = path.split(sep); for (int j=0; j<paths.length; j++) { java.io.File fd = new java.io.File(paths[j] , name); if (fd.exists()) { t.printStackTrace(); } } if ( i > 0) err.append(", "); err.append(t.getMessage()); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (BindException orig) { String msg; if (getAddress() == null) msg = orig.getMessage() + " <null>:" + getPort(); else msg = orig.getMessage() + " " + getAddress().toString() + ":" + getPort(); BindException be = new BindException(msg); be.initCause(orig); throw be; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (FileNotFoundException fnfe) { log.error(sm.getString("jsse.keystore_load_failed", type, path, fnfe.getMessage()), fnfe); throw fnfe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception e) { if( e instanceof IOException ) throw (IOException)e; throw new IOException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException ssle) { // SSL configuration is invalid. Possibly cert doesn't match ciphers IOException ioe = new IOException(sm.getString( "jsse.invalid_ssl_conf", ssle.getMessage())); ioe.initCause(ssle); throw ioe; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IllegalStateException ise) { // Hitting limit stops processing further params but does // not cause request to fail. parseFailed = true; UserDataHelper.Mode logMode = maxParamCountLog.getNextMode(); if (logMode != null) { String message = ise.getMessage(); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString( "parameters.maxCountFail.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } break; }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new FileUploadException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/buf/UDecoder.java
catch (RuntimeException ex) { throw new DecodeException(ex.getMessage()); }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
catch (Exception e) { // log message and error if (digester.log.isInfoEnabled()) { digester.log.info("[FactoryCreateRule] Create exception ignored: " + ((e.getMessage() == null) ? e.getClass().getName() : e.getMessage())); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule] Ignored exception:", e); } } exceptionIgnoredStack.push(Boolean.TRUE); }
// in java/org/apache/tomcat/util/digester/XercesParser.java
catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/GenericParser.java
catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); }
// in java/org/apache/el/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
// in java/org/apache/el/parser/ELParser.java
catch (ParseException pe) { throw new ELException(pe.getMessage());
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage())); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (SAXParseException spe) { log.warn("Catalina.start using " + getConfigFile() + ": " + spe.getMessage()); return; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassCastException e) { log.error(" Failed tracking modifications of '" + getJarPath() + "' : " + e.getMessage()); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This is likely a dual registration log.info("Dual registration of jndi stream handler: " + t.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { log.error("Couldn't get MD5 digest: ", e); throw new IllegalStateException(e.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTP_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTPS_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
catch (Exception e) { if (isEcho()) handleErrorOutput(e.getMessage()); return "Can't query mbeans " + qry; }
// in java/org/apache/catalina/ant/BaseRedirectorHelperTask.java
catch (IOException ioe) { log("Error closing redirector: " + ioe.getMessage(), Project.MSG_ERR); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch(Exception e) { message = smClient.getString ("htmlManagerServlet.deployUploadFail", e.getMessage()); log(message, e); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { //this could be the channel listener throwing an exception, we should log it //as a warning. if ( log.isWarnEnabled() ) log.warn("Error receiving message:",x); throw new RemoteProcessException("Exception:"+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/io/BufferPool.java
catch ( Throwable x ) { log.warn("Unable to initilize BufferPool, not pooling XByteBuffer objects:"+x.getMessage()); if ( log.isDebugEnabled() ) log.debug("Unable to initilize BufferPool, not pooling XByteBuffer objects:",x); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch ( java.io.IOException x ) { log.warn("Unable to send ACK back through channel, channel disconnected?: "+x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
catch ( Exception x ) { log.error("Unable to disconnect NioSender. msg="+x.getMessage()); if ( log.isDebugEnabled() ) log.debug("Unable to disconnect NioSender. msg="+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (Exception e) { //this is common, since the sockets on the other //end expire after a certain time. if ( e instanceof CancelledKeyException ) { //do nothing } else if ( e instanceof IOException ) { //dont spew out stack traces for IO exceptions unless debug is enabled. if (log.isDebugEnabled()) log.debug ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"].", e); else log.warn ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"]."); } else if ( log.isErrorEnabled() ) { //this is a real error, log it. log.error("Exception caught in TcpReplicationThread.drainChannel.",e); } cancelKey(key); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( java.io.IOException x ) { log.warn("Unable to send ACK back through channel, channel disconnected?: "+x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/tipis/LazyReplicatedMap.java
catch ( ChannelException x ) { log.error("Unable to replicate backup key:"+key+" to backup:"+next+". Reason:"+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/tipis/LazyReplicatedMap.java
catch ( ChannelException x ) { //log the error, but proceed, this should only happen if a node went down, //and if the node went down, then it can't receive the message, the others //should still get it. log.error("Unable to replicate proxy key:"+key+" to backup:"+next+". Reason:"+x.getMessage(),x); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("checking isLoaded for id, " + id + ", "+e.getMessage(), e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("Can't load sessions from store, " + e.getMessage(), e); return; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("Failed load session from store, " + e.getMessage(), e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("Exception removing session " + e.getMessage(), e); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
catch (ServletException e) { throw new IOException("Couldn't include file: " + originalPath + " because of ServletException: " + e.getMessage()); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException ioe) { res.setStatus(400); res.setMessage("Invalid URI: " + ioe.getMessage()); connector.getService().getContainer().logAccess( request, response, 0, true); return false; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage() ,e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardServer.java
catch (AccessControlException ace) { log.warn("StandardServer.accept security exception: " + ace.getMessage(), ace); continue; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch(Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage(), t); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); }
// in java/org/apache/catalina/core/StandardContext.java
catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException(cnfe.getMessage()); }
// in java/org/apache/catalina/core/StandardContext.java
catch (IllegalArgumentException e) { log.error("Error initializing resources: " + e.getMessage()); ok = false; }
// in java/org/apache/catalina/security/SecurityUtil.java
catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/javax/servlet/http/Cookie.java
catch (CloneNotSupportedException e) { throw new RuntimeException(e.getMessage()); }
// in java/javax/servlet/http/HttpUtils.java
catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); }
// in java/javax/servlet/http/HttpUtils.java
catch (java.io.UnsupportedEncodingException e) { // XXX function should accept an encoding parameter & throw this // exception. Otherwise throw something expected. throw new IllegalArgumentException(e.getMessage(), e); }
393
getName 135
                  
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn("Error processing preDestroy on tag instance of " + handler.getClass().getName(), t); }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn("Error processing preDestroy on tag instance of " + handler.getClass().getName(), t); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/jasper/compiler/Generator.java
catch (IntrospectionException ie) { err.jspError(n, "jsp.error.introspect.taghandler", tagHandlerClass.getName(), ie); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError (n, "jsp.error.unknown_attribute_type", tldAttr.getName(), expectedType); }
// in java/org/apache/jasper/compiler/Validator.java
catch (Exception e) { err.jspError (n, "jsp.error.coerce_to_type", tldAttr.getName(), expectedType, attrs.getValue(i)); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError("jsp.error.function.classnotfound", n .getFunctionInfo().getFunctionClass(), n .getPrefix() + ':' + n.getName(), e.getMessage()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError("jsp.error.signature.classnotfound", paramTypes[i], n.getPrefix() + ':' + n.getName(), e.getMessage()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (NoSuchMethodException e) { err.jspError("jsp.error.noFunctionMethod", n .getMethodName(), n.getName(), c.getName()); }
// in java/org/apache/naming/resources/WARDirContext.java
catch (IOException e) { log.warn ("Exception closing WAR File " + base.getName(), e); }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (AccessControlException ace) { // No permission to configure logging in context // Log and carry on ClassLoaderLogInfo info = classLoaderLoggers.get(ClassLoader.getSystemClassLoader()); if (info != null) { Logger log = info.loggers.get(""); if (log != null) { Permission perm = ace.getPermission(); if (perm instanceof FilePermission && perm.getActions().equals("read")) { log.warning("Reading " + perm.getName() + " is not permitted. See \"per context logging\" in the default catalina.policy file."); } else { log.warning("Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file."); log.warning("Original error was: " + ace.getMessage()); } } } }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().error(sm.getString( "abstractProtocolHandler.mbeanRegistrationFailed", tpOname, getName()), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.initError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.startError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.pauseError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.resumeError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.stopError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().error(sm.getString("abstractProtocolHandler.destroyError", getName()), e); }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
catch (Exception e) { // log message and error if (digester.log.isInfoEnabled()) { digester.log.info("[FactoryCreateRule] Create exception ignored: " + ((e.getMessage() == null) ? e.getClass().getName() : e.getMessage())); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule] Ignored exception:", e); } } exceptionIgnoredStack.push(Boolean.TRUE); }
// in java/org/apache/tomcat/util/digester/XercesParser.java
catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); }
// in java/org/apache/tomcat/util/digester/GenericParser.java
catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (SAXParseException e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); log.error(sm.getString("contextConfig.defaultPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString( "contextConfig.fixDocBase", context.getName()), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException ioe) { log.error(sm.getString( "contextConfig.servletContainerInitializerFail", url, context.getName())); ok = false; return; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException ioe) { log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName())); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (URISyntaxException e) { log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName())); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (Exception e) { log.error(sm.getString( "tldConfig.execute", context.getName()), e); }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage())); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in class " + clazz.getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not clean fields for class " + clazz.getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in object instance of class " + instance.getClass().getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.stopTimerThreadFail", thread.getName(), contextName), t); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { throw new IllegalArgumentException( sm.getString("webappClassLoader.validationErrorJarPath", jarEntry2.getName()), ioe); }
// in java/org/apache/catalina/realm/CombinedRealm.java
catch (LifecycleException e) { // If realm doesn't start can't authenticate against it iter.remove(); log.error(sm.getString("combinedRealm.realmStartFail", realm.getClass().getName()), e); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
catch (Exception e) { log.warn("Error during context [" + context.getName() + "] destroy ", e); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", environment.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", resource.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", resourceLink.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", environment.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", resource.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", resourceLink.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", cr.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", ce.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", crl.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (NamingException e) { log.warn(sm.getString( "namingResources.cleanupNoResource", cr.getName(), container), e); continue; }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", crl.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", ce.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", cr.getName()), e); }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
catch (Exception x) { log.warn("Unable to load meta data for class:"+clazz.getName()); return false; }
// in java/org/apache/catalina/ha/session/BackupManager.java
catch ( Exception x ) { log.error(sm.getString("backupManager.startUnable", getName()),x); throw new LifecycleException(sm.getString("backupManager.startFailed", getName()),x); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Exception x) { log.error(sm.getString("deltaManager.receiveMessage.error",getName()), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception e) { log.error(sm.getString("farmWarDeployer.mbeanNameFail", engine.getName(), hostname),e); return; }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { String errPrefix = ""; if(this.service != null) { errPrefix += "service.getName(): \"" + this.service.getName() + "\"; "; } throw new LifecycleException (errPrefix + " " + sm.getString ("coyoteConnector.protocolHandlerStartFailed"), e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error( sm.getString("standardWrapper.allocateException", wrapper.getName()), e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ServletException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.init", listenerClass.getName()), e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IOException ioe) { log.warn("onComplete() failed for listener of type [" + listener.getClass().getName() + "]", ioe); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IOException ioe) { log.warn("onStartAsync() failed for listener of type [" + listener.getClass().getName() + "]", ioe); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IOException ioe) { log.warn("onStartAsync() failed for listener of type [" + listener.getClass().getName() + "]", ioe); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NumberFormatException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", env.getName())); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (IllegalArgumentException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", env.getName())); }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException e) { log.warn(sm.getString("standardContext.workPath", getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.error( sm.getString("standardContext.stoppingContext", getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.error( sm.getString("standardContext.startingContext", getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextInitialized", listener); getLogger().error (sm.getString("standardContext.listenerStart", instances[i].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextDestroyed", listener); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (ServletException e) { getLogger().error(sm.getString("standardWrapper.loadException", getName()), StandardWrapper.getRootCause(e)); // NOTE: load errors (including a servlet that throws // UnavailableException from tht init() method) are NOT // fatal to application startup }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[i].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[j].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException e) { log.warn(sm.getString("standardContext.workCreateException", workDir, catalinaHomePath, getName()), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { getServletContext().log(sm.getString ("standardWrapper.unloadException", getName()), e); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servlet = null; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); ioException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (UnavailableException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); servletException = e; wrapper.unavailable(e); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause); } servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); runtimeException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e); // FIXME: Exception handling needs to be similar to what is in the StandardWrapperValue }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); }
// in java/javax/el/ExpressionFactory.java
catch (InstantiationException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/ExpressionFactory.java
catch (IllegalAccessException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/ExpressionFactory.java
catch (IllegalArgumentException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/ExpressionFactory.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
1196
debug 120
                  
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (log.isDebugEnabled()) log.debug("Problem accessing resource. Treat as outdated.", e); return true; }
// in java/org/apache/jasper/compiler/JspReader.java
catch (Exception any) { if(log.isDebugEnabled()) { log.debug("Exception closing reader: ", any); } }
// in java/org/apache/jasper/compiler/JspReader.java
catch (Exception any) { if(log.isDebugEnabled()) { log.debug("Exception closing reader: ", any); } }
// in java/org/apache/jasper/JspCompilationContext.java
catch (NoClassDefFoundError e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.error.compiler"), e); } }
// in java/org/apache/jasper/JspCompilationContext.java
catch (ClassNotFoundException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.error.compiler"), e); } }
// in java/org/apache/jasper/JspCompilationContext.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; }
// in java/org/apache/coyote/AbstractProtocol.java
catch(java.net.SocketException e) { // SocketExceptions are normal getLog().debug(sm.getString( "ajpprotocol.proto.socketexception.debug"), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (java.io.IOException e) { // IOExceptions are normal getLog().debug(sm.getString( "ajpprotocol.proto.ioexception.debug"), e); }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Ignored exception while flushing gzip filter", e); } }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), e); } error = true; break; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), t); } // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug(sm.getString( "http11processor.request.prepare"), t); } // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
catch (Exception e) { if (logger.isDebugEnabled()) logger .debug("Error loading SSL Implementation " + className, e); throw new ClassNotFoundException( "Error loading SSL Implementation " + className + " :" + e.toString()); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch ( NullPointerException x ) { //sun bug 5076772 on windows JDK 1.5 if (selector==null) throw x; if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); continue; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch ( CancelledKeyException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); continue; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch( Exception ignore ) { if (log.isDebugEnabled())log.debug("",ignore); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch( Exception ignore ) { if (log.isDebugEnabled())log.debug("",ignore); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("", ioe); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("", ioe); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "endpoint.debug.channelCloseFail"), e); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception e){ if (log.isDebugEnabled()) { log.debug(sm.getString( "endpoint.debug.socketCloseFail"), e); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( NullPointerException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( CancelledKeyException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( IOException x ) { if ( log.isDebugEnabled() ) log.debug("Unable to complete sendfile request:", x); cancelledKey(sk,SocketStatus.ERROR); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( IOException x ) { handshake = -1; if ( log.isDebugEnabled() ) log.debug("Error during SSL handshake",x);
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { if (step == 2) { log.debug(sm.getString("endpoint.err.handshake"), t); } else { log.debug(sm.getString("endpoint.err.unexpected"), t); } } // Tell to close the socket return false; }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
catch(Exception e) { if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("endpoint.debug.unlock", "" + getPort()), e); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.err.handshake"), t); } // Tell to close the socket state = SocketState.CLOSED; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (SocketException s) { //error here is common if the client has reset the connection if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.err.unexpected"), s); } // Close the socket return false; }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch( Throwable t ) { log.debug(sm.getString("jsseSupport.clientCertError"), t); return null; }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IllegalStateException ise) { // Hitting limit stops processing further params but does // not cause request to fail. parseFailed = true; UserDataHelper.Mode logMode = maxParamCountLog.getNextMode(); if (logMode != null) { String message = ise.getMessage(); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString( "parameters.maxCountFail.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } break; }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException e) { parseFailed = true; decodeFailCount++; if (decodeFailCount == 1 || log.isDebugEnabled()) { if (log.isDebugEnabled()) { log.debug(sm.getString("parameters.decodeFail.debug", origName.toString(), origValue.toString()), e); } else if (log.isInfoEnabled()) { UserDataHelper.Mode logMode = userDataLog.getNextMode(); if (logMode != null) { String message = sm.getString( "parameters.decodeFail.info", tmpName.toString(), tmpValue.toString()); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString("parameters.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } } } }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
catch( IOException ex) { if(log.isDebugEnabled()) { log.debug("B2CConverter: Reseting the converter " + ex.toString()); } reset(); throw ex; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (UnknownHostException exc) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Unable to resolve host name:" + value); ok = false; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (SecurityException ex1) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: SecurityException for " + o.getClass() + " " + name + "=" + value + ")", ex1); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalAccessException iae) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: IllegalAccessException for " + o.getClass() + " " + name + "=" + value + ")", iae); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); if (log.isDebugEnabled()) log.debug("IntrospectionUtils: InvocationTargetException for " + o.getClass() + " " + name + "=" + value + ")", ie); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (SecurityException ex1) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: SecurityException for " + o.getClass() + " " + name + ")", ex1); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalAccessException iae) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: IllegalAccessException for " + o.getClass() + " " + name + ")", iae); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); if (log.isDebugEnabled()) log.debug("IntrospectionUtils: InvocationTargetException for " + o.getClass() + " " + name + ")"); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (UnknownHostException exc) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Unable to resolve host name:" + object); }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
catch (Exception e) { // log message and error if (digester.log.isInfoEnabled()) { digester.log.info("[FactoryCreateRule] Create exception ignored: " + ((e.getMessage() == null) ? e.getClass().getName() : e.getMessage())); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule] Ignored exception:", e); } } exceptionIgnoredStack.push(Boolean.TRUE); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassFormatException e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (NoClassDefFoundError e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); return null; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassNotFoundException e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); return null; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassFormatError e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); return null; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), t); return null; }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage())); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", file), e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", getConfigFile()), e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", "server-embed.xml"), e); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NamingException e) { if (log.isDebugEnabled()) log.debug(" Failed tracking modifications of '" + getJarPath() + "'"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to close JAR", e); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in class " + clazz.getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not clean fields for class " + clazz.getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in object instance of class " + instance.getClass().getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { if (System.getProperty("java.vendor").startsWith("Sun")) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } else { log.debug(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to open JAR", e); } return false; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch( Exception ex ) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) log.debug("getClasspath ", ex); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Log the problem for posterity containerLog.error(sm.getString("jndiRealm.exception"), e); // Close the connection so that it gets reopened next time if (context != null) close(context); // Return "not authenticated" for this request if (containerLog.isDebugEnabled()) containerLog.debug("Returning null principal."); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (AccountExpiredException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.accountExpired", username)); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (CredentialExpiredException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.credentialExpired", username)); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (FailedLoginException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.failedLogin", username)); return (null); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (Exception e) { if (log.isDebugEnabled()) log.debug(" Validity exception", e); return (null); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "realmBase.delegatedCredentialFail", name), e); } }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (JMRuntimeException rme) { Throwable cause = rme.getCause(); if (cause instanceof UnsupportedOperationException) { if (log.isDebugEnabled()) { log.debug("Error getting attribute " + oname + " " + attName, rme); } } else if (cause instanceof NullPointerException) { if (log.isDebugEnabled()) { log.debug("Error getting attribute " + oname + " " + attName, rme); } } else { log.error("Error getting attribute " + oname + " " + attName, rme); } continue; }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException nfe) { log.debug("Invalid port value [" + portHeaderValue + "] provided in header [" + getPortHeader() + "]"); }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
catch ( Exception x ) { ChannelException cx = null; if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException(x); if ( log.isDebugEnabled() ) log.debug("Error while processing async message.",x); try { if (link.getHandler() != null) link.getHandler().handleError(cx, new UniqueId(msg.getUniqueId())); } catch ( Exception ex ) { log.error("Unable to report back error message.",ex); } }
// in java/org/apache/catalina/tribes/io/BufferPool.java
catch ( Throwable x ) { log.warn("Unable to initilize BufferPool, not pooling XByteBuffer objects:"+x.getMessage()); if ( log.isDebugEnabled() ) log.debug("Unable to initilize BufferPool, not pooling XByteBuffer objects:",x); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { if (log.isDebugEnabled()) { log.debug("Failed to close socket", x); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close socket", e); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close reader", e); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close socket", e); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close reader", e); } }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
catch ( Exception x ) { log.error("Unable to disconnect NioSender. msg="+x.getMessage()); if ( log.isDebugEnabled() ) log.debug("Unable to disconnect NioSender. msg="+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close selector", e); } }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (Exception e) { //this is common, since the sockets on the other //end expire after a certain time. if ( e instanceof CancelledKeyException ) { //do nothing } else if ( e instanceof IOException ) { //dont spew out stack traces for IO exceptions unless debug is enabled. if (log.isDebugEnabled()) log.debug ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"].", e); else log.warn ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"]."); } else if ( log.isErrorEnabled() ) { //this is a real error, log it. log.error("Exception caught in TcpReplicationThread.drainChannel.",e); } cancelKey(key); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (IOException e) { if (log.isDebugEnabled()) log.debug("", e); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception e) { if (log.isDebugEnabled()) log.debug("", e); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (IOException e) { if (log.isDebugEnabled()) log.debug("", e); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception iox) { if (log.isDebugEnabled()) log.debug("Unable to close datagram channel.",iox); }
// in java/org/apache/catalina/tribes/transport/PooledSender.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "PooledSender.senderDisconnectFail"), e); } }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (IllegalStateException ise) { log.debug("Unable to decode message.",ise); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( ArrayIndexOutOfBoundsException ax ) { //we can ignore this, as it means we have an invalid package //but we will log it to debug if ( log.isDebugEnabled() ) log.debug("Invalid member mcast package.",ax); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception x ) { if (x instanceof InterruptedException) interrupted(); else { if (errorCounter==0 && doRunReceiver) log.warn("Error receiving mcast package. Sleeping 500ms",x); else if (log.isDebugEnabled()) log.debug("Error receiving mcast package"+(doRunReceiver?". Sleeping 500ms":"."),x); if (doRunReceiver) { try { Thread.sleep(500); } catch ( Exception ignore ){} if ( (++errorCounter)>=recoveryCounter ) { errorCounter=0; RecoveryThread.recover(McastServiceImpl.this); } } } }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception x ) { if (errorCounter==0) log.warn("Unable to send mcast message.",x); else log.debug("Unable to send mcast message.",x); if ( (++errorCounter)>=recoveryCounter ) { errorCounter=0; RecoveryThread.recover(McastServiceImpl.this); } }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof ClassNotFoundException){ throw (ClassNotFoundException)exception; } else if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in load() " + exception); }
// in java/org/apache/catalina/session/StandardManager.java
catch (FileNotFoundException e) { if (log.isDebugEnabled()) log.debug("No persisted data file found"); return; }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in unLoad() " + exception); }
// in java/org/apache/catalina/session/FileStore.java
catch (FileNotFoundException e) { if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug("No persisted data file found"); return (null); }
// in java/org/apache/catalina/session/StandardSession.java
catch (NotSerializableException e) { manager.getContainer().getLogger().warn (sm.getString("standardSession.notSerializable", saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug (" storing attribute '" + saveNames.get(i) + "' with value NOT_SERIALIZED"); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("status.setContentType", t); } }
// in java/org/apache/catalina/valves/RemoteIpValve.java
catch (NumberFormatException nfe) { if (log.isDebugEnabled()) { log.debug(sm.getString( "remoteIpValve.invalidPortHeader", portHeaderValue, portHeader), nfe); } }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail", e)); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (IOException ioe) { log.debug("Request body too big to save during authentication"); response.sendError(HttpServletResponse.SC_FORBIDDEN, sm.getString("authenticator.requestBodyTooBig")); return (false); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (SecurityException e) { log.debug(sm.getString("namingResources.cleanupCloseSecurity", closeMethod, name, container)); return; }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (NoSuchMethodException e) { log.debug(sm.getString("namingResources.cleanupNoClose", name, container, closeMethod)); return; }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Client disconnect if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Client disconnect or chunkedPostTooLarge error if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { if (System.getProperty("java.vendor").startsWith( "Sun")) { log.error(sm.getString( "jreLeakListener.gcDaemonFail"), e); } else { log.debug(sm.getString( "jreLeakListener.gcDaemonFail"), e); } }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { if (System.getProperty("java.vendor").startsWith( "Sun")) { log.error(sm.getString( "jreLeakListener.ldapPoolManagerFail"), e); } else { log.debug(sm.getString( "jreLeakListener.ldapPoolManagerFail"), e); } }
// in java/org/apache/catalina/util/RequestUtil.java
catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.parseParameters.uee", encoding), uee); } }
// in java/org/apache/catalina/util/RequestUtil.java
catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee); } }
// in java/org/apache/catalina/util/RequestUtil.java
catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee); } return null; }
// in java/org/apache/catalina/security/SecurityConfig.java
catch (java.lang.Exception ex){ if (log.isDebugEnabled()){ log.debug("Unable to load properties using CatalinaProperties", ex); } }
// in java/org/apache/catalina/security/SecurityUtil.java
catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
801
isDebugEnabled 96
                  
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (log.isDebugEnabled()) log.debug("Problem accessing resource. Treat as outdated.", e); return true; }
// in java/org/apache/jasper/compiler/JspReader.java
catch (Exception any) { if(log.isDebugEnabled()) { log.debug("Exception closing reader: ", any); } }
// in java/org/apache/jasper/compiler/JspReader.java
catch (Exception any) { if(log.isDebugEnabled()) { log.debug("Exception closing reader: ", any); } }
// in java/org/apache/jasper/JspCompilationContext.java
catch (NoClassDefFoundError e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.error.compiler"), e); } }
// in java/org/apache/jasper/JspCompilationContext.java
catch (ClassNotFoundException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.error.compiler"), e); } }
// in java/org/apache/jasper/JspCompilationContext.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; }
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Ignored exception while flushing gzip filter", e); } }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), e); } error = true; break; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), t); } // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug(sm.getString( "http11processor.request.prepare"), t); } // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
catch (Exception e) { if (logger.isDebugEnabled()) logger .debug("Error loading SSL Implementation " + className, e); throw new ClassNotFoundException( "Error loading SSL Implementation " + className + " :" + e.toString()); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch ( NullPointerException x ) { //sun bug 5076772 on windows JDK 1.5 if (selector==null) throw x; if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); continue; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch ( CancelledKeyException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); continue; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch( Exception ignore ) { if (log.isDebugEnabled())log.debug("",ignore); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch( Exception ignore ) { if (log.isDebugEnabled())log.debug("",ignore); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("", ioe); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("", ioe); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "endpoint.debug.channelCloseFail"), e); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception e){ if (log.isDebugEnabled()) { log.debug(sm.getString( "endpoint.debug.socketCloseFail"), e); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); if (log.isDebugEnabled()) log.error("",e); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( NullPointerException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( CancelledKeyException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( IOException x ) { if ( log.isDebugEnabled() ) log.debug("Unable to complete sendfile request:", x); cancelledKey(sk,SocketStatus.ERROR); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( IOException x ) { handshake = -1; if ( log.isDebugEnabled() ) log.debug("Error during SSL handshake",x);
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { if (step == 2) { log.debug(sm.getString("endpoint.err.handshake"), t); } else { log.debug(sm.getString("endpoint.err.unexpected"), t); } } // Tell to close the socket return false; }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
catch(Exception e) { if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("endpoint.debug.unlock", "" + getPort()), e); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.err.handshake"), t); } // Tell to close the socket state = SocketState.CLOSED; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (SocketException s) { //error here is common if the client has reset the connection if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.err.unexpected"), s); } // Close the socket return false; }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException e) { parseFailed = true; decodeFailCount++; if (decodeFailCount == 1 || log.isDebugEnabled()) { if (log.isDebugEnabled()) { log.debug(sm.getString("parameters.decodeFail.debug", origName.toString(), origValue.toString()), e); } else if (log.isInfoEnabled()) { UserDataHelper.Mode logMode = userDataLog.getNextMode(); if (logMode != null) { String message = sm.getString( "parameters.decodeFail.info", tmpName.toString(), tmpValue.toString()); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString("parameters.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } } } }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
catch( IOException ex) { if(log.isDebugEnabled()) { log.debug("B2CConverter: Reseting the converter " + ex.toString()); } reset(); throw ex; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (UnknownHostException exc) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Unable to resolve host name:" + value); ok = false; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (SecurityException ex1) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: SecurityException for " + o.getClass() + " " + name + "=" + value + ")", ex1); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalAccessException iae) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: IllegalAccessException for " + o.getClass() + " " + name + "=" + value + ")", iae); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); if (log.isDebugEnabled()) log.debug("IntrospectionUtils: InvocationTargetException for " + o.getClass() + " " + name + "=" + value + ")", ie); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (SecurityException ex1) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: SecurityException for " + o.getClass() + " " + name + ")", ex1); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalAccessException iae) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: IllegalAccessException for " + o.getClass() + " " + name + ")", iae); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); if (log.isDebugEnabled()) log.debug("IntrospectionUtils: InvocationTargetException for " + o.getClass() + " " + name + ")"); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (UnknownHostException exc) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Unable to resolve host name:" + object); }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
catch (Exception e) { // log message and error if (digester.log.isInfoEnabled()) { digester.log.info("[FactoryCreateRule] Create exception ignored: " + ((e.getMessage() == null) ? e.getClass().getName() : e.getMessage())); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule] Ignored exception:", e); } } exceptionIgnoredStack.push(Boolean.TRUE); }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage())); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", file), e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", getConfigFile()), e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", "server-embed.xml"), e); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NamingException e) { if (log.isDebugEnabled()) log.debug(" Failed tracking modifications of '" + getJarPath() + "'"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to close JAR", e); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in class " + clazz.getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not clean fields for class " + clazz.getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in object instance of class " + instance.getClass().getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to open JAR", e); } return false; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch( Exception ex ) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) log.debug("getClasspath ", ex); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Log the problem for posterity containerLog.error(sm.getString("jndiRealm.exception"), e); // Close the connection so that it gets reopened next time if (context != null) close(context); // Return "not authenticated" for this request if (containerLog.isDebugEnabled()) containerLog.debug("Returning null principal."); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (AccountExpiredException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.accountExpired", username)); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (CredentialExpiredException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.credentialExpired", username)); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (FailedLoginException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.failedLogin", username)); return (null); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (Exception e) { if (log.isDebugEnabled()) log.debug(" Validity exception", e); return (null); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "realmBase.delegatedCredentialFail", name), e); } }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (JMRuntimeException rme) { Throwable cause = rme.getCause(); if (cause instanceof UnsupportedOperationException) { if (log.isDebugEnabled()) { log.debug("Error getting attribute " + oname + " " + attName, rme); } } else if (cause instanceof NullPointerException) { if (log.isDebugEnabled()) { log.debug("Error getting attribute " + oname + " " + attName, rme); } } else { log.error("Error getting attribute " + oname + " " + attName, rme); } continue; }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
catch ( Exception x ) { ChannelException cx = null; if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException(x); if ( log.isDebugEnabled() ) log.debug("Error while processing async message.",x); try { if (link.getHandler() != null) link.getHandler().handleError(cx, new UniqueId(msg.getUniqueId())); } catch ( Exception ex ) { log.error("Unable to report back error message.",ex); } }
// in java/org/apache/catalina/tribes/io/BufferPool.java
catch ( Throwable x ) { log.warn("Unable to initilize BufferPool, not pooling XByteBuffer objects:"+x.getMessage()); if ( log.isDebugEnabled() ) log.debug("Unable to initilize BufferPool, not pooling XByteBuffer objects:",x); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { if (log.isDebugEnabled()) { log.debug("Failed to close socket", x); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close socket", e); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close reader", e); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close socket", e); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close reader", e); } }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
catch ( Exception x ) { log.error("Unable to disconnect NioSender. msg="+x.getMessage()); if ( log.isDebugEnabled() ) log.debug("Unable to disconnect NioSender. msg="+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close selector", e); } }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (Exception e) { //this is common, since the sockets on the other //end expire after a certain time. if ( e instanceof CancelledKeyException ) { //do nothing } else if ( e instanceof IOException ) { //dont spew out stack traces for IO exceptions unless debug is enabled. if (log.isDebugEnabled()) log.debug ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"].", e); else log.warn ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"]."); } else if ( log.isErrorEnabled() ) { //this is a real error, log it. log.error("Exception caught in TcpReplicationThread.drainChannel.",e); } cancelKey(key); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( RemoteProcessException e ) { if ( log.isDebugEnabled() ) log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (IOException e) { if (log.isDebugEnabled()) log.debug("", e); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception e) { if (log.isDebugEnabled()) log.debug("", e); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (IOException e) { if (log.isDebugEnabled()) log.debug("", e); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception iox) { if (log.isDebugEnabled()) log.debug("Unable to close datagram channel.",iox); }
// in java/org/apache/catalina/tribes/transport/PooledSender.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "PooledSender.senderDisconnectFail"), e); } }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( ArrayIndexOutOfBoundsException ax ) { //we can ignore this, as it means we have an invalid package //but we will log it to debug if ( log.isDebugEnabled() ) log.debug("Invalid member mcast package.",ax); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception x ) { if (x instanceof InterruptedException) interrupted(); else { if (errorCounter==0 && doRunReceiver) log.warn("Error receiving mcast package. Sleeping 500ms",x); else if (log.isDebugEnabled()) log.debug("Error receiving mcast package"+(doRunReceiver?". Sleeping 500ms":"."),x); if (doRunReceiver) { try { Thread.sleep(500); } catch ( Exception ignore ){} if ( (++errorCounter)>=recoveryCounter ) { errorCounter=0; RecoveryThread.recover(McastServiceImpl.this); } } } }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof ClassNotFoundException){ throw (ClassNotFoundException)exception; } else if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in load() " + exception); }
// in java/org/apache/catalina/session/StandardManager.java
catch (FileNotFoundException e) { if (log.isDebugEnabled()) log.debug("No persisted data file found"); return; }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in unLoad() " + exception); }
// in java/org/apache/catalina/session/FileStore.java
catch (FileNotFoundException e) { if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug("No persisted data file found"); return (null); }
// in java/org/apache/catalina/session/StandardSession.java
catch (NotSerializableException e) { manager.getContainer().getLogger().warn (sm.getString("standardSession.notSerializable", saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug (" storing attribute '" + saveNames.get(i) + "' with value NOT_SERIALIZED"); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("status.setContentType", t); } }
// in java/org/apache/catalina/valves/RemoteIpValve.java
catch (NumberFormatException nfe) { if (log.isDebugEnabled()) { log.debug(sm.getString( "remoteIpValve.invalidPortHeader", portHeaderValue, portHeader), nfe); } }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail", e)); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Client disconnect if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Client disconnect or chunkedPostTooLarge error if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); }
// in java/org/apache/catalina/util/RequestUtil.java
catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.parseParameters.uee", encoding), uee); } }
// in java/org/apache/catalina/util/RequestUtil.java
catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee); } }
// in java/org/apache/catalina/util/RequestUtil.java
catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee); } return null; }
// in java/org/apache/catalina/security/SecurityConfig.java
catch (java.lang.Exception ex){ if (log.isDebugEnabled()){ log.debug("Unable to load properties using CatalinaProperties", ex); } }
// in java/org/apache/catalina/security/SecurityUtil.java
catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
735
getLogger 95
                  
// in java/org/apache/tomcat/util/digester/CallMethodRule.java
catch (ClassNotFoundException e) { // use the digester log digester.getLogger().error("(CallMethodRule) Cannot load class " + this.paramClassNames[i], e); this.paramTypes[i] = null; // Will cause NPE later }
// in java/org/apache/catalina/startup/WebRuleSet.java
catch (NoSuchMethodException e) { digester.getLogger().error("Can't find method " + method + " in " + top + " CLASS " + top.getClass()); return; }
// in java/org/apache/catalina/startup/UserConfig.java
catch (Exception e) { host.getLogger().error(sm.getString("userConfig.database"), e); return; }
// in java/org/apache/catalina/startup/UserConfig.java
catch (Exception e) { host.getLogger().error(sm.getString("userConfig.deploy.threaded.error"), e); }
// in java/org/apache/catalina/startup/UserConfig.java
catch (Exception e) { host.getLogger().error(sm.getString("userConfig.error", user), e); }
// in java/org/apache/catalina/session/StoreBase.java
catch (IOException e) { manager.getContainer().getLogger().error("Error getting keys", e); return; }
// in java/org/apache/catalina/session/StoreBase.java
catch (Exception e) { manager.getContainer().getLogger().error("Session: "+keys[i]+"; ", e); try { remove(keys[i]); } catch (IOException e2) { manager.getContainer().getLogger().error("Error removing key", e2); } }
// in java/org/apache/catalina/session/StoreBase.java
catch (IOException e2) { manager.getContainer().getLogger().error("Error removing key", e2); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); keys = new String[0]; // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionSQLException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (NamingException e) { manager.getContainer().getLogger().error( sm.getString(getStoreName() + ".wrongDataSource", this.dataSourceName), e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (ClassNotFoundException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (InstantiationException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (IllegalAccessException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".commitSQLException"), e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".close", e.toString())); // Just log it here }
// in java/org/apache/catalina/session/FileStore.java
catch (FileNotFoundException e) { if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug("No persisted data file found"); return (null); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionCreated", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent( "afterSessionDestroyed", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Exception e) { manager.getContainer().getLogger().error( sm.getString("standardSession.logoutfail"), e); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t){ manager.getContainer().getLogger().error (sm.getString("standardSession.bindingEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.bindingEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { if (unbound != null) { context.fireContainerEvent( "afterSessionAttributeReplaced", listener); } else { context.fireContainerEvent("afterSessionAttributeAdded", listener); } } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (NotSerializableException e) { manager.getContainer().getLogger().warn (sm.getString("standardSession.notSerializable", saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug (" storing attribute '" + saveNames.get(i) + "' with value NOT_SERIALIZED"); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionAttributeRemoved", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (Exception e) { container.getLogger().warn( sm.getString("cometConnectionManagerValve.event"), e); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (IOException e) { container.getLogger().warn(sm.getString( "cometConnectionManagerValve.event"), e); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (Exception e) { req.getWrapper().getParent().getLogger().warn(sm.getString( "cometConnectionManagerValve.listenerEvent"), e); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { // Log the problem for posterity container.getLogger().error(sm.getString("jdbcAccessLogValve.exception"), e); // Close the connection so that it gets reopened next time if (conn != null) { close(); } }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { container.getLogger().error(sm.getString("jdbcAccessLogValeve.close"), e); // Just log it here }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("status.setContentType", t); } }
// in java/org/apache/catalina/valves/PersistentValve.java
catch (Exception e) { container.getLogger().error("deserializeError"); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Client disconnect if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Client disconnect or chunkedPostTooLarge error if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error( sm.getString("standardWrapper.allocateException", wrapper.getName()), e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedServletsResource"), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedListenersResources"), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedServletsResources"), e); }
// in java/org/apache/catalina/core/StandardContextValve.java
catch (IOException ioe) { container.getLogger().error(sm.getString( "standardContextValve.acknowledgeException"), ioe); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (IOException e) { container.getLogger().warn("Exception Processing " + errorPage, e); }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (IOException e) { container.getLogger().warn("Exception Processing " + errorPage, e); }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // Report our failure to process this custom page container.getLogger().error("Exception Processing " + errorPage, t); return (false); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.filterStart", name), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.applicationListener", listeners[i]), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextInitialized", listener); getLogger().error (sm.getString("standardContext.listenerStart", instances[i].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextDestroyed", listener); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (ServletException e) { getLogger().error(sm.getString("standardWrapper.loadException", getName()), StandardWrapper.getRootCause(e)); // NOTE: load errors (including a servlet that throws // UnavailableException from tht init() method) are NOT // fatal to application startup }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[i].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[j].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servlet = null; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); ioException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (UnavailableException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); servletException = e; wrapper.unavailable(e); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause); } servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); runtimeException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e); // FIXME: Exception handling needs to be similar to what is in the StandardWrapperValue }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); }
217
toString 68
                  
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
catch (JasperException je) { throw new RuntimeException(je.toString(), je); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Exception ex) { err.jspError(mark, "jsp.error.tld.unable_to_read", jarResource.getUrl(), tldName, ex.toString()); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Exception ex) { err.jspError("jsp.error.tld.unable_to_get_jar", uri, ex .toString()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", attrs.getValue(i), e.toString()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", value, e .toString()); }
// in java/org/apache/jasper/compiler/AntCompiler.java
catch (BuildException e) { be = e; log.error(Localizer.getMessage("jsp.error.javac"), e); log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString()); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXParseException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException e) { // Unexpected exception throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); }
// in java/org/apache/tomcat/util/net/URL.java
catch (Exception e) { throw new MalformedURLException(e.toString()); }
// in java/org/apache/tomcat/util/net/URL.java
catch (NumberFormatException e) { throw new MalformedURLException(e.toString()); }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
catch (Exception e) { if (logger.isDebugEnabled()) logger .debug("Error loading SSL Implementation " + className, e); throw new ClassNotFoundException( "Error loading SSL Implementation " + className + " :" + e.toString()); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (BindException orig) { String msg; if (getAddress() == null) msg = orig.getMessage() + " <null>:" + getPort(); else msg = orig.getMessage() + " " + getAddress().toString() + ":" + getPort(); BindException be = new BindException(msg); be.initCause(orig); throw be; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException e){ throw new SocketException("SSL handshake error" + e.toString()); }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException e) { parseFailed = true; decodeFailCount++; if (decodeFailCount == 1 || log.isDebugEnabled()) { if (log.isDebugEnabled()) { log.debug(sm.getString("parameters.decodeFail.debug", origName.toString(), origValue.toString()), e); } else if (log.isInfoEnabled()) { UserDataHelper.Mode logMode = userDataLog.getNextMode(); if (logMode != null) { String message = sm.getString( "parameters.decodeFail.info", tmpName.toString(), tmpValue.toString()); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString("parameters.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } } } }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (UnsupportedEncodingException e) { // Fall back to platform default if specified encoding is not // supported. headers = baos.toString(); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
catch( IOException ex) { if(log.isDebugEnabled()) { log.debug("B2CConverter: Reseting the converter " + ex.toString()); } reset(); throw ex; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsSerSource.java
catch( Exception ex ) { log.error( "Error reading descriptors " + source + " " + ex.toString(), ex); throw ex; }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Exception t ) { if( failFirst ) throw t; log.info("Error initializing " + current + " " + t.toString()); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (IOException e) { System.out.println(buf.toString()); e.printStackTrace(); throw new ClassFormatException("Byte code error: " + e, e); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NumberFormatException e) { log.error(sm.getString("webappLoader.reloadable", event.getNewValue().toString())); }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (IOException e) { throw new LoginException(e.toString()); }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (UnsupportedCallbackException e) { throw new LoginException(e.toString()); }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (RemoteException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.createRegistryFailed", serverName, Integer.toString(theRmiRegistryPort)), e); return null; }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (MalformedURLException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.invalidURL", serverName, url.toString()), e); return null; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
catch (Exception e) { if (isEcho()) handleErrorOutput("Error getting attribute " + oname + " " + pname + attName + " " + e.toString()); continue; }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (Exception e) { log("HTMLManagerServlet.sessions[" + cn + "]", e); message = smClient.getString("managerServlet.exception", e.toString()); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch (Exception ex) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch( Exception ex ) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch (Exception ex) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); return; }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch( Exception ex ) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { getServletContext().log (sm.getString("hostManagerServlet.startFailed", name), e); writer.println(smClient.getString( "hostManagerServlet.startFailed", name)); writer.println(smClient.getString( "hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { getServletContext().log(sm.getString( "hostManagerServlet.stopFailed", name), e); writer.println(smClient.getString("hostManagerServlet.stopFailed", name)); writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.storeConfig", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.save[" + path + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.check[" + displayPath + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.check[" + displayPath + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.install[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.reload[" + cn.getDisplayName() + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.resources[" + type + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.resources[" + type + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log("ManagerServlet.serverinfo",t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.sessions[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log(sm.getString("managerServlet.startFailed", displayPath), t); writer.println(smClient.getString("managerServlet.startFailed", displayPath)); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.stop[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.undeploy[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionSQLException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (ClassNotFoundException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (InstantiationException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (IllegalAccessException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".close", e.toString())); // Just log it here }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { throw new IllegalArgumentException(cc.toString(), e); }
// in java/org/apache/catalina/util/CharsetMapper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new IllegalArgumentException(t.toString()); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.startFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.stopFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); }
// in java/javax/el/ResourceBundleELResolver.java
catch (MissingResourceException mre) { return "???" + property.toString() + "???"; }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
1036
printStackTrace 59
                  
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { e.printStackTrace(); result = null; }
// in java/org/apache/jasper/compiler/Localizer.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); t.printStackTrace(); }
// in java/org/apache/jasper/compiler/Dumper.java
catch (JasperException e) { e.printStackTrace(); }
// in java/org/apache/jasper/compiler/Dumper.java
catch (JasperException e) { e.printStackTrace(); }
// in java/org/apache/jasper/servlet/JasperLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; se.printStackTrace(); throw new ClassNotFoundException(error); }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { rootCause.printStackTrace(); } throw je; }
// in java/org/apache/naming/factory/BeanFactory.java
catch(ClassNotFoundException e) { e.printStackTrace(); }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IOException e) { // Report error System.err.println("Configuration error"); e.printStackTrace(); }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (Exception e) { // Report error System.err.println("Handler error"); e.printStackTrace(); }
// in java/org/apache/juli/AsyncFileHandler.java
catch (Exception x) { x.printStackTrace(); }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error t.printStackTrace(); response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (IOException e) { e.printStackTrace(); // Set error flag error = true; return; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (IOException e) { // Set error flag e.printStackTrace(); error = true; }
// in java/org/apache/coyote/spdy/SpdyProxyProtocol.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/SSLExt.java
catch (Throwable t) { t.printStackTrace(); return -1; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable e) { apr.reset(); e.printStackTrace(); throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Exception e) { //TODO Auto-generated catch block e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (InterruptedException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (InterruptedException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (InterruptedException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Error e) { e.printStackTrace(); if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(" endpoint.poll.limitedpollsize " + size); return 0; } else if (Status.APR_STATUS_IS_ENOTIMPL(e.getError())) { // thread safe not supported log.severe("THREAD SAFE NOT SUPPORTED" + e); threadSafe = false; // try again without the flags continue; } else { log.severe("endpoint.poll.initfail" + e); return 0; } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable t) { t.printStackTrace(); if (pollTime > FALLBACK_POLL_TIME) { pollTime = FALLBACK_POLL_TIME; } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable t) { t.printStackTrace(); // no error handler yet reset(); notifyError(t, false); return; }
// in java/org/apache/tomcat/jni/Library.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } String name = System.mapLibraryName(NAMES[i]); String path = System.getProperty("java.library.path"); String sep = System.getProperty("path.separator"); String [] paths = path.split(sep); for (int j=0; j<paths.length; j++) { java.io.File fd = new java.io.File(paths[j] , name); if (fd.exists()) { t.printStackTrace(); } } if ( i > 0) err.append(", "); err.append(t.getMessage()); }
// in java/org/apache/tomcat/spdy/SpdyStream.java
catch (IOException e) { e.printStackTrace(); // TODO: send rst, error processing the stream. }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (IOException e) { // connection closed - abort all streams e.printStackTrace(); onClose(); return false; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { t.printStackTrace(); trace("< onData-ERROR() " + lastChannel); abort("Error processing socket" + t); return CLOSE; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { abort("Error handling frame"); t.printStackTrace(); return CLOSE; }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); ch.reset(); }
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
catch (Exception e) { e.printStackTrace(); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (IOException ex) { ex.printStackTrace(); throw ex; }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (IOException ex) { if (running) { ex.printStackTrace(); } running = false; }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable oomt ) { try { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; socket.getPoller().cancelledKey(key,SocketStatus.ERROR); releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException e) { // Can't happen, as decodedQuery can't overflow e.printStackTrace(); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
catch (UnsupportedEncodingException e) { // Impossible. All JVMs must support these. e.printStackTrace(); }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsIntrospectionSource.java
catch( Exception ex ) { ex.printStackTrace(); return null; }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (IOException e) { System.out.println(buf.toString()); e.printStackTrace(); throw new ClassFormatException("Byte code error: " + e, e); }
// in java/org/apache/tomcat/util/bcel/classfile/Attribute.java
catch (CloneNotSupportedException e) { e.printStackTrace(); // Never occurs }
// in java/org/apache/el/lang/FunctionMapperImpl.java
catch (Exception e) { e.printStackTrace(); }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { e.printStackTrace(System.out); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (Throwable t) { handleThrowable(t); t.printStackTrace(); return; }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (Throwable t) { // Unwrap the Exception for clearer error reporting if (t instanceof InvocationTargetException && t.getCause() != null) { t = t.getCause(); } handleThrowable(t); t.printStackTrace(); System.exit(1); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch (Exception ex) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch( Exception ex ) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch (Exception ex) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); return; }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch( Exception ex ) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
catch (Exception e) { e.printStackTrace(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { e.printStackTrace(); result = false; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( Exception ignore) { ignore.printStackTrace(); }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new IllegalStateException(); }
// in java/org/apache/catalina/util/URLEncoder.java
catch (Exception e) { e.printStackTrace(); writer = new OutputStreamWriter(buf); }
67
initCause
48
                  
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer .getMessage("jsp.error.attempt_to_clear_flushed_buffer")); ise.initCause(ex); throw ise; }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load service Interface"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { if (e instanceof InvocationTargetException) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } } NamingException ex = new NamingException ("Error while reading Wsdl File"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
catch (Exception x) { if (x instanceof InvocationTargetException) { Throwable cause = x.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } if (cause instanceof Exception) { x = (Exception) cause; } } if (x instanceof NamingException) throw (NamingException)x; else { NamingException nx = new NamingException(x.getMessage()); nx.initCause(x); throw nx; } }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch (Exception e) { if (e instanceof NamingException) throw (NamingException) e; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(Throwable t) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(Throwable t) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (Exception e) { NamingException ne = new NamingException(e.getMessage()); ne.initCause(e); throw ne; }
// in java/org/apache/naming/resources/FileDirContext.java
catch (IOException e) { NamingException ne = new NamingException (sm.getString("resources.bindFailed", e)); ne.initCause(e); throw ne; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (BindException orig) { String msg; if (getAddress() == null) msg = orig.getMessage() + " <null>:" + getPort(); else msg = orig.getMessage() + " " + getAddress().toString() + ":" + getPort(); BindException be = new BindException(msg); be.initCause(orig); throw be; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException ssle) { // SSL configuration is invalid. Possibly cert doesn't match ciphers IOException ioe = new IOException(sm.getString( "jsse.invalid_ssl_conf", ssle.getMessage())); ioe.initCause(ssle); throw ioe; }
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
catch (URISyntaxException e) { // Wrap the exception and re-throw IOException ioe = new IOException(); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { IllegalArgumentException iae = new IllegalArgumentException ("Invalid repository: " + repository); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", libPath)); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", filename)); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/mbeans/UserMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for group " + group); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/UserMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role " + role); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating group [" + groupname + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating role [" + rolename + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating user [" + username + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for group [" + groupname + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role [" + rolename + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for user [" + username + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying group [" + groupname + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying role [" + rolename + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying user [" + username + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/GroupMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role " + role); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/GroupMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for user " + user); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for environment " + envs[i]); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for resource " + resources[i]); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for resource " + resourceLinks[i]); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/connector/Response.java
catch (PrivilegedActionException pae){ IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(pae.getException()); throw iae; }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; }
48
unwrapInvocationTargetException
43
                  
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JspException(e.getMessage(), t); }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn("Error processing preDestroy on tag instance of " + handler.getClass().getName(), t); }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn("Error processing preDestroy on tag instance of " + handler.getClass().getName(), t); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException ("error in invoking method", ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JasperException(t); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); // Log any exception, since it can't be passed along log.error(Localizer.getMessage("jsp.error.file.not.found", e.getMessage()), t); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); // Need to localize this. log.warn("Failed to load engineOptionsClass", e); // Use the default Options implementation options = new EmbeddedServletOptions(config, context); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error("Exception calling main() method", t); System.exit(1); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.jdbcRemoveFailed", contextName), t); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.stopTimerThreadFail", thread.getName(), contextName), t); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error( "LifecycleException ", t ); throw new LifecycleException("start: ", t); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch( Exception ex ) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) log.debug("getClasspath ", ex); }
// in java/org/apache/catalina/manager/StatusTransformer.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/util/SessionUtils.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); // stay silent }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (InvocationTargetException e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), t); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error(sm.getString("aprListener.sslInit"), t); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.info(sm.getString("aprListener.aprDestroy")); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.info(sm.getString("aprListener.aprInit", System.getProperty("java.library.path"))); return; }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); }
// in java/org/apache/catalina/core/ApplicationFilterFactory.java
catch (Exception e) { // Note: The try catch is there because getFilter has a lot of // declared exceptions. However, the filter is allocated much // earlier Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.filterStart", name), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.applicationListener", listeners[i]), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
43
getCause 40
                  
// in java/org/apache/jasper/servlet/JspServlet.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ServletException) throw (ServletException)t; throw new ServletException("Could not precompile jsp: " + jspFile, e); }
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.reflect.InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } NamingException ne = new NamingException(ite.getMessage()); ne.setRootCause(ite); throw ne; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { if (e instanceof InvocationTargetException) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } } NamingException ex = new NamingException ("Error while reading Wsdl File"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
catch (Exception x) { if (x instanceof InvocationTargetException) { Throwable cause = x.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } if (cause instanceof Exception) { x = (Exception) cause; } } if (x instanceof NamingException) throw (NamingException)x; else { NamingException nx = new NamingException(x.getMessage()); nx.initCause(x); throw nx; } }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
catch (Throwable t) { if (t instanceof InvocationTargetException && t.getCause() != null) { throw t.getCause(); } else { throw t; } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { Throwable cause = ioe.getCause(); if (cause instanceof UnrecoverableKeyException) { // Log a warning we had a password issue log.warn(sm.getString("jsse.invalid_truststore_password"), cause); // Re-try trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, null); } else { // Something else went wrong - re-throw throw ioe; } }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); if (log.isDebugEnabled()) log.debug("IntrospectionUtils: InvocationTargetException for " + o.getClass() + " " + name + "=" + value + ")", ie); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); if (log.isDebugEnabled()) log.debug("IntrospectionUtils: InvocationTargetException for " + o.getClass() + " " + name + ")"); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; }
// in java/org/apache/el/parser/AstFunction.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(MessageFactory.get("error.function", this .getOutputName()), cause); }
// in java/org/apache/el/parser/AstValue.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (Throwable t) { // Unwrap the Exception for clearer error reporting if (t instanceof InvocationTargetException && t.getCause() != null) { t = t.getCause(); } handleThrowable(t); t.printStackTrace(); System.exit(1); }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (JMRuntimeException rme) { Throwable cause = rme.getCause(); if (cause instanceof UnsupportedOperationException) { if (log.isDebugEnabled()) { log.debug("Error getting attribute " + oname + " " + attName, rme); } } else if (cause instanceof NullPointerException) { if (log.isDebugEnabled()) { log.debug("Error getting attribute " + oname + " " + attName, rme); } } else { log.error("Error getting attribute " + oname + " " + attName, rme); } continue; }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( ChannelException cx ) { FaultyMember[] mbrs = cx.getFaultyMembers(); for ( int i=0; i<mbrs.length; i++ ) { if ( mbrs[i].getCause()!=null && (!(mbrs[i].getCause() instanceof RemoteProcessException)) ) {//RemoteProcessException's are ok this.memberDisappeared(mbrs[i].getMember()); }//end if }//for throw cx; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { if (e.getCause() instanceof FileNotFoundException) { // We know the source exists so it must be the // destination dir that can't be found errorList.put(source, new Integer(WebdavStatus.SC_CONFLICT)); } else { errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR)); } return false; }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); ServletException se = new ServletException(e); throw se; }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/org/apache/catalina/security/SecurityUtil.java
catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/javax/el/ExpressionFactory.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
60
println 36
                  
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { System.err.println(je); if (jspc.dieLevel != NO_DIE_LEVEL) { System.exit(jspc.dieLevel); } }
// in java/org/apache/jasper/JspC.java
catch (MalformedURLException me) { System.out.println("**" + me); }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IOException e) { // Report error System.err.println("Configuration error"); e.printStackTrace(); }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (Exception e) { // Report error System.err.println("Handler error"); e.printStackTrace(); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); System.err.println(oomParachuteMsg); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable oomt ) { try { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; socket.getPoller().cancelledKey(key,SocketStatus.ERROR); releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (IOException e) { System.out.println(buf.toString()); e.printStackTrace(); throw new ClassFormatException("Byte code error: " + e, e); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should not occur System.err.println(e); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch (Exception ex) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch( Exception ex ) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch (Exception ex) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); return; }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch( Exception ex ) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (IOException e) { writer.println(smClient.getString( "hostManagerServlet.managerXml")); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { getServletContext().log (sm.getString("hostManagerServlet.startFailed", name), e); writer.println(smClient.getString( "hostManagerServlet.startFailed", name)); writer.println(smClient.getString( "hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { getServletContext().log(sm.getString( "hostManagerServlet.stopFailed", name), e); writer.println(smClient.getString("hostManagerServlet.stopFailed", name)); writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.storeConfig", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.save[" + path + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.check[" + displayPath + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.check[" + displayPath + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.install[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.reload[" + cn.getDisplayName() + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.resources[" + type + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.resources[" + type + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log("ManagerServlet.serverinfo",t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.sessions[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log(sm.getString("managerServlet.startFailed", displayPath), t); writer.println(smClient.getString("managerServlet.startFailed", displayPath)); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.stop[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.undeploy[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { if (war.exists() && !war.delete()) { writer.println( smClient.getString("managerServlet.deleteFail", war)); } throw e; }
540
close 35
                  
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (writer != null) { try { writer.close(); writer = null; } catch (Exception e1) { // do nothing } } // Remove the generated .java file File file = new File(javaFileName); if (file.exists()) { if (!file.delete()) { log.warn(Localizer.getMessage( "jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath())); } } throw e; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (EnableDTDValidationException e) { saxParser = getSAXParser(true, jspDocParser); jspDocParser.isValidating = true; if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } inStream = JspUtil.getInputStream(path, jarFile, jspDocParser.ctxt); saxParser.parse(new InputSource(inStream), jspDocParser); }
// in java/org/apache/jasper/JspC.java
catch (IOException ex) { fis.close(); throw ex; }
// in java/org/apache/jasper/JspC.java
catch (IOException ex) { fos.close(); throw ex; }
// in java/org/apache/catalina/startup/PasswdUserDatabase.java
catch (Exception e) { if (reader != null) { try { reader.close(); } catch (IOException f) { // Ignore } reader = null; } }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NullPointerException e) { /* BZ 42449 - Kludge Sun's LDAP provider with broken SSL */ // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (CommunicationException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Log the problem for posterity containerLog.error(sm.getString("jndiRealm.exception"), e); // Close the connection so that it gets reopened next time if (context != null) close(context); // Return "not authenticated" for this request if (containerLog.isDebugEnabled()) containerLog.debug("Returning null principal."); return (null); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (CommunicationException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Log the problem for posterity containerLog.error(sm.getString("jndiRealm.exception"), e); // Close the connection so that it gets reopened next time if (context != null) close(context); // Return "not authenticated" for this request return (null); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { // Log the problem for posterity containerLog.error(sm.getString("jdbcRealm.exception"), e); // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { // Log the problem for posterity containerLog.error(sm.getString("jdbcRealm.exception"), e); // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { // Log the problem for posterity containerLog.error(sm.getString("jdbcRealm.exception"), e); // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
catch (IOException e) { if (writer != null) { writer.close(); } fileNew.delete(); throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.unloading.ioe", e), e); try { oos.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); keys = new String[0]; // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException e) { if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException e) { if (fos != null) { try { fos.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { // Log the problem for posterity container.getLogger().error(sm.getString("jdbcAccessLogValve.exception"), e); // Close the connection so that it gets reopened next time if (conn != null) { close(); } }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (Exception ex) { log.error("Unable to connect to proxy: " + ex); close(i); }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (Exception ex) { log.error("Unable to send collected load information to proxy: " + ex); close(i); }
// in java/org/apache/catalina/ha/backend/MultiCastSender.java
catch (Exception ex) { log.error("Unable to send colllected load information: " + ex); s.close(); s = null; return -1; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IllegalStateException e) { try { ServletOutputStream stream = response.getOutputStream(); stream.close(); } catch (IllegalStateException f) { // Ignore } catch (IOException f) { // Ignore } }
390
getClass 32
                  
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn("Error processing preDestroy on tag instance of " + handler.getClass().getName(), t); }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn("Error processing preDestroy on tag instance of " + handler.getClass().getName(), t); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (SecurityException ex1) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: SecurityException for " + o.getClass() + " " + name + "=" + value + ")", ex1); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalAccessException iae) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: IllegalAccessException for " + o.getClass() + " " + name + "=" + value + ")", iae); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); if (log.isDebugEnabled()) log.debug("IntrospectionUtils: InvocationTargetException for " + o.getClass() + " " + name + "=" + value + ")", ie); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (SecurityException ex1) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: SecurityException for " + o.getClass() + " " + name + ")", ex1); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalAccessException iae) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: IllegalAccessException for " + o.getClass() + " " + name + ")", iae); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); if (log.isDebugEnabled()) log.debug("IntrospectionUtils: InvocationTargetException for " + o.getClass() + " " + name + ")"); }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
catch (Exception e) { // log message and error if (digester.log.isInfoEnabled()) { digester.log.info("[FactoryCreateRule] Create exception ignored: " + ((e.getMessage() == null) ? e.getClass().getName() : e.getMessage())); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule] Ignored exception:", e); } } exceptionIgnoredStack.push(Boolean.TRUE); }
// in java/org/apache/tomcat/util/digester/XercesParser.java
catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); }
// in java/org/apache/tomcat/util/digester/GenericParser.java
catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); }
// in java/org/apache/el/lang/ELSupport.java
catch (IllegalArgumentException iae) { throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/catalina/startup/WebRuleSet.java
catch (NoSuchMethodException e) { digester.getLogger().error("Can't find method " + method + " in " + top + " CLASS " + top.getClass()); return; }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage())); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in object instance of class " + instance.getClass().getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException nfe){ targetField = thread.getClass().getDeclaredField("runnable"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException nfe){ Method cancelMethod = thread.getClass().getDeclaredMethod("cancel"); if (null != cancelMethod){ synchronized(thread) { cancelMethod.setAccessible(true); cancelMethod.invoke(thread); } } }
// in java/org/apache/catalina/realm/CombinedRealm.java
catch (LifecycleException e) { // If realm doesn't start can't authenticate against it iter.remove(); log.error(sm.getString("combinedRealm.realmStartFail", realm.getClass().getName()), e); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (ClassCastException cce) { project.log("wrong object reference " + refId + " - " + pref.getClass()); return null; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (ClassCastException cce) { getProject().log( "Wrong object reference " + getRef() + " - " + pref.getClass()); return null; }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IOException ioe) { log.warn("onComplete() failed for listener of type [" + listener.getClass().getName() + "]", ioe); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IOException ioe) { log.warn("onStartAsync() failed for listener of type [" + listener.getClass().getName() + "]", ioe); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IOException ioe) { log.warn("onStartAsync() failed for listener of type [" + listener.getClass().getName() + "]", ioe); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextInitialized", listener); getLogger().error (sm.getString("standardContext.listenerStart", instances[i].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextDestroyed", listener); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[i].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[j].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
354
getContainer 31
                  
// in java/org/apache/catalina/session/StoreBase.java
catch (IOException e) { manager.getContainer().getLogger().error("Error getting keys", e); return; }
// in java/org/apache/catalina/session/StoreBase.java
catch (Exception e) { manager.getContainer().getLogger().error("Session: "+keys[i]+"; ", e); try { remove(keys[i]); } catch (IOException e2) { manager.getContainer().getLogger().error("Error removing key", e2); } }
// in java/org/apache/catalina/session/StoreBase.java
catch (IOException e2) { manager.getContainer().getLogger().error("Error removing key", e2); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); keys = new String[0]; // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionSQLException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (NamingException e) { manager.getContainer().getLogger().error( sm.getString(getStoreName() + ".wrongDataSource", this.dataSourceName), e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (ClassNotFoundException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (InstantiationException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (IllegalAccessException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".commitSQLException"), e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".close", e.toString())); // Just log it here }
// in java/org/apache/catalina/session/FileStore.java
catch (FileNotFoundException e) { if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug("No persisted data file found"); return (null); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionCreated", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent( "afterSessionDestroyed", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Exception e) { manager.getContainer().getLogger().error( sm.getString("standardSession.logoutfail"), e); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t){ manager.getContainer().getLogger().error (sm.getString("standardSession.bindingEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.bindingEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { if (unbound != null) { context.fireContainerEvent( "afterSessionAttributeReplaced", listener); } else { context.fireContainerEvent("afterSessionAttributeAdded", listener); } } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (NotSerializableException e) { manager.getContainer().getLogger().warn (sm.getString("standardSession.notSerializable", saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug (" storing attribute '" + saveNames.get(i) + "' with value NOT_SERIALIZED"); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionAttributeRemoved", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException ioe) { res.setStatus(400); res.setMessage("Invalid URI: " + ioe.getMessage()); connector.getService().getContainer().logAccess( request, response, 0, true); return false; }
138
jspError 31
                  
// in java/org/apache/jasper/compiler/JspUtil.java
catch (UnsupportedEncodingException ex) { err.jspError("jsp.error.unsupported.encoding", encoding); }
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
catch (NumberFormatException e) { err.jspError("jsp.error.invalid.implicit.version", path); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (NumberFormatException ex) { errDispatcher.jspError(ex); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (UnsupportedEncodingException ex) { errDispatcher.jspError("jsp.error.needAlternateJavaEncoding", javaEncoding); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (FileNotFoundException ex) { err.jspError(mark, "jsp.error.file.not.found", tldName); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Exception ex) { err.jspError(mark, "jsp.error.tld.unable_to_read", jarResource.getUrl(), tldName, ex.toString()); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Exception ex) { err.jspError("jsp.error.tld.unable_to_get_jar", uri, ex .toString()); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Exception e) { err.jspError("jsp.error.teiclass.instantiation", teiClassName, e); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Exception e) { err.jspError("jsp.error.tlvclass.instantiation", validatorClass, e); }
// in java/org/apache/jasper/compiler/Parser.java
catch (IllegalArgumentException iae) { // Duplicate attribute err.jspError(reader.mark(), "jsp.error.attribute.duplicate"); }
// in java/org/apache/jasper/compiler/Parser.java
catch (IllegalArgumentException iae) { err.jspError(start, iae.getMessage()); }
// in java/org/apache/jasper/compiler/Parser.java
catch (FileNotFoundException ex) { err.jspError(start, "jsp.error.file.not.found", file); }
// in java/org/apache/jasper/compiler/Parser.java
catch (Exception ex) { err.jspError(start, ex.getMessage()); }
// in java/org/apache/jasper/compiler/Parser.java
catch (Exception e) { err.jspError(start, "jsp.error.loadclass.taghandler", handlerClassName, tagName); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
catch (FileNotFoundException e) { err.jspError("jsp.error.file.not.found", path); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
catch (IOException e) { err.jspError("jsp.error.file.not.found", path); }
// in java/org/apache/jasper/compiler/PageInfo.java
catch (NumberFormatException e) { if (n == null) { err.jspError("jsp.error.page.invalid.buffer"); } else { err.jspError(n, "jsp.error.page.invalid.buffer"); } }
// in java/org/apache/jasper/compiler/JspReader.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.error("Exception parsing file ", ex); // Pop state being constructed: popFile(); err.jspError("jsp.error.file.cannot.read", file); }
// in java/org/apache/jasper/compiler/Generator.java
catch (Exception e) { // Cannot instantiate the specified class, either a // compilation error or a runtime error will be raised, // depending on a compiler flag. if (ctxt.getOptions() .getErrorOnUseBeanInvalidClassAttribute()) { err.jspError(n, "jsp.error.invalid.bean", klass); } if (canonicalName == null) { // Doing our best here to get a canonical name // from the binary name, should work 99.99% of time. canonicalName = klass.replace('$', '.'); } }
// in java/org/apache/jasper/compiler/Generator.java
catch (IntrospectionException ie) { err.jspError(n, "jsp.error.introspect.taghandler", tagHandlerClass.getName(), ie); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (IOException ioe) { jspDocParser.err.jspError("jsp.error.data.file.read", path, ioe); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (SAXParseException e) { jspDocParser.err.jspError (new Mark(jspDocParser.ctxt, path, e.getLineNumber(), e.getColumnNumber()), e.getMessage()); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { jspDocParser.err.jspError(e); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError (n, "jsp.error.unknown_attribute_type", tldAttr.getName(), expectedType); }
// in java/org/apache/jasper/compiler/Validator.java
catch (Exception e) { err.jspError (n, "jsp.error.coerce_to_type", tldAttr.getName(), expectedType, attrs.getValue(i)); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", attrs.getValue(i), e.toString()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", value, e .toString()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError("jsp.error.function.classnotfound", n .getFunctionInfo().getFunctionClass(), n .getPrefix() + ':' + n.getName(), e.getMessage()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError("jsp.error.signature.classnotfound", paramTypes[i], n.getPrefix() + ':' + n.getName(), e.getMessage()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (NoSuchMethodException e) { err.jspError("jsp.error.noFunctionMethod", n .getMethodName(), n.getName(), c.getName()); }
280
getLog 30
                  
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().error(sm.getString( "abstractProtocolHandler.mbeanRegistrationFailed", tpOname, getName()), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.initError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.startError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.pauseError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.resumeError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.stopError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().error(sm.getString("abstractProtocolHandler.destroyError", getName()), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch(java.net.SocketException e) { // SocketExceptions are normal getLog().debug(sm.getString( "ajpprotocol.proto.socketexception.debug"), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (java.io.IOException e) { // IOExceptions are normal getLog().debug(sm.getString( "ajpprotocol.proto.ioexception.debug"), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); // any other exception or error is odd. Here we log it // with "ERROR" level, so it will show up even on // less-than-verbose logs. getLog().error(sm.getString("ajpprotocol.proto.error"), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().warn("Error registering request"); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().warn("Error unregistering request", e); }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (java.security.cert.CertificateException e) { getLog().error(sm.getString("ajpprocessor.certs.fail"), e); return; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (NoSuchProviderException e) { getLog().error(sm.getString("ajpprocessor.certs.fail"), e); return; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), e); } error = true; break; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), t); } // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug(sm.getString( "http11processor.request.prepare"), t); } // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString( "http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.finish"), t); // 500 - Internal Server Error // Can't add a 500 to the access log since that has already been // written in the Adapter.service method. response.setStatus(500); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.response.finish"), t); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Protocol.java
catch (Exception ex) { getLog().warn("Failed to init light protocol " + impl, ex); }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
catch ( Exception x ) { getLog().error("Unable to set attribute \""+name+"\" to \""+value+"\"",x); return false; }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
catch(Exception e) { if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("endpoint.debug.unlock", "" + getPort()), e); } }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); LogFactory.getLog("org.apache.tomcat.util.digester.Digester"). error("Unable to load property source["+className+"].",t); }
272
info 30
                  
// in java/org/apache/naming/resources/WARDirContext.java
catch (InvalidNameException e) { log.info(sm.getString("resources.invalidName", strName), e); return null; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Error e) { e.printStackTrace(); if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(" endpoint.poll.limitedpollsize " + size); return 0; } else if (Status.APR_STATUS_IS_ENOTIMPL(e.getError())) { // thread safe not supported log.severe("THREAD SAFE NOT SUPPORTED" + e); threadSafe = false; // try again without the flags continue; } else { log.severe("endpoint.poll.initfail" + e); return 0; } }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { log.info("Error parsing head SYN_STREAM" + t); abort("Error reading headers " + t); return CLOSE; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Error e) { if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(sm.getString("endpoint.poll.limitedpollsize", "" + size)); return 0; } else { log.error(sm.getString("endpoint.poll.initfail"), e); return -1; } }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch(Exception ex) { log.info(sm.getString( "jseeSupport.certTranslationError", certs[i]), ex); return null; }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch(SSLException sslex) { log.info(sm.getString("jsseSupport.clientCertError"), sslex); throw sslex; }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IllegalStateException ise) { // Hitting limit stops processing further params but does // not cause request to fail. parseFailed = true; UserDataHelper.Mode logMode = maxParamCountLog.getNextMode(); if (logMode != null) { String message = ise.getMessage(); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString( "parameters.maxCountFail.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } break; }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException e) { parseFailed = true; decodeFailCount++; if (decodeFailCount == 1 || log.isDebugEnabled()) { if (log.isDebugEnabled()) { log.debug(sm.getString("parameters.decodeFail.debug", origName.toString(), origValue.toString()), e); } else if (log.isInfoEnabled()) { UserDataHelper.Mode logMode = userDataLog.getNextMode(); if (logMode != null) { String message = sm.getString( "parameters.decodeFail.info", tmpName.toString(), tmpValue.toString()); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString("parameters.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } } } }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch (MalformedObjectNameException e) { log.info("Error creating object name " + e ); }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Exception t ) { if( failFirst ) throw t; log.info("Error initializing " + current + " " + t.toString()); }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch (Exception e) { log.info( "Can't find metadata for object" + oname ); return null; }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch (Exception e) { log.info( "Can't find metadata " + oname ); return null; }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
catch (Exception e) { // log message and error if (digester.log.isInfoEnabled()) { digester.log.info("[FactoryCreateRule] Create exception ignored: " + ((e.getMessage() == null) ? e.getClass().getName() : e.getMessage())); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule] Ignored exception:", e); } } exceptionIgnoredStack.push(Boolean.TRUE); }
// in java/org/apache/tomcat/util/digester/XercesParser.java
catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); }
// in java/org/apache/tomcat/util/digester/GenericParser.java
catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage())); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalStateException e) { log.info(sm.getString("webappClassLoader.stopped", name), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { log.info(sm.getString("webappClassLoader.clearRmiInfo", contextName), e); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This is likely a dual registration log.info("Dual registration of jndi stream handler: " + t.getMessage()); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind server socket to:" + addr + " throwing error."); throw x; } port++; }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (BindException e) { /* * On some platforms (e.g. Linux) it is not possible to bind * to the multicast address. In this case only bind to the * port. */ log.info("Binding to multicast address, failed. Binding to port only."); socket = new MulticastSocket(port); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.info(sm.getString("accessLogValve.closeFail"), e); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.info(sm.getString("aprListener.aprDestroy")); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.info(sm.getString("aprListener.aprInit", System.getProperty("java.library.path"))); return; }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception ex) { log.info(sm.getString("applicationFilterConfig.jmxRegisterFail", getFilterClass(), getFilterName()), ex); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch( Exception ex ) { log.info("Error registering JSP monitoring with jmx " + instance); }
245
getException 29
                  
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); throw (JasperException)e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof ClassNotFoundException){ throw (ClassNotFoundException)exception; } else if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in load() " + exception); }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in unLoad() " + exception); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); log.error("Exception clearing the Store: " + exception, exception); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); log.error("Exception in the Store during load: " + exception, exception); return; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); log.error("Exception in the Store during removeSession: " + exception, exception); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (PrivilegedActionException ex) { Exception e = ex.getException(); log.error(sm.getString( "persistentManager.swapInException", id), e); if (e instanceof IOException){ throw (IOException)e; } else if (e instanceof ClassNotFoundException) { throw (ClassNotFoundException)e; } }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException) { throw (IOException) exception; } log.error("Exception in the Store during writeSession: " + exception, exception); }
// in java/org/apache/catalina/connector/OutputBuffer.java
catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } }
// in java/org/apache/catalina/connector/Response.java
catch (PrivilegedActionException pae){ IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(pae.getException()); throw iae; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage() ,e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/InputBuffer.java
catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } }
// in java/org/apache/catalina/connector/ResponseFacade.java
catch(PrivilegedActionException e){ Exception ex = e.getException(); if (ex instanceof IOException){ throw (IOException)ex; } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; }
// in java/org/apache/catalina/security/SecurityUtil.java
catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
33
clearNodeScope
26
                  
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte004) { if (jjtc004) { jjtree.clearNodeScope(jjtn004); jjtc004 = false; } else { jjtree.popNode(); } if (jjte004 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte004;} } if (jjte004 instanceof ParseException) { {if (true) throw (ParseException)jjte004;} } {if (true) throw (Error)jjte004;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
26
popNode 26
                  
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte004) { if (jjtc004) { jjtree.clearNodeScope(jjtn004); jjtc004 = false; } else { jjtree.popNode(); } if (jjte004 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte004;} } if (jjte004 instanceof ParseException) { {if (true) throw (ParseException)jjte004;} } {if (true) throw (Error)jjte004;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
32
get 21
                  
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (AccessControlException ace) { // No permission to configure logging in context // Log and carry on ClassLoaderLogInfo info = classLoaderLoggers.get(ClassLoader.getSystemClassLoader()); if (info != null) { Logger log = info.loggers.get(""); if (log != null) { Permission perm = ace.getPermission(); if (perm instanceof FilePermission && perm.getActions().equals("read")) { log.warning("Reading " + perm.getName() + " is not permitted. See \"per context logging\" in the default catalina.policy file."); } else { log.warning("Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file."); log.warning("Original error was: " + ace.getMessage()); } } } }
// in java/org/apache/el/lang/ELSupport.java
catch (IllegalArgumentException iae) { throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ExpressionBuilder.java
catch (Exception e) { throw new ELException( MessageFactory.get("error.parseFail", expr), e); }
// in java/org/apache/el/parser/AstFunction.java
catch (ELException ele) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), ele); }
// in java/org/apache/el/parser/AstFunction.java
catch (IllegalAccessException iae) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), iae); }
// in java/org/apache/el/parser/AstFunction.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(MessageFactory.get("error.function", this .getOutputName()), cause); }
// in java/org/apache/catalina/tribes/group/interceptors/ThroughputInterceptor.java
catch ( ChannelException x ) { msgTxErr.addAndGet(1); if ( access.get() == 1 ) access.addAndGet(-1); throw x; }
// in java/org/apache/catalina/session/StandardSession.java
catch (NotSerializableException e) { manager.getContainer().getLogger().warn (sm.getString("standardSession.notSerializable", saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug (" storing attribute '" + saveNames.get(i) + "' with value NOT_SERIALIZED"); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
catch (NotSerializableException e) { log.error(sm.getString("standardSession.notSerializable",saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); log.error(" storing attribute '" + saveNames.get(i)+ "' with value NOT_SERIALIZED"); }
811
sendError 21
                  
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); }
// in java/org/apache/catalina/authenticator/SSLAuthenticator.java
catch (IllegalStateException ise) { // Request body was too large for save buffer response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.certificates")); return false; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (LoginException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail", e)); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (PrivilegedActionException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail", e)); response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (IOException ioe) { log.debug("Request body too big to save during authentication"); response.sendError(HttpServletResponse.SC_FORBIDDEN, sm.getString("authenticator.requestBodyTooBig")); return (false); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardLoginFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardErrorFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NumberFormatException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NumberFormatException e) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse .SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NumberFormatException e) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse .SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (SAXException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (IOException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { resp.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch(SAXException saxe) { // Parse error - assume invalid content resp.sendError(WebdavStatus.SC_UNSUPPORTED_MEDIA_TYPE); return; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); return false; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error( sm.getString("standardWrapper.allocateException", wrapper.getName()), e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
// in java/org/apache/catalina/core/StandardContextValve.java
catch (IOException ioe) { container.getLogger().error(sm.getString( "standardContextValve.acknowledgeException"), ioe); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; }
126
setStatus 20
                  
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { response.setStatus(400); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), t); } // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug(sm.getString( "http11processor.request.prepare"), t); } // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString( "http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.finish"), t); // 500 - Internal Server Error // Can't add a 500 to the access log since that has already been // written in the Adapter.service method. response.setStatus(500); error = true; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error t.printStackTrace(); response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
// in java/org/apache/catalina/connector/Response.java
catch (IllegalArgumentException e) { setStatus(SC_NOT_FOUND); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException ioe) { res.setStatus(400); res.setMessage("Invalid URI: " + ioe.getMessage()); connector.getService().getContainer().logAccess( request, response, 0, true); return false; }
97
fireInstanceEvent 17
                  
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (UnavailableException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); unavailable(f); throw f; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw f; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ClientAbortException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); ioException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); ioException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (UnavailableException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); servletException = e; wrapper.unavailable(e); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause); } servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); runtimeException = e; }
27
exception 16
                  
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ClientAbortException e) { throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ClientAbortException e) { throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
27
Integer 15
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put (dest, new Integer(WebdavStatus.SC_CONFLICT)); return false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put (dest, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR)); return false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { if (e.getCause() instanceof FileNotFoundException) { // We know the source exists so it must be the // destination dir that can't be found errorList.put(source, new Integer(WebdavStatus.SC_CONFLICT)); } else { errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR)); } return false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put(path, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put(path, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); return; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { if (!(object instanceof DirContext)) { // If it's not a collection, then it's an unknown // error errorList.put (childName, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put (childName, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); }
310
getAbsolutePath 14
                  
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (writer != null) { try { writer.close(); writer = null; } catch (Exception e1) { // do nothing } } // Remove the generated .java file File file = new File(javaFileName); if (file.exists()) { if (!file.delete()) { log.warn(Localizer.getMessage( "jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath())); } } throw e; }
// in java/org/apache/tomcat/buildutil/CheckEol.java
catch (IOException e) { throw new BuildException("Could not check file '" + file.getAbsolutePath() + "'", e); }
// in java/org/apache/tomcat/buildutil/Txt2Html.java
catch( IOException e ) { throw new BuildException( "Could not convert '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath() + "'", e ); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamFile", file.getAbsolutePath()),e); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.dirFail", fileList[i].getAbsolutePath()), ioe); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", contextXml.getAbsolutePath())); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployDescriptor.error", contextXml.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", war.getAbsolutePath())); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", war.getAbsolutePath())); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployWar.error", war.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployDir.error", dir.getAbsolutePath()), t); }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (Exception e) { log.warn("Error processing configuration file " + file.getAbsolutePath(), e); return; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException ioe) { // delete in case file is corrupted if (f.exists()) { if (!f.delete() && debug >= 2) { log("expandCGIScript: failed to delete '" + f.getAbsolutePath() + "'"); } } }
131
getDestination 13
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( IOException io ) { if ( x==null ) x = new ChannelException(io); x.addFaultyMember(senders[i].getDestination(),io); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( IOException io ) { if ( x==null ) x = new ChannelException(io); x.addFaultyMember(senders[i].getDestination(),io); }
18
getStoreName 13
                  
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); keys = new String[0]; // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionSQLException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (NamingException e) { manager.getContainer().getLogger().error( sm.getString(getStoreName() + ".wrongDataSource", this.dataSourceName), e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (ClassNotFoundException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (InstantiationException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (IllegalAccessException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".commitSQLException"), e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".close", e.toString())); // Just log it here }
25
fireContainerEvent 12
                  
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionCreated", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent( "afterSessionDestroyed", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { if (unbound != null) { context.fireContainerEvent( "afterSessionAttributeReplaced", listener); } else { context.fireContainerEvent("afterSessionAttributeAdded", listener); } } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionAttributeRemoved", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.fireContainerEvent("afterContextAttributeRemoved", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (replaced) context.fireContainerEvent("afterContextAttributeReplaced", listener); else context.fireContainerEvent("afterContextAttributeAdded", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextInitialized", listener); getLogger().error (sm.getString("standardContext.listenerStart", instances[i].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextDestroyed", listener); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
85
trace 12
                  
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { t.printStackTrace(); trace("< onData-ERROR() " + lastChannel); abort("Error processing socket" + t); return CLOSE; }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
catch (Exception e) { if (logger.isTraceEnabled()) logger.trace("Error creating " + implementations[i], e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { if (log.isTraceEnabled()) log.trace(" --> Passing on ClassNotFoundException"); throw e; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (AuthenticationException e) { if (containerLog.isTraceEnabled()) { containerLog.trace(" bind attempt failed"); } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x ) { if (log.isTraceEnabled()) log.trace("Error sending message", x); int faulty = (cx == null)?0:cx.getFaultyMembers().length; if ( cx == null ) { if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException("Parallel NIO send failed.", x); } else { if (x instanceof ChannelException) cx.addFaultyMember( ( (ChannelException) x).getFaultyMembers()); } //count down the remaining on an error if (faulty<cx.getFaultyMembers().length) remaining -= (cx.getFaultyMembers().length-faulty); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (CancelledKeyException ckx ) { NioReceiver.cancelledKey(key); if ( log.isTraceEnabled() ) log.trace("CKX Cancelling key:"+key); }
125
addFaultyMember 11
                  
// in java/org/apache/catalina/tribes/group/interceptors/OrderInterceptor.java
catch ( ChannelException x ) { if ( cx == null ) cx = x; cx.addFaultyMember(x.getFaultyMembers()); }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
catch (Exception x) { if (cx == null) cx = new ChannelException(x); cx.addFaultyMember(destination[i],x); }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
catch (Exception x ) { if ( cx== null ) cx = new ChannelException(x); cx.addFaultyMember(destination[i],x); }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
catch ( Exception e ) { if ( x == null ) x = new ChannelException(e); x.addFaultyMember(mbr,e); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x ) { if (log.isTraceEnabled()) log.trace("Error sending message", x); int faulty = (cx == null)?0:cx.getFaultyMembers().length; if ( cx == null ) { if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException("Parallel NIO send failed.", x); } else { if (x instanceof ChannelException) cx.addFaultyMember( ( (ChannelException) x).getFaultyMembers()); } //count down the remaining on an error if (faulty<cx.getFaultyMembers().length) remaining -= (cx.getFaultyMembers().length-faulty); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( IOException io ) { if ( x==null ) x = new ChannelException(io); x.addFaultyMember(senders[i].getDestination(),io); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( IOException io ) { if ( x==null ) x = new ChannelException(io); x.addFaultyMember(senders[i].getDestination(),io); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( UnknownHostException x ) { if (cx == null) cx = new ChannelException("Unable to setup NioSender.", x); cx.addFaultyMember(destination[i], x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( Exception e ) { if ( x == null ) x = new ChannelException(e); x.addFaultyMember(mbr,e); }
16
getRootCause 11
                  
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { rootCause.printStackTrace(); } throw je; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (ServletException e) { getLogger().error(sm.getString("standardWrapper.loadException", getName()), StandardWrapper.getRootCause(e)); // NOTE: load errors (including a servlet that throws // UnavailableException from tht init() method) are NOT // fatal to application startup }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause); } servletException = e; }
15
handleErrorOutput 11
                  
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to integer:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to long:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to float:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to double:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (MalformedObjectNameException e) { if (isEcho()) handleErrorOutput("Unable to convert to ObjectName:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (UnknownHostException exc) { if (isEcho()) handleErrorOutput("Unable to resolve host name:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
catch (Exception e) { if (isEcho()) handleErrorOutput(e.getMessage()); return "Can't query mbeans " + qry; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
catch (Exception e) { if (isEcho()) handleErrorOutput("Error getting attribute " + oname + " " + pname + attName + " " + e.toString()); continue; }
// in java/org/apache/catalina/ant/ValidatorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException("Validation failure", e); } else { handleErrorOutput("Validation failure: " + e); } }
13
isTraceEnabled 11
                  
// in java/org/apache/tomcat/util/net/SSLImplementation.java
catch (Exception e) { if (logger.isTraceEnabled()) logger.trace("Error creating " + implementations[i], e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { if (log.isTraceEnabled()) log.trace(" --> Passing on ClassNotFoundException"); throw e; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (AuthenticationException e) { if (containerLog.isTraceEnabled()) { containerLog.trace(" bind attempt failed"); } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x ) { if (log.isTraceEnabled()) log.trace("Error sending message", x); int faulty = (cx == null)?0:cx.getFaultyMembers().length; if ( cx == null ) { if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException("Parallel NIO send failed.", x); } else { if (x instanceof ChannelException) cx.addFaultyMember( ( (ChannelException) x).getFaultyMembers()); } //count down the remaining on an error if (faulty<cx.getFaultyMembers().length) remaining -= (cx.getFaultyMembers().length-faulty); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (CancelledKeyException ckx ) { NioReceiver.cancelledKey(key); if ( log.isTraceEnabled() ) log.trace("CKX Cancelling key:"+key); }
114
cancelledKey 10
                  
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (CancelledKeyException ckx) { try { socket.getPoller().cancelledKey(key,SocketStatus.DISCONNECT); }catch (Exception ignore) {} }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( CancelledKeyException ckx ) { cancelledKey(sk, SocketStatus.ERROR); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( IOException x ) { if ( log.isDebugEnabled() ) log.debug("Unable to complete sendfile request:", x); cancelledKey(sk,SocketStatus.ERROR); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable t ) { log.error("",t); cancelledKey(sk, SocketStatus.ERROR); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( CancelledKeyException ckx ) { cancelledKey(key, SocketStatus.ERROR); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch(CancelledKeyException cx) { socket.getPoller().cancelledKey(key,null); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; socket.getPoller().cancelledKey(key,SocketStatus.ERROR); releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable t ) { log.error("",t); socket.getPoller().cancelledKey(key,SocketStatus.ERROR); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (CancelledKeyException ckx ) { NioReceiver.cancelledKey(key); if ( log.isTraceEnabled() ) log.trace("CKX Cancelling key:"+key); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch ( CancelledKeyException ckx ) { cancelledKey(key); }
23
interrupted
10
                  
// in java/org/apache/juli/AsyncFileHandler.java
catch (InterruptedException x) { //allow thread to be interrupted and back out of the publish operation //after this we clear the flag Thread.interrupted(); }
// in java/org/apache/juli/AsyncFileHandler.java
catch (InterruptedException x) { Thread.interrupted(); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (InterruptedException ignore) { Thread.interrupted(); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (InterruptedException ignore) { Thread.interrupted(); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore and clean the interrupt flag Thread.interrupted(); }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( InterruptedException x ) { interrupted(); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpPingInterceptor.java
catch ( InterruptedException ix ) { interrupted(); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( InterruptedException x ) { Thread.interrupted(); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception x ) { if (x instanceof InterruptedException) interrupted(); else { if (errorCounter==0 && doRunReceiver) log.warn("Error receiving mcast package. Sleeping 500ms",x); else if (log.isDebugEnabled()) log.debug("Error receiving mcast package"+(doRunReceiver?". Sleeping 500ms":"."),x); if (doRunReceiver) { try { Thread.sleep(500); } catch ( Exception ignore ){} if ( (++errorCounter)>=recoveryCounter ) { errorCounter=0; RecoveryThread.recover(McastServiceImpl.this); } } } }
10
put 10
                  
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put (dest, new Integer(WebdavStatus.SC_CONFLICT)); return false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put (dest, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR)); return false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { if (e.getCause() instanceof FileNotFoundException) { // We know the source exists so it must be the // destination dir that can't be found errorList.put(source, new Integer(WebdavStatus.SC_CONFLICT)); } else { errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR)); } return false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put(path, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put(path, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); return; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { if (!(object instanceof DirContext)) { // If it's not a collection, then it's an unknown // error errorList.put (childName, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put (childName, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); }
1022
reset 10
                  
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch(IOException e) { buf.reset(); continue; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (IOException e) { apr.reset(); throw e; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable e) { apr.reset(); e.printStackTrace(); throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable t) { t.printStackTrace(); // no error handler yet reset(); notifyError(t, false); return; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException t) { reset(); // also sets status ERROR if (handler instanceof AprSocketContext.NonBlockingPollHandler) { ((AprSocketContext.NonBlockingPollHandler) handler).process(this, false, false, true); } notifyError(t, false); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable e) { log.log(Level.SEVERE, this + " error ", e); reset(); // no notifyIO - just did it. }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); ch.reset(); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
catch( IOException ex) { if(log.isDebugEnabled()) { log.debug("B2CConverter: Reseting the converter " + ex.toString()); } reset(); throw ex; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( IOException x ) { sender.disconnect(); sender.reset(); //nioSenders.remove(entry.getKey()); i.remove(); result = true; }
// in java/org/apache/catalina/util/URLEncoder.java
catch(IOException e) { buf.reset(); continue; }
113
currentThread 9
                  
// in java/org/apache/naming/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { tempBundle = ResourceBundle.getBundle( bundleName, Locale.getDefault(), cl); } catch(MissingResourceException ex2) { // Ignore } } }
// in java/org/apache/tomcat/util/res/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { bnd = ResourceBundle.getBundle(bundleName, locale, cl); } catch(MissingResourceException ex2) { // Ignore } } }
// in java/org/apache/catalina/tribes/group/RpcChannel.java
catch ( InterruptedException ix ) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/group/interceptors/SimpleCoordinator.java
catch (final InterruptedException e) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/bio/util/SingleRemoveSynchronizedAddLock.java
catch ( InterruptedException e ) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/bio/util/SingleRemoveSynchronizedAddLock.java
catch ( InterruptedException e ) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch (InterruptedException ti) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/RxTaskPool.java
catch (java.lang.InterruptedException x) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/util/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { bundle = ResourceBundle.getBundle( bundleName, Locale.getDefault(), cl); } catch(MissingResourceException ex2) { // Ignore } } }
160
exit 9
                  
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { System.err.println(je); if (jspc.dieLevel != NO_DIE_LEVEL) { System.exit(jspc.dieLevel); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { log.error("Catalina.stop: ", e); System.exit(1); }
// in java/org/apache/catalina/startup/Catalina.java
catch (IOException e) { log.error("Catalina.stop: ", e); System.exit(1); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (Throwable t) { handleThrowable(t); log.error("Class loader creation threw exception", t); System.exit(1); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (Throwable t) { // Unwrap the Exception for clearer error reporting if (t instanceof InvocationTargetException && t.getCause() != null) { t = t.getCause(); } handleThrowable(t); t.printStackTrace(); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Class loader creation threw exception", t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Exception creating instance of " + className, t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Exception locating main() method", t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error("Exception calling main() method", t); System.exit(1); }
16
getDevelopment 9
                  
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; }
13
jjStopStringLiteralDfa_1 9
                  
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(0, active0); return 1; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(1, active0); return 2; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(2, active0); return 3; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(3, active0); return 4; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(4, active0); return 5; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(5, active0); return 6; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(6, active0); return 7; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(7, active0); return 8; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(8, active0); return 9; }
10
getProperty 8
                  
// in java/org/apache/tomcat/jni/Library.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } String name = System.mapLibraryName(NAMES[i]); String path = System.getProperty("java.library.path"); String sep = System.getProperty("path.separator"); String [] paths = path.split(sep); for (int j=0; j<paths.length; j++) { java.io.File fd = new java.io.File(paths[j] , name); if (fd.exists()) { t.printStackTrace(); } } if ( i > 0) err.append(", "); err.append(t.getMessage()); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { if (System.getProperty("java.vendor").startsWith("Sun")) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } else { log.debug(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x ) { log.error("Unable to parse mcastTTL="+properties.getProperty("mcastTTL"),x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x ) { log.error("Unable to parse mcastSoTimeout="+properties.getProperty("mcastSoTimeout"),x); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.info(sm.getString("aprListener.aprInit", System.getProperty("java.library.path"))); return; }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { if (System.getProperty("java.vendor").startsWith( "Sun")) { log.error(sm.getString( "jreLeakListener.gcDaemonFail"), e); } else { log.debug(sm.getString( "jreLeakListener.gcDaemonFail"), e); } }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { if (System.getProperty("java.vendor").startsWith( "Sun")) { log.error(sm.getString( "jreLeakListener.ldapPoolManagerFail"), e); } else { log.debug(sm.getString( "jreLeakListener.ldapPoolManagerFail"), e); } }
298
handleJspException
8
                  
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
8
isEcho 8
                  
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to integer:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to long:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to float:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to double:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (MalformedObjectNameException e) { if (isEcho()) handleErrorOutput("Unable to convert to ObjectName:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (UnknownHostException exc) { if (isEcho()) handleErrorOutput("Unable to resolve host name:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
catch (Exception e) { if (isEcho()) handleErrorOutput(e.getMessage()); return "Can't query mbeans " + qry; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
catch (Exception e) { if (isEcho()) handleErrorOutput("Error getting attribute " + oname + " " + pname + attName + " " + e.toString()); continue; }
15
isWarnEnabled 8
                  
// in java/org/apache/jasper/JspC.java
catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.checkInterval")); } }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval")); } }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.maxLoadedJsps", ""+this.maxLoadedJsps)); } }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.jspIdleTimeout", ""+this.jspIdleTimeout)); } }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { //this could be the channel listener throwing an exception, we should log it //as a warning. if ( log.isWarnEnabled() ) log.warn("Error receiving message:",x); throw new RemoteProcessException("Exception:"+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch ( IOException ignore ){ if (log.isWarnEnabled()) { log.warn("Unable to cleanup on selector close.",ignore); } }
44
getCharset 7
                  
// in java/org/apache/catalina/ant/JMXSetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/ResourcesTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JMXGetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/AbstractCatalinaCommandTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JKStatusUpdateTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JMXQueryTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
45
getFaultyMembers 7
                  
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( ChannelException cx ) { FaultyMember[] mbrs = cx.getFaultyMembers(); for ( int i=0; i<mbrs.length; i++ ) { if ( mbrs[i].getCause()!=null && (!(mbrs[i].getCause() instanceof RemoteProcessException)) ) {//RemoteProcessException's are ok this.memberDisappeared(mbrs[i].getMember()); }//end if }//for throw cx; }
// in java/org/apache/catalina/tribes/group/interceptors/OrderInterceptor.java
catch ( ChannelException x ) { if ( cx == null ) cx = x; cx.addFaultyMember(x.getFaultyMembers()); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x ) { if (log.isTraceEnabled()) log.trace("Error sending message", x); int faulty = (cx == null)?0:cx.getFaultyMembers().length; if ( cx == null ) { if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException("Parallel NIO send failed.", x); } else { if (x instanceof ChannelException) cx.addFaultyMember( ( (ChannelException) x).getFaultyMembers()); } //count down the remaining on an error if (faulty<cx.getFaultyMembers().length) remaining -= (cx.getFaultyMembers().length-faulty); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException ce) { // Handle known failed members FaultyMember[] faultyMembers = ce.getFaultyMembers(); for (FaultyMember faultyMember : faultyMembers) { memberDisappeared(faultyMember.getMember()); } }
8
getServletContext 7
                  
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); jsw.getServletContext().log("Background compile failed", t); }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { getServletContext().log (sm.getString("hostManagerServlet.startFailed", name), e); writer.println(smClient.getString( "hostManagerServlet.startFailed", name)); writer.println(smClient.getString( "hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { getServletContext().log(sm.getString( "hostManagerServlet.stopFailed", name), e); writer.println(smClient.getString("hostManagerServlet.stopFailed", name)); writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log("ManagerServlet.serverinfo",t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log(sm.getString("managerServlet.startFailed", displayPath), t); writer.println(smClient.getString("managerServlet.startFailed", displayPath)); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { getServletContext().log(sm.getString ("standardWrapper.unloadException", getName()), e); }
134
setAttribute 7
                  
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (IllegalStateException ise) { // at least 1 of the sessions is invalidated req.setAttribute(APPLICATION_ERROR, "Can't sort session list: one session is invalidated"); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardLoginFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardErrorFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); }
// in java/org/apache/catalina/core/StandardContextValve.java
catch (IOException ioe) { container.getLogger().error(sm.getString( "standardContextValve.acknowledgeException"), ioe); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); throwable(request, response, t); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[i].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[j].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
186
createSAXException 6
                  
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Finish event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Body event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("End event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { throw createSAXException("endPrefixMapping popped too many times"); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Begin event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { throw createSAXException(e); }
8
getAbsoluteFile 6
                  
// in java/org/apache/catalina/startup/Bootstrap.java
catch (IOException ioe) { homeFile = f.getAbsoluteFile(); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (IOException ioe) { homeFile = f.getAbsoluteFile(); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (IOException ioe) { homeFile = f.getAbsoluteFile(); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (IOException ioe) { baseFile = baseFile.getAbsoluteFile(); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (IOException e) { baseFile = baseFile.getAbsoluteFile(); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (IOException e) { homeFile = homeFile.getAbsoluteFile(); }
14
interrupt 6
                  
// in java/org/apache/catalina/tribes/group/RpcChannel.java
catch ( InterruptedException ix ) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/group/interceptors/SimpleCoordinator.java
catch (final InterruptedException e) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/bio/util/SingleRemoveSynchronizedAddLock.java
catch ( InterruptedException e ) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/bio/util/SingleRemoveSynchronizedAddLock.java
catch ( InterruptedException e ) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch (InterruptedException ti) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/RxTaskPool.java
catch (java.lang.InterruptedException x) { Thread.currentThread().interrupt(); }
20
open 6
                  
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
catch (NoSuchElementException x ) { try { synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 s = Selector.open(); } } catch (IOException iox) { } }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NullPointerException e) { /* BZ 42449 - Kludge Sun's LDAP provider with broken SSL */ // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (CommunicationException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (CommunicationException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); }
48
abort 5
                  
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (IOException ex) { abort("Compress error"); return false; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { t.printStackTrace(); trace("< onData-ERROR() " + lastChannel); abort("Error processing socket" + t); return CLOSE; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { abort("Error handling frame"); t.printStackTrace(); return CLOSE; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { log.log(Level.SEVERE, "Error parsing head SYN_STREAM", t); abort("Error reading headers " + t); return CLOSE; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { log.info("Error parsing head SYN_STREAM" + t); abort("Error reading headers " + t); return CLOSE; }
12
fatal 5
                  
// in java/org/apache/jasper/runtime/JspFactoryImpl.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.fatal("Exception initializing page context", ex); return null; }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
10
getAddress 5
                  
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (BindException orig) { String msg; if (getAddress() == null) msg = orig.getMessage() + " <null>:" + getPort(); else msg = orig.getMessage() + " " + getAddress().toString() + ":" + getPort(); BindException be = new BindException(msg); be.initCause(orig); throw be; }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
48
getAttempt
5
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
5
getLifecycle 5
                  
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassCastException e) { log.error(sm.getString("contextConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/TldConfig.java
catch (ClassCastException e) { log.error(sm.getString("tldConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/EngineConfig.java
catch (ClassCastException e) { log.error(sm.getString("engineConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/HostConfig.java
catch (ClassCastException e) { log.error(sm.getString("hostConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/UserConfig.java
catch (ClassCastException e) { log.error(sm.getString("hostConfig.cce", event.getLifecycle()), e); return; }
15
getPort 5
                  
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
catch(Exception e) { if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("endpoint.debug.unlock", "" + getPort()), e); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (BindException orig) { String msg; if (getAddress() == null) msg = orig.getMessage() + " <null>:" + getPort(); else msg = orig.getMessage() + " " + getAddress().toString() + ":" + getPort(); BindException be = new BindException(msg); be.initCause(orig); throw be; }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
63
getSenderState 5
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
12
reportError 5
                  
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { reportError(null, e, ErrorManager.FORMAT_FAILURE); return; }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { reportError(null, e, ErrorManager.WRITE_FAILURE); return; }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { reportError(null, e, ErrorManager.CLOSE_FAILURE); }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { reportError(null, e, ErrorManager.FLUSH_FAILURE); }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { reportError(null, e, ErrorManager.OPEN_FAILURE); writer = null; }
8
unavailable 5
                  
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ClassCastException e) { unavailable(null); // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.notServlet", servletClass), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (UnavailableException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); unavailable(f); throw f; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (UnavailableException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); servletException = e; wrapper.unavailable(e); }
8
append 4
                  
// in java/org/apache/tomcat/jni/Library.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } String name = System.mapLibraryName(NAMES[i]); String path = System.getProperty("java.library.path"); String sep = System.getProperty("path.separator"); String [] paths = path.split(sep); for (int j=0; j<paths.length; j++) { java.io.File fd = new java.io.File(paths[j] , name); if (fd.exists()) { t.printStackTrace(); } } if ( i > 0) err.append(", "); err.append(t.getMessage()); }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); sb.append("NON-STRINGABLE VALUE"); }
// in java/javax/servlet/http/HttpUtils.java
catch (StringIndexOutOfBoundsException e) { String rest = s.substring(i); sb.append(rest); if (rest.length()==2) i++; }
2579
cancel 4
                  
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (CancelledKeyException cx) { cancel(sk,key,ops); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (ClosedChannelException cx) { cancel(sk,key,ops); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (CancelledKeyException cx) { if (sk!=null) { sk.cancel(); sk.attach(null); } }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (CancelledKeyException ckx) { sk.cancel(); countDown(attachment.getReadLatch()); countDown(attachment.getWriteLatch()); }
16
countDownConnection 4
                  
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw ioe; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw e; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (IOException ioe) { countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw ioe; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket reprocessing request was rejected for:"+socket,x); try { //unable to handle connection at this time handler.process(socket, SocketStatus.DISCONNECT); } finally { countDownConnection(); } }
13
delete 4
                  
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (writer != null) { try { writer.close(); writer = null; } catch (Exception e1) { // do nothing } } // Remove the generated .java file File file = new File(javaFileName); if (file.exists()) { if (!file.delete()) { log.warn(Localizer.getMessage( "jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath())); } } throw e; }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
catch (IOException e) { if (writer != null) { writer.close(); } fileNew.delete(); throw e; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { if (war.exists() && !war.delete()) { writer.println( smClient.getString("managerServlet.deleteFail", war)); } throw e; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException ioe) { // delete in case file is corrupted if (f.exists()) { if (!f.delete() && debug >= 2) { log("expandCGIScript: failed to delete '" + f.getAbsolutePath() + "'"); } } }
56
disconnect 4
                  
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
catch (ChannelException x) { sender.disconnect(); throw x; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x ) { try { this.disconnect(); } catch (Exception e) {/*Ignore*/} if ( x instanceof ChannelException ) throw (ChannelException)x; else throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( IOException x ) { sender.disconnect(); sender.reset(); //nioSenders.remove(entry.getKey()); i.remove(); result = true; }
18
exists 4
                  
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (writer != null) { try { writer.close(); writer = null; } catch (Exception e1) { // do nothing } } // Remove the generated .java file File file = new File(javaFileName); if (file.exists()) { if (!file.delete()) { log.warn(Localizer.getMessage( "jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath())); } } throw e; }
// in java/org/apache/tomcat/jni/Library.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } String name = System.mapLibraryName(NAMES[i]); String path = System.getProperty("java.library.path"); String sep = System.getProperty("path.separator"); String [] paths = path.split(sep); for (int j=0; j<paths.length; j++) { java.io.File fd = new java.io.File(paths[j] , name); if (fd.exists()) { t.printStackTrace(); } } if ( i > 0) err.append(", "); err.append(t.getMessage()); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { if (war.exists() && !war.delete()) { writer.println( smClient.getString("managerServlet.deleteFail", war)); } throw e; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException ioe) { // delete in case file is corrupted if (f.exists()) { if (!f.delete() && debug >= 2) { log("expandCGIScript: failed to delete '" + f.getAbsolutePath() + "'"); } } }
116
getColumnNumber 4
                  
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (SAXParseException e) { jspDocParser.err.jspError (new Mark(jspDocParser.ctxt, path, e.getLineNumber(), e.getColumnNumber()), e.getMessage()); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXParseException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (SAXParseException e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); log.error(sm.getString("contextConfig.defaultPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (SAXParseException e) { log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e); log.error(sm.getString("contextConfig.applicationPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; }
16
getError 4
                  
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Error e) { e.printStackTrace(); if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(" endpoint.poll.limitedpollsize " + size); return 0; } else if (Status.APR_STATUS_IS_ENOTIMPL(e.getError())) { // thread safe not supported log.severe("THREAD SAFE NOT SUPPORTED" + e); threadSafe = false; // try again without the flags continue; } else { log.severe("endpoint.poll.initfail" + e); return 0; } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Error e) { if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(sm.getString("endpoint.poll.limitedpollsize", "" + size)); return 0; } else { log.error(sm.getString("endpoint.poll.initfail"), e); return -1; } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (running) { String msg = sm.getString("endpoint.accept.fail"); if (t instanceof Error) { Error e = (Error) t; if (e.getError() == 233) { // Not an error on HP-UX so log as a warning // so it can be filtered out on that platform // See bug 50273 log.warn(msg, t); } else { log.error(msg, t); } } else { log.error(msg, t); } } }
5
getLineNumber 4
                  
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (SAXParseException e) { jspDocParser.err.jspError (new Mark(jspDocParser.ctxt, path, e.getLineNumber(), e.getColumnNumber()), e.getMessage()); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXParseException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (SAXParseException e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); log.error(sm.getString("contextConfig.defaultPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (SAXParseException e) { log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e); log.error(sm.getString("contextConfig.applicationPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; }
24
getOptions 4
                  
// in java/org/apache/jasper/compiler/Generator.java
catch (Exception e) { // Cannot instantiate the specified class, either a // compilation error or a runtime error will be raised, // depending on a compiler flag. if (ctxt.getOptions() .getErrorOnUseBeanInvalidClassAttribute()) { err.jspError(n, "jsp.error.invalid.bean", klass); } if (canonicalName == null) { // Doing our best here to get a canonical name // from the binary name, should work 99.99% of time. canonicalName = klass.replace('$', '.'); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch ( Exception x ) { if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(Constants.FAIL_ACK_COMMAND); log.error("Error thrown from messageDataReceived.",x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( RemoteProcessException e ) { if ( log.isDebugEnabled() ) log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( Exception e ) { log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); }
64
getPoller 4
                  
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (CancelledKeyException ckx) { try { socket.getPoller().cancelledKey(key,SocketStatus.DISCONNECT); }catch (Exception ignore) {} }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch(CancelledKeyException cx) { socket.getPoller().cancelledKey(key,null); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; socket.getPoller().cancelledKey(key,SocketStatus.ERROR); releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable t ) { log.error("",t); socket.getPoller().cancelledKey(key,SocketStatus.ERROR); }
27
getTargetException
4
                  
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
catch (InvocationTargetException ite) { throw ite.getTargetException(); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
4
setRootCause
4
                  
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.beans.IntrospectionException ie) { NamingException ne = new NamingException(ie.getMessage()); ne.setRootCause(ie); throw ne; }
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.IllegalAccessException iae) { NamingException ne = new NamingException(iae.getMessage()); ne.setRootCause(iae); throw ne; }
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.InstantiationException ie2) { NamingException ne = new NamingException(ie2.getMessage()); ne.setRootCause(ie2); throw ne; }
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.reflect.InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } NamingException ne = new NamingException(ite.getMessage()); ne.setRootCause(ite); throw ne; }
4
setStateInternal 4
                  
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.startFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.stopFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); }
15
setSuspect
4
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
4
startsWith 4
                  
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { if (System.getProperty("java.vendor").startsWith("Sun")) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } else { log.debug(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { if (System.getProperty("java.vendor").startsWith( "Sun")) { log.error(sm.getString( "jreLeakListener.gcDaemonFail"), e); } else { log.debug(sm.getString( "jreLeakListener.gcDaemonFail"), e); } }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { if (System.getProperty("java.vendor").startsWith( "Sun")) { log.error(sm.getString( "jreLeakListener.ldapPoolManagerFail"), e); } else { log.debug(sm.getString( "jreLeakListener.ldapPoolManagerFail"), e); } }
267
write 4
                  
// in java/org/apache/catalina/ssi/SSIInclude.java
catch (IOException e) { ssiMediator.log("#include--Couldn't include file: " + substitutedValue, e); writer.write(configErrMsg); }
// in java/org/apache/catalina/ssi/SSIFlastmod.java
catch (IOException e) { ssiMediator.log( "#flastmod--Couldn't get last modified for file: " + substitutedValue, e); writer.write(configErrMsg); }
// in java/org/apache/catalina/ssi/SSIExec.java
catch (InterruptedException e) { ssiMediator.log("Couldn't exec file: " + substitutedValue, e); writer.write(configErrMsg); }
// in java/org/apache/catalina/ssi/SSIFsize.java
catch (IOException e) { ssiMediator.log("#fsize--Couldn't get size for file: " + substitutedValue, e); writer.write(configErrMsg); }
404
FailedContext 3
                  
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", contextXml.getAbsolutePath())); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", war.getAbsolutePath())); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", xml)); context = new FailedContext(); }
4
authenticate 3
                  
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NullPointerException e) { /* BZ 42449 - Kludge Sun's LDAP provider with broken SSL */ // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (CommunicationException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
33
closeOutboundConnection 3
                  
// in java/org/apache/catalina/websocket/StreamInbound.java
catch (MalformedInputException mie) { // Invalid UTF-8 closeOutboundConnection(Constants.STATUS_BAD_DATA, null); return SocketState.CLOSED; }
// in java/org/apache/catalina/websocket/StreamInbound.java
catch (UnmappableCharacterException uce) { // Invalid UTF-8 closeOutboundConnection(Constants.STATUS_BAD_DATA, null); return SocketState.CLOSED; }
// in java/org/apache/catalina/websocket/StreamInbound.java
catch (IOException ioe) { // Given something must have gone to reach this point, this // might not work but try it anyway. closeOutboundConnection(Constants.STATUS_PROTOCOL_ERROR, null); return SocketState.CLOSED; }
6
decrementAndGet 3
                  
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); }
23
getBundle 3
                  
// in java/org/apache/naming/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { tempBundle = ResourceBundle.getBundle( bundleName, Locale.getDefault(), cl); } catch(MissingResourceException ex2) { // Ignore } } }
// in java/org/apache/tomcat/util/res/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { bnd = ResourceBundle.getBundle(bundleName, locale, cl); } catch(MissingResourceException ex2) { // Ignore } } }
// in java/org/apache/catalina/tribes/util/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { bundle = ResourceBundle.getBundle( bundleName, Locale.getDefault(), cl); } catch(MissingResourceException ex2) { // Ignore } } }
16
getConfigFile 3
                  
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", getConfigFile()), e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (SAXParseException spe) { log.warn("Catalina.start using " + getConfigFile() + ": " + spe.getMessage()); return; }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { log.warn("Catalina.start using " + getConfigFile() + ": " , e); return; }
8
getContextClassLoader 3
                  
// in java/org/apache/naming/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { tempBundle = ResourceBundle.getBundle( bundleName, Locale.getDefault(), cl); } catch(MissingResourceException ex2) { // Ignore } } }
// in java/org/apache/tomcat/util/res/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { bnd = ResourceBundle.getBundle(bundleName, locale, cl); } catch(MissingResourceException ex2) { // Ignore } } }
// in java/org/apache/catalina/tribes/util/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { bundle = ResourceBundle.getBundle( bundleName, Locale.getDefault(), cl); } catch(MissingResourceException ex2) { // Ignore } } }
65
getDigestEncoding 3
                  
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
4
getKey 3
                  
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (Exception x) { log.error("Unable to apply diff to key:" + entry.getKey(), x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to relocate[" + entry.getKey() + "] to a new backup node", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to relocate[" + entry.getKey() + "] to a new backup node", x); }
124
getMembers 3
                  
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.warn("Unable to send election message to:"+msg.getMembers()[current]); current = Arrays.nextIndex(msg.getMembers()[current],msg.getMembers()); if ( current == next ) throw x; }
58
getOutputName 3
                  
// in java/org/apache/el/parser/AstFunction.java
catch (ELException ele) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), ele); }
// in java/org/apache/el/parser/AstFunction.java
catch (IllegalAccessException iae) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), iae); }
// in java/org/apache/el/parser/AstFunction.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(MessageFactory.get("error.function", this .getOutputName()), cause); }
8
getQueue 3
                  
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
catch (RejectedExecutionException rx) { //there could have been contention around the queue if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException("Work queue full."); }
7
getURL 3
                  
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException e) { // Unexpected exception throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.jarFail", jarConn.getURL()), ioe); }
42
handleExceptionWithDelay
3
                  
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw ioe; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw e; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (IOException ioe) { countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw ioe; }
3
isFailOnError 3
                  
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/ValidatorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException("Validation failure", e); } else { handleErrorOutput("Validation failure: " + e); } }
5
isInfoEnabled 3
                  
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException e) { parseFailed = true; decodeFailCount++; if (decodeFailCount == 1 || log.isDebugEnabled()) { if (log.isDebugEnabled()) { log.debug(sm.getString("parameters.decodeFail.debug", origName.toString(), origValue.toString()), e); } else if (log.isInfoEnabled()) { UserDataHelper.Mode logMode = userDataLog.getNextMode(); if (logMode != null) { String message = sm.getString( "parameters.decodeFail.info", tmpName.toString(), tmpValue.toString()); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString("parameters.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } } } }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
catch (Exception e) { // log message and error if (digester.log.isInfoEnabled()) { digester.log.info("[FactoryCreateRule] Create exception ignored: " + ((e.getMessage() == null) ? e.getClass().getName() : e.getMessage())); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule] Ignored exception:", e); } } exceptionIgnoredStack.push(Boolean.TRUE); }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage())); } }
78
releaseCaches 3
                  
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; socket.getPoller().cancelledKey(key,SocketStatus.ERROR); releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
4
remove 3
                  
// in java/org/apache/catalina/realm/CombinedRealm.java
catch (LifecycleException e) { // If realm doesn't start can't authenticate against it iter.remove(); log.error(sm.getString("combinedRealm.realmStartFail", realm.getClass().getName()), e); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( IOException x ) { sender.disconnect(); sender.reset(); //nioSenders.remove(entry.getKey()); i.remove(); result = true; }
// in java/org/apache/catalina/session/StoreBase.java
catch (Exception e) { manager.getContainer().getLogger().error("Session: "+keys[i]+"; ", e); try { remove(keys[i]); } catch (IOException e2) { manager.getContainer().getLogger().error("Error removing key", e2); } }
259
sendAck 3
                  
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch ( Exception x ) { if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(Constants.FAIL_ACK_COMMAND); log.error("Error thrown from messageDataReceived.",x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( RemoteProcessException e ) { if ( log.isDebugEnabled() ) log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( Exception e ) { log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); }
8
sendAckSync 3
                  
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch ( Exception x ) { if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(Constants.FAIL_ACK_COMMAND); log.error("Error thrown from messageDataReceived.",x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( RemoteProcessException e ) { if ( log.isDebugEnabled() ) log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( Exception e ) { log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); }
5
sleep 3
                  
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception x ) { if (x instanceof InterruptedException) interrupted(); else { if (errorCounter==0 && doRunReceiver) log.warn("Error receiving mcast package. Sleeping 500ms",x); else if (log.isDebugEnabled()) log.debug("Error receiving mcast package"+(doRunReceiver?". Sleeping 500ms":"."),x); if (doRunReceiver) { try { Thread.sleep(500); } catch ( Exception ignore ){} if ( (++errorCounter)>=recoveryCounter ) { errorCounter=0; RecoveryThread.recover(McastServiceImpl.this); } } } }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IllegalThreadStateException e) { try { Thread.sleep(500); } catch (InterruptedException ignored) { // Ignore } }
32
warning 3
                  
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (AccessControlException ace) { // No permission to configure logging in context // Log and carry on ClassLoaderLogInfo info = classLoaderLoggers.get(ClassLoader.getSystemClassLoader()); if (info != null) { Logger log = info.loggers.get(""); if (log != null) { Permission perm = ace.getPermission(); if (perm instanceof FilePermission && perm.getActions().equals("read")) { log.warning("Reading " + perm.getName() + " is not permitted. See \"per context logging\" in the default catalina.policy file."); } else { log.warning("Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file."); log.warning("Original error was: " + ace.getMessage()); } } } }
7
APR_STATUS_IS_EINVAL
2
                  
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Error e) { e.printStackTrace(); if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(" endpoint.poll.limitedpollsize " + size); return 0; } else if (Status.APR_STATUS_IS_ENOTIMPL(e.getError())) { // thread safe not supported log.severe("THREAD SAFE NOT SUPPORTED" + e); threadSafe = false; // try again without the flags continue; } else { log.severe("endpoint.poll.initfail" + e); return 0; } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Error e) { if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(sm.getString("endpoint.poll.limitedpollsize", "" + size)); return 0; } else { log.error(sm.getString("endpoint.poll.initfail"), e); return -1; } }
2
AttributeInfo 2
                  
// in java/org/apache/catalina/ha/session/DeltaRequest.java
catch ( Exception x ) { log.error("Unable to remove element:",x); info = new AttributeInfo(type, action, name, value); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
catch ( Exception x ) { log.error("Unable to remove element",x); info = new AttributeInfo(); }
6
File 2
                  
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (writer != null) { try { writer.close(); writer = null; } catch (Exception e1) { // do nothing } } // Remove the generated .java file File file = new File(javaFileName); if (file.exists()) { if (!file.delete()) { log.warn(Localizer.getMessage( "jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath())); } } throw e; }
// in java/org/apache/tomcat/jni/Library.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } String name = System.mapLibraryName(NAMES[i]); String path = System.getProperty("java.library.path"); String sep = System.getProperty("path.separator"); String [] paths = path.split(sep); for (int j=0; j<paths.length; j++) { java.io.File fd = new java.io.File(paths[j] , name); if (fd.exists()) { t.printStackTrace(); } } if ( i > 0) err.append(", "); err.append(t.getMessage()); }
315
GetImage 2
                  
// in java/org/apache/tomcat/util/http/parser/HttpParserTokenManager.java
catch (java.io.IOException e1) { EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch (java.io.IOException e1) { EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; }
6
Long 2
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
171
OutputStreamWriter 2
                  
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (java.io.UnsupportedEncodingException ex) { // Use the default encoding? writer = new OutputStreamWriter(buf); }
// in java/org/apache/catalina/util/URLEncoder.java
catch (Exception e) { e.printStackTrace(); writer = new OutputStreamWriter(buf); }
21
addAndGet 2
                  
// in java/org/apache/catalina/tribes/group/interceptors/ThroughputInterceptor.java
catch ( ChannelException x ) { msgTxErr.addAndGet(1); if ( access.get() == 1 ) access.addAndGet(-1); throw x; }
17
addHeader 2
                  
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NumberFormatException e) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse .SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NumberFormatException e) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse .SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; }
36
backup 2
                  
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; }
// in java/org/apache/el/parser/SimpleCharStream.java
catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; }
9
checkSwallowInput 2
                  
// in java/org/apache/catalina/connector/Request.java
catch (FileUploadBase.SizeException e) { checkSwallowInput(); partsParseException = new IllegalStateException(e); }
// in java/org/apache/catalina/connector/Request.java
catch (IllegalStateException e) { checkSwallowInput(); partsParseException = e; }
4
countDown 2
                  
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (CancelledKeyException ckx) { sk.cancel(); countDown(attachment.getReadLatch()); countDown(attachment.getWriteLatch()); }
15
equals 2
                  
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (AccessControlException ace) { // No permission to configure logging in context // Log and carry on ClassLoaderLogInfo info = classLoaderLoggers.get(ClassLoader.getSystemClassLoader()); if (info != null) { Logger log = info.loggers.get(""); if (log != null) { Permission perm = ace.getPermission(); if (perm instanceof FilePermission && perm.getActions().equals("read")) { log.warning("Reading " + perm.getName() + " is not permitted. See \"per context logging\" in the default catalina.policy file."); } else { log.warning("Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file."); log.warning("Original error was: " + ace.getMessage()); } } } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
1676
force
2
                  
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
catch (RejectedExecutionException rx) { //there could have been contention around the queue if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException("Work queue full."); }
2
getAvailable 2
                  
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error( sm.getString("standardWrapper.allocateException", wrapper.getName()), e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
20
getBoolean 2
                  
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) { throw new java.lang.Error(e); } else { log.error("Catalina.start", e); } }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { String message = sm.getString( "standardService.connector.initFailed", connector); log.error(message, e); if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) throw new LifecycleException(message); }
3
getContextPath 2
                  
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Exception e) { // Unexpected log(sm.getString("applicationContext.lookup.error", path, getContextPath()), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Exception e) { // Unexpected log(sm.getString("applicationContext.lookup.error", path, getContextPath()), e); }
71
getDefault 2
                  
// in java/org/apache/naming/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { tempBundle = ResourceBundle.getBundle( bundleName, Locale.getDefault(), cl); } catch(MissingResourceException ex2) { // Ignore } } }
// in java/org/apache/catalina/tribes/util/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { bundle = ResourceBundle.getBundle( bundleName, Locale.getDefault(), cl); } catch(MissingResourceException ex2) { // Ignore } } }
17
getDisplayName 2
                  
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.reload[" + cn.getDisplayName() + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/javax/el/ELResolver.java
catch (MissingResourceException e) { return "Missing Resource: '" + name + "' for Locale " + locale.getDisplayName(); }
32
getFilterClass 2
                  
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception ex) { log.info(sm.getString("applicationFilterConfig.jmxRegisterFail", getFilterClass(), getFilterName()), ex); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch(Exception ex) { log.error(sm.getString( "applicationFilterConfig.jmxUnregisterFail", getFilterClass(), getFilterName()), ex); }
15
getFilterName 2
                  
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception ex) { log.info(sm.getString("applicationFilterConfig.jmxRegisterFail", getFilterClass(), getFilterName()), ex); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch(Exception ex) { log.error(sm.getString( "applicationFilterConfig.jmxUnregisterFail", getFilterClass(), getFilterName()), ex); }
29
getHandler 2
                  
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
catch ( Exception x ) { ChannelException cx = null; if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException(x); if ( log.isDebugEnabled() ) log.debug("Error while processing async message.",x); try { if (link.getHandler() != null) link.getHandler().handleError(cx, new UniqueId(msg.getUniqueId())); } catch ( Exception ex ) { log.error("Unable to report back error message.",ex); } }
9
getHostAddress 2
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
18
getJarPath 2
                  
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NamingException e) { if (log.isDebugEnabled()) log.debug(" Failed tracking modifications of '" + getJarPath() + "'"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassCastException e) { log.error(" Failed tracking modifications of '" + getJarPath() + "' : " + e.getMessage()); }
4
getJspFile 2
                  
// in java/org/apache/jasper/JspCompilationContext.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; }
20
getMember 2
                  
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( ChannelException cx ) { FaultyMember[] mbrs = cx.getFaultyMembers(); for ( int i=0; i<mbrs.length; i++ ) { if ( mbrs[i].getCause()!=null && (!(mbrs[i].getCause() instanceof RemoteProcessException)) ) {//RemoteProcessException's are ok this.memberDisappeared(mbrs[i].getMember()); }//end if }//for throw cx; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException ce) { // Handle known failed members FaultyMember[] faultyMembers = ce.getFaultyMembers(); for (FaultyMember faultyMember : faultyMembers) { memberDisappeared(faultyMember.getMember()); } }
29
getNewValue 2
                  
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NumberFormatException e) { log.error(sm.getString("webappLoader.reloadable", event.getNewValue().toString())); }
// in java/org/apache/catalina/session/ManagerBase.java
catch (NumberFormatException e) { log.error(sm.getString("managerBase.sessionTimeout", event.getNewValue())); }
5
getNextMode 2
                  
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IllegalStateException ise) { // Hitting limit stops processing further params but does // not cause request to fail. parseFailed = true; UserDataHelper.Mode logMode = maxParamCountLog.getNextMode(); if (logMode != null) { String message = ise.getMessage(); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString( "parameters.maxCountFail.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } break; }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException e) { parseFailed = true; decodeFailCount++; if (decodeFailCount == 1 || log.isDebugEnabled()) { if (log.isDebugEnabled()) { log.debug(sm.getString("parameters.decodeFail.debug", origName.toString(), origValue.toString()), e); } else if (log.isInfoEnabled()) { UserDataHelper.Mode logMode = userDataLog.getNextMode(); if (logMode != null) { String message = sm.getString( "parameters.decodeFail.info", tmpName.toString(), tmpValue.toString()); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString("parameters.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } } } }
6
getPrefix 2
                  
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError("jsp.error.function.classnotfound", n .getFunctionInfo().getFunctionClass(), n .getPrefix() + ':' + n.getName(), e.getMessage()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError("jsp.error.signature.classnotfound", paramTypes[i], n.getPrefix() + ':' + n.getName(), e.getMessage()); }
21
getPrincipal 2
                  
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (CommunicationException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); }
29
getStart 2
                  
// in java/org/apache/jasper/compiler/Validator.java
catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", attrs.getValue(i), e.toString()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", value, e .toString()); }
88
getSystemId 2
                  
// in java/org/apache/catalina/startup/ContextConfig.java
catch (SAXParseException e) { log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e); log.error(sm.getString("contextConfig.applicationPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e); ok = false; }
8
getValue 2
                  
// in java/org/apache/jasper/compiler/Validator.java
catch (Exception e) { err.jspError (n, "jsp.error.coerce_to_type", tldAttr.getName(), expectedType, attrs.getValue(i)); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", attrs.getValue(i), e.toString()); }
433
getWriter 2
                  
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
26
handleException
2
                  
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ handleException(ex); return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; }
2
invoke 2
                  
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalArgumentException biae) { //the boolean method had the wrong //parameter types. lets try the other if (setPropertyMethodVoid!=null) { setPropertyMethodVoid.invoke(o, params); return true; }else { throw biae; } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException nfe){ Method cancelMethod = thread.getClass().getDeclaredMethod("cancel"); if (null != cancelMethod){ synchronized(thread) { cancelMethod.setAccessible(true); cancelMethod.invoke(thread); } } }
148
isErrorEnabled 2
                  
// in java/org/apache/catalina/tribes/group/interceptors/FragmentationInterceptor.java
catch ( Exception x ) { if ( log.isErrorEnabled() ) { log.error("Unable to perform heartbeat clean up in the frag interceptor",x); } }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (Exception e) { //this is common, since the sockets on the other //end expire after a certain time. if ( e instanceof CancelledKeyException ) { //do nothing } else if ( e instanceof IOException ) { //dont spew out stack traces for IO exceptions unless debug is enabled. if (log.isDebugEnabled()) log.debug ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"].", e); else log.warn ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"]."); } else if ( log.isErrorEnabled() ) { //this is a real error, log it. log.error("Exception caught in TcpReplicationThread.drainChannel.",e); } cancelKey(key); }
5
isReady 2
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
4
jjFillToken 2
                  
// in java/org/apache/tomcat/util/http/parser/HttpParserTokenManager.java
catch(java.io.IOException e) { jjmatchedKind = 0; matchedToken = jjFillToken(); return matchedToken; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjmatchedKind = 0; matchedToken = jjFillToken(); return matchedToken; }
4
memberDisappeared 2
                  
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( ChannelException cx ) { FaultyMember[] mbrs = cx.getFaultyMembers(); for ( int i=0; i<mbrs.length; i++ ) { if ( mbrs[i].getCause()!=null && (!(mbrs[i].getCause() instanceof RemoteProcessException)) ) {//RemoteProcessException's are ok this.memberDisappeared(mbrs[i].getMember()); }//end if }//for throw cx; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException ce) { // Handle known failed members FaultyMember[] faultyMembers = ce.getFaultyMembers(); for (FaultyMember faultyMember : faultyMembers) { memberDisappeared(faultyMember.getMember()); } }
17
message 2
                  
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
52
notifyError
2
                  
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable t) { t.printStackTrace(); // no error handler yet reset(); notifyError(t, false); return; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException t) { reset(); // also sets status ERROR if (handler instanceof AprSocketContext.NonBlockingPollHandler) { ((AprSocketContext.NonBlockingPollHandler) handler).process(this, false, false, true); } notifyError(t, false); }
2
process 2
                  
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException t) { reset(); // also sets status ERROR if (handler instanceof AprSocketContext.NonBlockingPollHandler) { ((AprSocketContext.NonBlockingPollHandler) handler).process(this, false, false, true); } notifyError(t, false); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket reprocessing request was rejected for:"+socket,x); try { //unable to handle connection at this time handler.process(socket, SocketStatus.DISCONNECT); } finally { countDownConnection(); } }
32
recover
2
                  
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception x ) { if (x instanceof InterruptedException) interrupted(); else { if (errorCounter==0 && doRunReceiver) log.warn("Error receiving mcast package. Sleeping 500ms",x); else if (log.isDebugEnabled()) log.debug("Error receiving mcast package"+(doRunReceiver?". Sleeping 500ms":"."),x); if (doRunReceiver) { try { Thread.sleep(500); } catch ( Exception ignore ){} if ( (++errorCounter)>=recoveryCounter ) { errorCounter=0; RecoveryThread.recover(McastServiceImpl.this); } } } }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception x ) { if (errorCounter==0) log.warn("Unable to send mcast message.",x); else log.debug("Unable to send mcast message.",x); if ( (++errorCounter)>=recoveryCounter ) { errorCounter=0; RecoveryThread.recover(McastServiceImpl.this); } }
2
resolveClass 2
                  
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch (ClassNotFoundException e) { return super.resolveClass(classDesc); }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (ClassNotFoundException e) { try { // Try also the superclass because of primitive types return super.resolveClass(classDesc); } catch (ClassNotFoundException e2) { // Rethrow original exception, as it can have more information // about why the class was not found. BZ 48007 throw e; } }
12
setAttempt 2
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
4
setCompilationException 2
                  
// in java/org/apache/jasper/JspCompilationContext.java
catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (Exception ex) { JasperException je = new JasperException( Localizer.getMessage("jsp.error.unable.compile"), ex); // Cache compilation exception jsw.setCompilationException(je); throw je; }
3
setDateHeader 2
                  
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error( sm.getString("standardWrapper.allocateException", wrapper.getName()), e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
20
setFailing
2
                  
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( Exception ignore){ state.setFailing(); }
2
setHeader 2
                  
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail", e)); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (PrivilegedActionException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail", e)); response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
43
setMessage 2
                  
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException ioe) { res.setStatus(400); res.setMessage("Invalid URI: " + ioe.getMessage()); connector.getService().getContainer().logAccess( request, response, 0, true); return false; }
18
severe 2
                  
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Error e) { e.printStackTrace(); if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(" endpoint.poll.limitedpollsize " + size); return 0; } else if (Status.APR_STATUS_IS_ENOTIMPL(e.getError())) { // thread safe not supported log.severe("THREAD SAFE NOT SUPPORTED" + e); threadSafe = false; // try again without the flags continue; } else { log.severe("endpoint.poll.initfail" + e); return 0; } }
11
substring 2
                  
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
// in java/javax/servlet/http/HttpUtils.java
catch (StringIndexOutOfBoundsException e) { String rest = s.substring(i); sb.append(rest); if (rest.length()==2) i++; }
401
writeElement 2
                  
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
161
writeObject 2
                  
// in java/org/apache/catalina/session/StandardSession.java
catch (NotSerializableException e) { manager.getContainer().getLogger().warn (sm.getString("standardSession.notSerializable", saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug (" storing attribute '" + saveNames.get(i) + "' with value NOT_SERIALIZED"); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
catch (NotSerializableException e) { log.error(sm.getString("standardSession.notSerializable",saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); log.error(" storing attribute '" + saveNames.get(i)+ "' with value NOT_SERIALIZED"); }
45
APR_STATUS_IS_ENOTIMPL
1
                  
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Error e) { e.printStackTrace(); if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(" endpoint.poll.limitedpollsize " + size); return 0; } else if (Status.APR_STATUS_IS_ENOTIMPL(e.getError())) { // thread safe not supported log.severe("THREAD SAFE NOT SUPPORTED" + e); threadSafe = false; // try again without the flags continue; } else { log.severe("endpoint.poll.initfail" + e); return 0; } }
1
BigDecimal 1
                  
// in java/org/apache/el/parser/AstFloatingPoint.java
catch (ArithmeticException e0) { this.number = new BigDecimal(this.image); }
16
BigInteger 1
                  
// in java/org/apache/el/parser/AstInteger.java
catch (ArithmeticException e1) { this.number = new BigInteger(this.image); }
5
CaptureLog 1
                  
// in java/org/apache/tomcat/util/log/SystemLogHandler.java
catch (EmptyStackException e) { log = new CaptureLog(); }
2
CharsetMapper
1
                  
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); this.charsetMapper = new CharsetMapper(); }
1
DeltaManager 1
                  
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to clone cluster manager, defaulting to org.apache.catalina.ha.session.DeltaManager", x); manager = new org.apache.catalina.ha.session.DeltaManager(); }
3
EmbeddedServletOptions 1
                  
// in java/org/apache/jasper/servlet/JspServlet.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); // Need to localize this. log.warn("Failed to load engineOptionsClass", e); // Use the default Options implementation options = new EmbeddedServletOptions(config, context); }
2
InitialDirContext 1
                  
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (Exception e) { connectionAttempt = 1; // log the first exception. containerLog.warn(sm.getString("jndiRealm.exception"), e); // Try connecting to the alternate url. context = new InitialDirContext(getDirectoryContextEnvironment()); }
2
InputSource 1
                  
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (EnableDTDValidationException e) { saxParser = getSAXParser(true, jspDocParser); jspDocParser.isValidating = true; if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } inStream = JspUtil.getInputStream(path, jarFile, jspDocParser.ctxt); saxParser.parse(new InputSource(inStream), jspDocParser); }
29
Mark 1
                  
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (SAXParseException e) { jspDocParser.err.jspError (new Mark(jspDocParser.ctxt, path, e.getLineNumber(), e.getColumnNumber()), e.getMessage()); }
11
MulticastSocket 1
                  
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (BindException e) { /* * On some platforms (e.g. Linux) it is not possible to bind * to the multicast address. In this case only bind to the * port. */ log.info("Binding to multicast address, failed. Binding to port only."); socket = new MulticastSocket(port); }
5
SimpleFormatter 1
                  
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { // Ignore and fallback to defaults setFormatter(new SimpleFormatter()); }
2
String 1
                  
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
catch (UnsupportedEncodingException e) { return new String(rawdata); }
171
UniqueId 1
                  
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
catch ( Exception x ) { ChannelException cx = null; if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException(x); if ( log.isDebugEnabled() ) log.debug("Error while processing async message.",x); try { if (link.getHandler() != null) link.getHandler().handleError(cx, new UniqueId(msg.getUniqueId())); } catch ( Exception ex ) { log.error("Unable to report back error message.",ex); } }
19
XByteBuffer 1
                  
// in java/org/apache/catalina/tribes/io/ObjectReader.java
catch ( IOException x ) { //unable to get buffer size log.warn("Unable to retrieve the socket receiver buffer size, setting to default 43800 bytes."); this.buffer = new XByteBuffer(43800,true); }
77
XMLWriter 1
                  
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
5
attach 1
                  
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (CancelledKeyException cx) { if (sk!=null) { sk.cancel(); sk.attach(null); } }
23
bindUdp 1
                  
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); }
2
breakdown 1
                  
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.warn("Unable to send map start message."); // remove listener from channel this.rpcChannel.breakdown(); this.channel.removeChannelListener(this); this.channel.removeMembershipListener(this); throw new RuntimeException("Unable to start replicated map.",x); }
5
cancelKey 1
                  
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (Exception e) { //this is common, since the sockets on the other //end expire after a certain time. if ( e instanceof CancelledKeyException ) { //do nothing } else if ( e instanceof IOException ) { //dont spew out stack traces for IO exceptions unless debug is enabled. if (log.isDebugEnabled()) log.debug ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"].", e); else log.warn ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"]."); } else if ( log.isErrorEnabled() ) { //this is a real error, log it. log.error("Exception caught in TcpReplicationThread.drainChannel.",e); } cancelKey(key); }
5
closeSocket 1
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException xx) { exception = xx; closeSocket(); }
7
connect 1
                  
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
27
contains 1
                  
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } }
89
currentTimeMillis 1
                  
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); }
235
destroy 1
                  
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { log.error(sm.getString("endpoint.sendfile.error"), e); Pool.destroy(data.fdpool); data.socket = 0; return false; }
53
doListen 1
                  
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch ( Exception x ) { if ( doListen() ) throw x; }
6
elements 1
                  
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
40
endsWith 1
                  
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } }
125
findExternalClass 1
                  
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch (Exception x) { if (tryRepFirst) return findExternalClass(name); else return findReplicationClass(name); }
2
findReplicationClass 1
                  
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch (Exception x) { if (tryRepFirst) return findExternalClass(name); else return findReplicationClass(name); }
2
getActions
1
                  
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (AccessControlException ace) { // No permission to configure logging in context // Log and carry on ClassLoaderLogInfo info = classLoaderLoggers.get(ClassLoader.getSystemClassLoader()); if (info != null) { Logger log = info.loggers.get(""); if (log != null) { Permission perm = ace.getPermission(); if (perm instanceof FilePermission && perm.getActions().equals("read")) { log.warning("Reading " + perm.getName() + " is not permitted. See \"per context logging\" in the default catalina.policy file."); } else { log.warning("Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file."); log.warning("Original error was: " + ace.getMessage()); } } } }
1
getAttribute 1
                  
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); }
247
getClassName 1
                  
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (Exception e) { throw new MBeanException (e, "Cannot instantiate ModelMBean of class " + getClassName()); }
39
getDeclaredField 1
                  
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException nfe){ targetField = thread.getClass().getDeclaredField("runnable"); }
16
getDeclaredMethod 1
                  
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException nfe){ Method cancelMethod = thread.getClass().getDeclaredMethod("cancel"); if (null != cancelMethod){ synchronized(thread) { cancelMethod.setAccessible(true); cancelMethod.invoke(thread); } } }
13
getDirectoryContextEnvironment 1
                  
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (Exception e) { connectionAttempt = 1; // log the first exception. containerLog.warn(sm.getString("jndiRealm.exception"), e); // Try connecting to the alternate url. context = new InitialDirContext(getDirectoryContextEnvironment()); }
2
getErrorOnUseBeanInvalidClassAttribute
1
                  
// in java/org/apache/jasper/compiler/Generator.java
catch (Exception e) { // Cannot instantiate the specified class, either a // compilation error or a runtime error will be raised, // depending on a compiler flag. if (ctxt.getOptions() .getErrorOnUseBeanInvalidClassAttribute()) { err.jspError(n, "jsp.error.invalid.bean", klass); } if (canonicalName == null) { // Doing our best here to get a canonical name // from the binary name, should work 99.99% of time. canonicalName = klass.replace('$', '.'); } }
1
getFailOnError
1
                  
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } }
1
getFile 1
                  
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
catch (MalformedURLException me) { // Fallback to using context-relative path file = where.getFile(); }
33
getFunctionClass 1
                  
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError("jsp.error.function.classnotfound", n .getFunctionInfo().getFunctionClass(), n .getPrefix() + ':' + n.getName(), e.getMessage()); }
3
getFunctionInfo 1
                  
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError("jsp.error.function.classnotfound", n .getFunctionInfo().getFunctionClass(), n .getPrefix() + ':' + n.getName(), e.getMessage()); }
5
getIdInternal 1
                  
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error(sm.getString ("persistentManager.serializeError", session.getIdInternal(), e)); throw e; }
33
getInputStream 1
                  
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (EnableDTDValidationException e) { saxParser = getSAXParser(true, jspDocParser); jspDocParser.isValidating = true; if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } inStream = JspUtil.getInputStream(path, jarFile, jspDocParser.ctxt); saxParser.parse(new InputSource(inStream), jspDocParser); }
50
getInstance 1
                  
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { // default to now calendar = Calendar.getInstance(); }
54
getLocalPort 1
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
16
getLocalizedMessage
1
                  
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); }
1
getMaxRetryAttempts 1
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
2
getMethodName 1
                  
// in java/org/apache/jasper/compiler/Validator.java
catch (NoSuchMethodException e) { err.jspError("jsp.error.noFunctionMethod", n .getMethodName(), n.getName(), c.getName()); }
10
getOutputStream 1
                  
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IllegalStateException e) { try { ServletOutputStream stream = response.getOutputStream(); stream.close(); } catch (IllegalStateException f) { // Ignore } catch (IOException f) { // Ignore } }
24
getParent 1
                  
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (Exception e) { req.getWrapper().getParent().getLogger().warn(sm.getString( "cometConnectionManagerValve.listenerEvent"), e); }
149
getPermission
1
                  
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (AccessControlException ace) { // No permission to configure logging in context // Log and carry on ClassLoaderLogInfo info = classLoaderLoggers.get(ClassLoader.getSystemClassLoader()); if (info != null) { Logger log = info.loggers.get(""); if (log != null) { Permission perm = ace.getPermission(); if (perm instanceof FilePermission && perm.getActions().equals("read")) { log.warning("Reading " + perm.getName() + " is not permitted. See \"per context logging\" in the default catalina.policy file."); } else { log.warning("Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file."); log.warning("Original error was: " + ace.getMessage()); } } } }
1
getPortHeader 1
                  
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException nfe) { log.debug("Invalid port value [" + portHeaderValue + "] provided in header [" + getPortHeader() + "]"); }
3
getProject 1
                  
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (ClassCastException cce) { getProject().log( "Wrong object reference " + getRef() + " - " + pref.getClass()); return null; }
16
getReadLatch 1
                  
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (CancelledKeyException ckx) { sk.cancel(); countDown(attachment.getReadLatch()); countDown(attachment.getWriteLatch()); }
9
getRecompileOnFail
1
                  
// in java/org/apache/jasper/JspCompilationContext.java
catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; }
1
getRef 1
                  
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (ClassCastException cce) { getProject().log( "Wrong object reference " + getRef() + " - " + pref.getClass()); return null; }
8
getResourceAsStream 1
                  
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (FileNotFoundException ex) { // if file not found on filesystem, get the resource through // the context return ctxt.getResourceAsStream(uri); }
39
getSAXParser 1
                  
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (EnableDTDValidationException e) { saxParser = getSAXParser(true, jspDocParser); jspDocParser.isValidating = true; if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } inStream = JspUtil.getInputStream(path, jarFile, jspDocParser.ctxt); saxParser.parse(new InputSource(inStream), jspDocParser); }
2
getService 1
                  
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException ioe) { res.setStatus(400); res.setMessage("Invalid URI: " + ioe.getMessage()); connector.getService().getContainer().logAccess( request, response, 0, true); return false; }
33
getStore 1
                  
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { Throwable cause = ioe.getCause(); if (cause instanceof UnrecoverableKeyException) { // Log a warning we had a password issue log.warn(sm.getString("jsse.invalid_truststore_password"), cause); // Re-try trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, null); } else { // Something else went wrong - re-throw throw ioe; } }
12
getSystemClassLoader 1
                  
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (AccessControlException ace) { // No permission to configure logging in context // Log and carry on ClassLoaderLogInfo info = classLoaderLoggers.get(ClassLoader.getSystemClassLoader()); if (info != null) { Logger log = info.loggers.get(""); if (log != null) { Permission perm = ace.getPermission(); if (perm instanceof FilePermission && perm.getActions().equals("read")) { log.warning("Reading " + perm.getName() + " is not permitted. See \"per context logging\" in the default catalina.policy file."); } else { log.warning("Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file."); log.warning("Original error was: " + ace.getMessage()); } } } }
14
getTaglibURI 1
                  
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.webxmlFail", resourcePath, descriptor.getTaglibURI()), ioe); }
6
getTimeout 1
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
29
getUnavailableSeconds 1
                  
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); }
2
getUniqueId 1
                  
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
catch ( Exception x ) { ChannelException cx = null; if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException(x); if ( log.isDebugEnabled() ) log.debug("Error while processing async message.",x); try { if (link.getHandler() != null) link.getHandler().handleError(cx, new UniqueId(msg.getUniqueId())); } catch ( Exception ex ) { log.error("Unable to report back error message.",ex); } }
32
getUrl 1
                  
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Exception ex) { err.jspError(mark, "jsp.error.tld.unable_to_read", jarResource.getUrl(), tldName, ex.toString()); }
6
getUserByPattern 1
                  
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // If the getUserByPattern() call fails, try it again with the // credentials of the user that we're searching for try { userCredentialsAdd(context, dn, credentials); user = getUserByPattern(context, username, attrIds, dn); } finally { userCredentialsRemove(context); } }
3
getWrapper 1
                  
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (Exception e) { req.getWrapper().getParent().getLogger().warn(sm.getString( "cometConnectionManagerValve.listenerEvent"), e); }
14
getWriteLatch 1
                  
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (CancelledKeyException ckx) { sk.cancel(); countDown(attachment.getReadLatch()); countDown(attachment.getWriteLatch()); }
9
handleError
1
                  
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
catch ( Exception x ) { ChannelException cx = null; if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException(x); if ( log.isDebugEnabled() ) log.debug("Error while processing async message.",x); try { if (link.getHandler() != null) link.getHandler().handleError(cx, new UniqueId(msg.getUniqueId())); } catch ( Exception ex ) { log.error("Unable to report back error message.",ex); } }
1
handleMissingResource 1
                  
// in java/org/apache/jasper/servlet/JspServlet.java
catch (FileNotFoundException fnfe) { handleMissingResource(request, response, jspUri); }
2
hasMoreElements 1
                  
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
138
include 1
                  
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IllegalStateException ise) { include(errorPageURL); }
14
incrementRemoved 1
                  
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch (FileNotFoundException ex) { ctxt.incrementRemoved(); }
2
init 1
                  
// in java/org/apache/tomcat/util/buf/C2BConverter.java
catch (IOException e) { log.warn(sm.getString("c2bConverter.recycleFailed"), e); try { init(); } catch (IOException ignore) { // Should never happen since this means encoding is invalid and // in that case, the constructor will have failed. } }
78
isConnected 1
                  
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
12
isSuspect 1
                  
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
2
jjStopStringLiteralDfa_0 1
                  
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_0(0, active0); return 1; }
5
lastIndexOf 1
                  
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
80
length 1
                  
// in java/javax/servlet/http/HttpUtils.java
catch (StringIndexOutOfBoundsException e) { String rest = s.substring(i); sb.append(rest); if (rest.length()==2) i++; }
635
logAccess 1
                  
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException ioe) { res.setStatus(400); res.setMessage("Invalid URI: " + ioe.getMessage()); connector.getService().getContainer().logAccess( request, response, 0, true); return false; }
13
lookup 1
                  
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { // Silent catch. Probably an object is already bound in // the context. currentContext = (javax.naming.Context) currentContext.lookup(token); }
82
mapLibraryName
1
                  
// in java/org/apache/tomcat/jni/Library.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } String name = System.mapLibraryName(NAMES[i]); String path = System.getProperty("java.library.path"); String sep = System.getProperty("path.separator"); String [] paths = path.split(sep); for (int j=0; j<paths.length; j++) { java.io.File fd = new java.io.File(paths[j] , name); if (fd.exists()) { t.printStackTrace(); } } if ( i > 0) err.append(", "); err.append(t.getMessage()); }
1
mark 1
                  
// in java/org/apache/jasper/compiler/Parser.java
catch (IllegalArgumentException iae) { // Duplicate attribute err.jspError(reader.mark(), "jsp.error.attribute.duplicate"); }
100
newProxyInstance 1
                  
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (IllegalArgumentException e) { proxyInstance = Proxy.newProxyInstance(tcl, serviceInterfaces, proxy); }
2
nextElement 1
                  
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
130
nextIndex 1
                  
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.warn("Unable to send election message to:"+msg.getMembers()[current]); current = Arrays.nextIndex(msg.getMembers()[current],msg.getMembers()); if ( current == next ) throw x; }
2
onClose 1
                  
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (IOException e) { // connection closed - abort all streams e.printStackTrace(); onClose(); return false; }
3
parse 1
                  
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (EnableDTDValidationException e) { saxParser = getSAXParser(true, jspDocParser); jspDocParser.isValidating = true; if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } inStream = JspUtil.getInputStream(path, jarFile, jspDocParser.ctxt); saxParser.parse(new InputSource(inStream), jspDocParser); }
69
parseLockNullProperties 1
                  
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
2
permitDenied 1
                  
// in java/org/apache/catalina/valves/SemaphoreValve.java
catch (InterruptedException e) { shouldRelease = false; permitDenied(request, response); return; }
2
popFile 1
                  
// in java/org/apache/jasper/compiler/JspReader.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.error("Exception parsing file ", ex); // Pop state being constructed: popFile(); err.jspError("jsp.error.file.cannot.read", file); }
2
push 1
                  
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
catch (Exception e) { // log message and error if (digester.log.isInfoEnabled()) { digester.log.info("[FactoryCreateRule] Create exception ignored: " + ((e.getMessage() == null) ? e.getClass().getName() : e.getMessage())); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule] Ignored exception:", e); } } exceptionIgnoredStack.push(Boolean.TRUE); }
38
pushMessage 1
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
2
recycle 1
                  
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException e) { log.error("Invalid URI character encoding; trying ascii"); cc.recycle(); }
146
removeChannelListener 1
                  
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.warn("Unable to send map start message."); // remove listener from channel this.rpcChannel.breakdown(); this.channel.removeChannelListener(this); this.channel.removeMembershipListener(this); throw new RuntimeException("Unable to start replicated map.",x); }
4
removeMembershipListener 1
                  
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.warn("Unable to send map start message."); // remove listener from channel this.rpcChannel.breakdown(); this.channel.removeChannelListener(this); this.channel.removeMembershipListener(this); throw new RuntimeException("Unable to start replicated map.",x); }
3
replace 1
                  
// in java/org/apache/jasper/compiler/Generator.java
catch (Exception e) { // Cannot instantiate the specified class, either a // compilation error or a runtime error will be raised, // depending on a compiler flag. if (ctxt.getOptions() .getErrorOnUseBeanInvalidClassAttribute()) { err.jspError(n, "jsp.error.invalid.bean", klass); } if (canonicalName == null) { // Doing our best here to get a canonical name // from the binary name, should work 99.99% of time. canonicalName = klass.replace('$', '.'); } }
58
replyFailed 1
                  
// in java/org/apache/catalina/tribes/group/RpcChannel.java
catch ( Exception x ) { if (excallback != null && !asyncReply) { excallback.replyFailed(rmsg.message, reply, sender, x); } else { log.error("Unable to send back reply in RpcChannel.",x); } }
2
sendData 1
                  
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
3
setAccessible 1
                  
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException nfe){ Method cancelMethod = thread.getClass().getDeclaredMethod("cancel"); if (null != cancelMethod){ synchronized(thread) { cancelMethod.setAccessible(true); cancelMethod.invoke(thread); } } }
26
setContentType 1
                  
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
42
setContentTypeNoCharset 1
                  
// in java/org/apache/catalina/connector/Response.java
catch (ParseException e) { // Invalid - Assume no charset and just pass through whatever // the user provided. coyoteResponse.setContentTypeNoCharset(type); return; }
2
setErrorException
1
                  
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { // Set error flag error = true; response.setErrorException(e); }
1
setFormatter 1
                  
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { // Ignore and fallback to defaults setFormatter(new SimpleFormatter()); }
4
setLastModificationTest 1
                  
// in java/org/apache/jasper/JspCompilationContext.java
catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; }
2
setLoadOnStartup 1
                  
// in java/org/apache/catalina/core/StandardWrapper.java
catch (NumberFormatException e) { setLoadOnStartup(0); }
8
setURIEncoding
1
                  
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException e) { // Ignore log.error("Invalid URI encoding; using HTTP default"); connector.setURIEncoding(null); }
1
split 1
                  
// in java/org/apache/tomcat/jni/Library.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } String name = System.mapLibraryName(NAMES[i]); String path = System.getProperty("java.library.path"); String sep = System.getProperty("path.separator"); String [] paths = path.split(sep); for (int j=0; j<paths.length; j++) { java.io.File fd = new java.io.File(paths[j] , name); if (fd.exists()) { t.printStackTrace(); } } if ( i > 0) err.append(", "); err.append(t.getMessage()); }
23
synchronized 1
                  
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
catch (NoSuchElementException x ) { try { synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 s = Selector.open(); } } catch (IOException iox) { } }
14
throwable 1
                  
// in java/org/apache/catalina/core/StandardHostValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); throwable(request, response, t); }
6
userCredentialsAdd 1
                  
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // If the getUserByPattern() call fails, try it again with the // credentials of the user that we're searching for try { userCredentialsAdd(context, dn, credentials); user = getUserByPattern(context, username, attrIds, dn); } finally { userCredentialsRemove(context); } }
3
userCredentialsRemove 1
                  
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // If the getUserByPattern() call fails, try it again with the // credentials of the user that we're searching for try { userCredentialsAdd(context, dn, credentials); user = getUserByPattern(context, username, attrIds, dn); } finally { userCredentialsRemove(context); } }
3
valueOf 1
                  
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException( sm.getString( "Duration unit not found after amount {} in directive '{}'", Integer.valueOf(amount), line)); }
524
writeXMLHeader 1
                  
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
5
Method Nbr Nbr total
close 130
                  
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
finally { if (in != null) { try { in.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/jasper/compiler/Compiler.java
finally { if (writer != null) { try { writer.close(); } catch (Exception e2) { // do nothing } } }
// in java/org/apache/jasper/compiler/Compiler.java
finally { if (tfp != null && ctxt.isPrototypeMode()) { tfp.removeProtoTypeFiles(null); } // Make sure these object which are only used during the // generation and compilation of the JSP page get // dereferenced so that they can be GC'd and reduce the // memory footprint. tfp = null; errDispatcher = null; pageInfo = null; // Only get rid of the pageNodes if in production. // In development mode, they are used for detailed // error messages. // http://issues.apache.org/bugzilla/show_bug.cgi?id=37062 if (!this.options.getDevelopment()) { pageNodes = null; } if (ctxt.getWriter() != null) { ctxt.getWriter().close(); ctxt.setWriter(null); } }
// in java/org/apache/jasper/compiler/ParserController.java
finally { if (inStreamReader != null) { try { inStreamReader.close(); } catch (Exception any) { } } }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
finally { if (in != null) { try { in.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
finally { if (webXml != null) { webXml.close(); } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
finally { if (jar != null) { jar.close(); } }
// in java/org/apache/jasper/compiler/JDTCompiler.java
finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) {/*Ignore*/} } if (isr != null) { try { isr.close(); } catch (IOException ioe) {/*Ignore*/} } if (is != null) { try { is.close(); } catch (IOException exc) {/*Ignore*/} } }
// in java/org/apache/jasper/compiler/JDTCompiler.java
finally { if (is != null) { try { is.close(); } catch (IOException exc) { // Ignore } } }
// in java/org/apache/jasper/compiler/JspReader.java
finally { if (reader != null) { try { reader.close(); } catch (Exception any) { if(log.isDebugEnabled()) { log.debug("Exception closing reader: ", any); } } } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
finally { if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } }
// in java/org/apache/jasper/compiler/JavacErrorDetail.java
finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } if (fis != null) { try { fis.close(); } catch (IOException ioe) { // Ignore } } }
// in java/org/apache/jasper/compiler/JspConfig.java
finally { if (webXml != null) { webXml.close(); } }
// in java/org/apache/jasper/servlet/JspCServletContext.java
finally { if (is != null) { try { is.close(); } catch (Throwable t2) { ExceptionUtils.handleThrowable(t2); } } }
// in java/org/apache/jasper/JspCompilationContext.java
finally { if (uc != null) { try { uc.getInputStream().close(); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; } } }
// in java/org/apache/naming/resources/FileDirContext.java
finally { if (os != null) os.close(); is.close(); }
// in java/org/apache/naming/resources/ProxyDirContext.java
finally { try { if (is != null) is.close(); } catch (IOException e) { // Ignore } }
// in java/org/apache/juli/ClassLoaderLogManager.java
finally { try { is.close(); } catch (IOException ioe) { // Ignore } }
// in java/org/apache/tomcat/buildutil/CheckEol.java
finally { is.close(); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
finally { if (key!=null) try {key.cancel();} catch (Exception ignore) {} if (selector!=null) try {selector.close();} catch (Exception ignore) {} }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
finally { if ( force || closed ) { closed = true; sc.socket().close(); sc.close(); } }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
finally { if (s != null) { try { s.close(); } catch (Exception e) { // Ignore } } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
finally { if (istream != null) { try { istream.close(); } catch (IOException ioe) { // Do nothing } } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
finally { if(is != null) { try{ is.close(); } catch(Exception ex) { // Ignore } } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
finally { // Should be open here but just in case if (!socket.isClosed()) { socket.close(); } }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // ignore } } }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
finally { if (fout != null) { fout.close(); } }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } if (out != null) { try { out.close(); } catch (IOException e) { // ignore } } }
// in java/org/apache/tomcat/util/http/fileupload/util/Streams.java
finally { if (in != null) { try { in.close(); } catch (IOException ioe) { /* Ignore me */ } } if (pClose && out != null) { try { out.close(); } catch (IOException ioe) { /* Ignore me */ } } }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { log.error(sm.getString("contextConfig.contextClose"), e); } }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (is != null) { try { is.close(); } catch (IOException e) { // Ignore } } if (jar != null) { jar.close(); } }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (jar != null) { jar.close(); } }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (jar != null) { jar.close(); } }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (is != null) { try { is.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (fis != null) { try { fis.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } if (jar != null) { jar.close(); } fragment.setURL(url); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } fragment.setURL(file.toURI().toURL()); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
// in java/org/apache/catalina/startup/TldConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/catalina/startup/TldConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/catalina/startup/TldConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/catalina/startup/TldConfig.java
finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } }
// in java/org/apache/catalina/startup/TldConfig.java
finally { if (jar != null) { jar.close(); } }
// in java/org/apache/catalina/startup/HostConfig.java
finally { if (ostream != null) { try { ostream.close(); } catch (IOException ioe) { // Ignore } ostream = null; } if (fos != null) { try { fos.close(); } catch (IOException ioe) { // Ignore } fos = null; } if (istream != null) { try { istream.close(); } catch (IOException ioe) { // Ignore } istream = null; } entry = null; if (jar != null) { try { jar.close(); } catch (IOException ioe) { // Ignore; } jar = null; } }
// in java/org/apache/catalina/startup/HostConfig.java
finally { if (context == null) { context = new FailedContext(); } context.setConfigFile(new URL("jar:" + war.toURI().toString() + "!/" + Constants.ApplicationContextXml)); if (istream != null) { try { istream.close(); } catch (IOException e) { /* Ignore */ } istream = null; } entry = null; if (jar != null) { try { jar.close(); } catch (IOException e) { /* Ignore */ } jar = null; } digester.reset(); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { try { if (is != null) is.close(); } catch (IOException e){ // Ignore } try { if (os != null) os.close(); } catch (IOException e){ // Ignore } }
// in java/org/apache/catalina/startup/ExpandWar.java
finally { if (!success) { // If something went wrong, delete expanded dir to keep things // clean deleteDir(docBase); } if (input != null) { try { input.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } input = null; } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } }
// in java/org/apache/catalina/startup/ExpandWar.java
finally { if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } }
// in java/org/apache/catalina/startup/ExpandWar.java
finally { if (ic != null) { try { ic.close(); } catch (IOException e) { } } if (oc != null) { try { oc.close(); } catch (IOException e) { } } }
// in java/org/apache/catalina/startup/ExpandWar.java
finally { if (output != null) { try { output.close(); } catch (IOException e) { // Ignore } } }
// in java/org/apache/catalina/startup/Catalina.java
finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // Ignore } } }
// in java/org/apache/catalina/startup/Catalina.java
finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // Ignore } } if (socket != null) { try { socket.close(); } catch (IOException e) { // Ignore } } }
// in java/org/apache/catalina/startup/Catalina.java
finally { try { inputStream.close(); } catch (IOException e) { // Ignore } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
finally { if (is != null) { try { is.close(); } catch (IOException ioe) { log.warn(sm.getString( "webappClassLoader.jdbcRemoveStreamError", contextName), ioe); } } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
finally { try { if (is != null) { is.close(); } } catch (IOException e) { // Ignore } try { if (os != null) { os.close(); } } catch (IOException e) { // Ignore } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
finally { if (binaryStream != null) { try { binaryStream.close(); } catch (IOException e) { /* Ignore */} } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException ioe) { // Ignore } } }
// in java/org/apache/catalina/realm/DataSourceRealm.java
finally { close(dbConnection); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getPassword.exception", username)); } }
// in java/org/apache/catalina/realm/DataSourceRealm.java
finally { close(dbConnection); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
finally { close(dbConnection); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getRoles.exception", username)); } }
// in java/org/apache/catalina/realm/JDBCRealm.java
finally { if (rs!=null) { try { rs.close(); } catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); } } dbConnection.commit(); }
// in java/org/apache/catalina/realm/JDBCRealm.java
finally { if (rs!=null) { try { rs.close(); } catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); } } dbConnection.commit(); }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
finally { if (fis != null) { try { fis.close(); } catch (IOException ioe) { // Ignore } } }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
finally { closeRedirector(); if (reader != null) { try { reader.close(); } catch (IOException ioe) { // Ignore } reader = null; } if (istream != null) { try { istream.close(); } catch (IOException ioe) { // Ignore } } }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
finally { if (is != null) { try { is.close(); } catch (IOException e) { // Ignore } } if (os != null) { try { os.close(); } catch (IOException e) { // Ignore } } }
// in java/org/apache/catalina/manager/ManagerServlet.java
finally { if (ostream != null) { try { ostream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } ostream = null; } if (istream != null) { try { istream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } istream = null; } }
// in java/org/apache/catalina/manager/ManagerServlet.java
finally { if (is != null) { try { is.close(); } catch (IOException e) { // Ignore } } if (os != null) { try { os.close(); } catch (IOException e) { // Ignore } } }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
finally { try {socket.close(); } catch ( Exception ignore ){} }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
finally { try { socket.close(); }catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close socket", e); } } try { reader.close(); }catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close reader", e); } } reader = null; socket = null; }
// in java/org/apache/catalina/session/StandardManager.java
finally { // Close the input stream try { ois.close(); } catch (IOException f) { // ignored } // Delete the persistent storage file if (file.exists() ) file.delete(); }
// in java/org/apache/catalina/session/StandardManager.java
finally { if (error) { if (oos != null) { try { oos.close(); } catch (IOException ioe) { // Ignore } } if (bos != null) { try { bos.close(); } catch (IOException ioe) { // Ignore } } if (fos != null) { try { fos.close(); } catch (IOException ioe) { // Ignore } } } }
// in java/org/apache/catalina/session/StandardManager.java
finally { try { oos.close(); } catch (IOException f) { // Ignore } }
// in java/org/apache/catalina/session/JDBCStore.java
finally { try { if (rst != null) { rst.close(); } } catch (SQLException e) { // Ignore } release(_conn); }
// in java/org/apache/catalina/session/JDBCStore.java
finally { try { if (rst != null) rst.close(); } catch (SQLException e) { // Ignore } release(_conn); }
// in java/org/apache/catalina/session/JDBCStore.java
finally { try { if (rst != null) { rst.close(); } } catch (SQLException e) { // Ignore } if (ois != null) { try { ois.close(); } catch (IOException e) { // Ignore } } release(_conn); }
// in java/org/apache/catalina/session/JDBCStore.java
finally { if (oos != null) { oos.close(); } if (bis != null) { bis.close(); } if (in != null) { in.close(); } release(_conn); }
// in java/org/apache/catalina/session/FileStore.java
finally { // Close the input stream try { ois.close(); } catch (IOException f) { // Ignore } }
// in java/org/apache/catalina/session/FileStore.java
finally { oos.close(); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
finally { try { cometEvent.close(); } catch (IOException e) { container.getLogger().warn(sm.getString( "cometConnectionManagerValve.event"), e); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
finally { if (fis!=null) fis.close(); }
// in java/org/apache/catalina/servlets/CGIServlet.java
finally{ // Close the header reader if (cgiHeaderReader != null) { try { cgiHeaderReader.close(); } catch (IOException ioe) { log ("Exception closing header reader " + ioe); } } // Close the output stream if used if (cgiOutput != null) { try { cgiOutput.close(); } catch (IOException ioe) { log ("Exception closing output stream " + ioe); } } // Make sure the error stream reader has finished if (errReaderThread != null) { try { errReaderThread.join(stderrTimeout); } catch (InterruptedException e) { log ("Interupted waiting for stderr reader thread"); } } if (debug > 4) { log ("Running finally block"); } if (proc != null){ proc.destroy(); proc = null; } }
// in java/org/apache/catalina/servlets/CGIServlet.java
finally { try { rdr.close() ; } catch (IOException ce) { log("sendToLog error", ce) ; } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { // Close the input stream try { if (ois != null) ois.close(); } catch (IOException f) { // ignored } ois = null; if (originalLoader != null) Thread.currentThread().setContextClassLoader(originalLoader); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { if (oos != null) { try { oos.close(); } catch (IOException f) { // Ignore } oos = null; } }
// in java/org/apache/catalina/core/StandardServer.java
finally { // Close the socket now that we are done with it try { if (socket != null) { socket.close(); } } catch (IOException e) { // Ignore } }
// in java/org/apache/catalina/core/StandardServer.java
finally { ServerSocket serverSocket = awaitSocket; awaitThread = null; awaitSocket = null; // Close the server socket and return if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { // Ignore } } }
// in java/org/apache/catalina/core/StandardContext.java
finally { if (br != null) { try { br.close(); } catch (IOException ioe) {/*Ignore*/} } }
// in java/org/apache/catalina/util/ExtensionValidator.java
finally { if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/catalina/util/ExtensionValidator.java
finally { if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/catalina/util/ExtensionValidator.java
finally { if (jin != null) { try { jin.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/javax/el/ExpressionFactory.java
finally { try { if (br != null) { br.close(); } } catch (IOException ioe) {/*Ignore*/} try { if (isr != null) { isr.close(); } } catch (IOException ioe) {/*Ignore*/} try { is.close(); } catch (IOException ioe) {/*Ignore*/} }
// in java/javax/el/ExpressionFactory.java
finally { if (is != null) { try { is.close(); } catch (IOException e) { // Ignore } } }
390
unlock 43
                  
// in java/org/apache/juli/FileHandler.java
finally { writerLock.writeLock().unlock(); // Down grade to read-lock. This ensures the writer remains valid // until the log message is written writerLock.readLock().lock(); }
// in java/org/apache/juli/FileHandler.java
finally { writerLock.readLock().unlock(); }
// in java/org/apache/juli/FileHandler.java
finally { writerLock.writeLock().unlock(); }
// in java/org/apache/juli/FileHandler.java
finally { writerLock.readLock().unlock(); }
// in java/org/apache/juli/FileHandler.java
finally { writerLock.writeLock().unlock(); }
// in java/org/apache/catalina/tribes/group/interceptors/OrderInterceptor.java
finally { outLock.writeLock().unlock(); }
// in java/org/apache/catalina/tribes/group/interceptors/OrderInterceptor.java
finally { inLock.writeLock().unlock(); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
finally { rentry.unlock(); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
finally { diff.unlock(); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
finally { rentry.unlock(); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
finally{ unlock(); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
finally { unlock(); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
finally{ unlock(); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
finally{ unlock(); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
finally { unlock(); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
finally { unlock(); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
finally{ unlock(); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
finally{ unlock(); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
finally{ unlock(); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
finally { unlock(); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
finally { unlock(); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
finally { unlock(); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { session.unlock(); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { session.unlock(); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { if (session!=null) session.unlock(); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { session.unlock(); }
// in java/org/apache/catalina/core/ContainerBase.java
finally { l.unlock(); }
// in java/org/apache/catalina/core/ContainerBase.java
finally { l.unlock(); }
// in java/org/apache/catalina/core/ContainerBase.java
finally { l.unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { parametersLock.writeLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { mappingsLock.writeLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { referencesLock.writeLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { parametersLock.readLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { parametersLock.readLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { mappingsLock.readLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { referencesLock.readLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { referencesLock.readLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { parametersLock.writeLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { mappingsLock.writeLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { referencesLock.writeLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { parametersLock.readLock().unlock(); }
// in java/javax/el/ExpressionFactory.java
finally { readLock.unlock(); }
// in java/javax/el/ExpressionFactory.java
finally { writeLock.unlock(); }
45
closeNodeScope 39
                  
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 3); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, 2); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc004) { jjtree.closeNodeScope(jjtn004, 2); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, 2); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, jjtree.nodeArity() > 1); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } }
52
log 31
                  
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
finally { if (error) { // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); } }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
finally { if (error) { // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); } }
// in java/org/apache/catalina/servlets/CGIServlet.java
finally{ // Close the header reader if (cgiHeaderReader != null) { try { cgiHeaderReader.close(); } catch (IOException ioe) { log ("Exception closing header reader " + ioe); } } // Close the output stream if used if (cgiOutput != null) { try { cgiOutput.close(); } catch (IOException ioe) { log ("Exception closing output stream " + ioe); } } // Make sure the error stream reader has finished if (errReaderThread != null) { try { errReaderThread.join(stderrTimeout); } catch (InterruptedException e) { log ("Interupted waiting for stderr reader thread"); } } if (debug > 4) { log ("Running finally block"); } if (proc != null){ proc.destroy(); proc = null; } }
// in java/org/apache/catalina/servlets/CGIServlet.java
finally { try { rdr.close() ; } catch (IOException ce) { log("sendToLog error", ce) ; } }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
finally { String capturedlog = SystemLogHandler.stopCapture(); if (capturedlog != null && capturedlog.length() > 0) { getServletContext().log(capturedlog); } }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { // Write captured output if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } }
2765
handleThrowable 19
                  
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
finally { if (in != null) { try { in.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
finally { if (in != null) { try { in.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/jasper/servlet/JspCServletContext.java
finally { if (is != null) { try { is.close(); } catch (Throwable t2) { ExceptionUtils.handleThrowable(t2); } } }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (is != null) { try { is.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (fis != null) { try { fis.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } fragment.setURL(file.toURI().toURL()); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
// in java/org/apache/catalina/startup/TldConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/catalina/startup/TldConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/catalina/startup/TldConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/catalina/startup/ExpandWar.java
finally { if (!success) { // If something went wrong, delete expanded dir to keep things // clean deleteDir(docBase); } if (input != null) { try { input.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } input = null; } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } }
// in java/org/apache/catalina/startup/ExpandWar.java
finally { if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } }
// in java/org/apache/catalina/manager/ManagerServlet.java
finally { if (ostream != null) { try { ostream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } ostream = null; } if (istream != null) { try { istream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } istream = null; } }
// in java/org/apache/catalina/util/ExtensionValidator.java
finally { if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/catalina/util/ExtensionValidator.java
finally { if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
// in java/org/apache/catalina/util/ExtensionValidator.java
finally { if (jin != null) { try { jin.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
273
put 19
                  
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
finally { if ( selector != null ) pool.put(selector); }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
finally { if ( selector != null ) pool.put(selector); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
finally { if ( selector != null ) pool.put(selector); }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
finally { if (selector != null) { pool.put(selector); } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
finally { if (selector != null) { pool.put(selector); } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
finally { if (selector != null) { pool.put(selector); } }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
finally { if ( selector != null ) pool.put(selector); }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } if (jar != null) { jar.close(); } fragment.setURL(url); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } fragment.setURL(file.toURI().toURL()); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { // Get paths for WAR and expanded WAR in appBase // default to appBase dir + name expandedDocBase = new File(host.getAppBaseFile(), cn.getBaseName()); if (context != null && context.getDocBase() != null) { // first assume docBase is absolute expandedDocBase = new File(context.getDocBase()); if (!expandedDocBase.isAbsolute()) { // if docBase specified and relative, it must be relative to appBase expandedDocBase = new File(host.getAppBaseFile(), context.getDocBase()); } } // Add the eventual unpacked WAR and all the resources which will be // watched inside it if (isExternalWar && unpackWARs) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); deployedApp.redeployResources.put(contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { // Find an existing matching war and expanded folder if (!isExternal) { File warDocBase = new File(expandedDocBase.getAbsolutePath() + ".war"); if (warDocBase.exists()) { deployedApp.redeployResources.put(warDocBase.getAbsolutePath(), Long.valueOf(warDocBase.lastModified())); } } if (expandedDocBase.exists()) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { addWatchedResources(deployedApp, null, context); } // Add the context XML to the list of files which should trigger a redeployment if (!isExternal) { deployedApp.redeployResources.put( contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); } } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { // If we're unpacking WARs, the docBase will be mutated after // starting the context if (unpackWARs && context != null && context.getDocBase() != null) { File docBase = new File(host.getAppBaseFile(), cn.getBaseName()); deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified())); addWatchedResources(deployedApp, docBase.getAbsolutePath(), context); if (deployXML && !copyXML && (xmlInWar || xml.exists())) { deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } } else { addWatchedResources(deployedApp, null, context); } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { deployedApp.redeployResources.put(dir.getAbsolutePath(), Long.valueOf(dir.lastModified())); if (deployXML && xml.exists()) { if (xmlCopy == null) { deployedApp.redeployResources.put( xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } else { deployedApp.redeployResources.put( xmlCopy.getAbsolutePath(), Long.valueOf(xmlCopy.lastModified())); } } addWatchedResources(deployedApp, dir.getAbsolutePath(), context); // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
1022
currentThread 18
                  
// in java/org/apache/jasper/JspC.java
finally { if(originalClassLoader != null) { Thread.currentThread().setContextClassLoader(originalClassLoader); } }
// in java/org/apache/coyote/AsyncStateMachine.java
finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( oldCL); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldCL); } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(loader); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(loader); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(loader); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(loader); } }
// in java/org/apache/catalina/loader/WebappLoader.java
finally { if (container.getLoader() != null) { Thread.currentThread().setContextClassLoader (container.getLoader().getClassLoader()); } }
// in java/org/apache/catalina/realm/JAASRealm.java
finally { if(!isUseContextClassLoader()) { Thread.currentThread().setContextClassLoader(ocl); } }
// in java/org/apache/catalina/ant/ValidatorTask.java
finally { Thread.currentThread().setContextClassLoader(oldCL); closeRedirector(); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
finally { Thread.currentThread().setName(name); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
finally { Thread.currentThread().setName(name); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
finally { Thread.currentThread().setName(name); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
finally { Thread.currentThread().setName(name); }
// in java/org/apache/catalina/session/StandardSession.java
finally { if (oldTccl != null) { if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(oldTccl); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldTccl); } } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
finally { Thread.currentThread().setContextClassLoader(contextLoader); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { // Close the input stream try { if (ois != null) ois.close(); } catch (IOException f) { // ignored } ois = null; if (originalLoader != null) Thread.currentThread().setContextClassLoader(originalLoader); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { Thread.currentThread().setContextClassLoader(contextLoader); }
// in java/org/apache/catalina/core/ContainerBase.java
finally { Thread.currentThread().setContextClassLoader(cl); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
finally { if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( oldCL); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldCL); } }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
finally { Thread.currentThread().setContextClassLoader(loader); }
160
getAbsolutePath 15
                  
// in java/org/apache/catalina/startup/HostConfig.java
finally { // Get paths for WAR and expanded WAR in appBase // default to appBase dir + name expandedDocBase = new File(host.getAppBaseFile(), cn.getBaseName()); if (context != null && context.getDocBase() != null) { // first assume docBase is absolute expandedDocBase = new File(context.getDocBase()); if (!expandedDocBase.isAbsolute()) { // if docBase specified and relative, it must be relative to appBase expandedDocBase = new File(host.getAppBaseFile(), context.getDocBase()); } } // Add the eventual unpacked WAR and all the resources which will be // watched inside it if (isExternalWar && unpackWARs) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); deployedApp.redeployResources.put(contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { // Find an existing matching war and expanded folder if (!isExternal) { File warDocBase = new File(expandedDocBase.getAbsolutePath() + ".war"); if (warDocBase.exists()) { deployedApp.redeployResources.put(warDocBase.getAbsolutePath(), Long.valueOf(warDocBase.lastModified())); } } if (expandedDocBase.exists()) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { addWatchedResources(deployedApp, null, context); } // Add the context XML to the list of files which should trigger a redeployment if (!isExternal) { deployedApp.redeployResources.put( contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); } } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { // If we're unpacking WARs, the docBase will be mutated after // starting the context if (unpackWARs && context != null && context.getDocBase() != null) { File docBase = new File(host.getAppBaseFile(), cn.getBaseName()); deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified())); addWatchedResources(deployedApp, docBase.getAbsolutePath(), context); if (deployXML && !copyXML && (xmlInWar || xml.exists())) { deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } } else { addWatchedResources(deployedApp, null, context); } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { deployedApp.redeployResources.put(dir.getAbsolutePath(), Long.valueOf(dir.lastModified())); if (deployXML && xml.exists()) { if (xmlCopy == null) { deployedApp.redeployResources.put( xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } else { deployedApp.redeployResources.put( xmlCopy.getAbsolutePath(), Long.valueOf(xmlCopy.lastModified())); } } addWatchedResources(deployedApp, dir.getAbsolutePath(), context); // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
131
setContextClassLoader 14
                  
// in java/org/apache/jasper/JspC.java
finally { if(originalClassLoader != null) { Thread.currentThread().setContextClassLoader(originalClassLoader); } }
// in java/org/apache/coyote/AsyncStateMachine.java
finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( oldCL); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldCL); } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(loader); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(loader); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(loader); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(loader); } }
// in java/org/apache/catalina/loader/WebappLoader.java
finally { if (container.getLoader() != null) { Thread.currentThread().setContextClassLoader (container.getLoader().getClassLoader()); } }
// in java/org/apache/catalina/realm/JAASRealm.java
finally { if(!isUseContextClassLoader()) { Thread.currentThread().setContextClassLoader(ocl); } }
// in java/org/apache/catalina/ant/ValidatorTask.java
finally { Thread.currentThread().setContextClassLoader(oldCL); closeRedirector(); }
// in java/org/apache/catalina/session/StandardSession.java
finally { if (oldTccl != null) { if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(oldTccl); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldTccl); } } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
finally { Thread.currentThread().setContextClassLoader(contextLoader); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { // Close the input stream try { if (ois != null) ois.close(); } catch (IOException f) { // ignored } ois = null; if (originalLoader != null) Thread.currentThread().setContextClassLoader(originalLoader); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { Thread.currentThread().setContextClassLoader(contextLoader); }
// in java/org/apache/catalina/core/ContainerBase.java
finally { Thread.currentThread().setContextClassLoader(cl); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
finally { if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( oldCL); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldCL); } }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
finally { Thread.currentThread().setContextClassLoader(loader); }
48
recycle 13
                  
// in java/org/apache/jasper/runtime/PageContextImpl.java
finally { servlet = null; config = null; context = null; applicationContext = null; elContext = null; errorPageURL = null; request = null; response = null; depth = -1; baseOut.recycle(); session = null; attributes.clear(); for (BodyContentImpl body: outs) { body.recycle(); } }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { digester.reset(); ruleSet.recycle(); }
// in java/org/apache/catalina/session/StandardManager.java
finally { session.recycle(); }
// in java/org/apache/catalina/session/StandardManager.java
finally { // Measure against memory leaking if references to the session // object are kept in a shared field somewhere session.recycle(); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (error || response.isClosed() || !request.isComet()) { ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); request.recycle(); request.setFilterChain(null); response.recycle(); } }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!success || (!comet && !request.isAsync())) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!comet && !async) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { request.recycle(); response.recycle(); }
146
writeLock 12
                  
// in java/org/apache/juli/FileHandler.java
finally { writerLock.writeLock().unlock(); // Down grade to read-lock. This ensures the writer remains valid // until the log message is written writerLock.readLock().lock(); }
// in java/org/apache/juli/FileHandler.java
finally { writerLock.writeLock().unlock(); }
// in java/org/apache/juli/FileHandler.java
finally { writerLock.writeLock().unlock(); }
// in java/org/apache/catalina/tribes/group/interceptors/OrderInterceptor.java
finally { outLock.writeLock().unlock(); }
// in java/org/apache/catalina/tribes/group/interceptors/OrderInterceptor.java
finally { inLock.writeLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { parametersLock.writeLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { mappingsLock.writeLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { referencesLock.writeLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { parametersLock.writeLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { mappingsLock.writeLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { referencesLock.writeLock().unlock(); }
27
getString 11
                  
// in java/org/apache/tomcat/util/net/NioEndpoint.java
finally { if (launch) { try { getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN)); } catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } } } socket = null; status = null; //return to cache processorCache.offer(this); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
finally { if (launch) { try { getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN)); } catch (RejectedExecutionException x) { log.warn("Socket reprocessing request was rejected for:"+socket,x); try { //unable to handle connection at this time handler.process(socket, SocketStatus.DISCONNECT); } finally { countDownConnection(); } } catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } } } }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { log.error(sm.getString("contextConfig.contextClose"), e); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
finally { if (is != null) { try { is.close(); } catch (IOException ioe) { log.warn(sm.getString( "webappClassLoader.jdbcRemoveStreamError", contextName), ioe); } } }
// in java/org/apache/catalina/realm/DataSourceRealm.java
finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getPassword.exception", username)); } }
// in java/org/apache/catalina/realm/DataSourceRealm.java
finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getRoles.exception", username)); } }
// in java/org/apache/catalina/realm/JDBCRealm.java
finally { if (rs!=null) { try { rs.close(); } catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); } } dbConnection.commit(); }
// in java/org/apache/catalina/realm/JDBCRealm.java
finally { if (rs!=null) { try { rs.close(); } catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); } } dbConnection.commit(); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
finally { try { cometEvent.close(); } catch (IOException e) { container.getLogger().warn(sm.getString( "cometConnectionManagerValve.event"), e); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { synchronized(receivedMessageQueue) { for (Iterator<SessionMessage> iter = receivedMessageQueue.iterator(); iter.hasNext();) { SessionMessage smsg = iter.next(); if (!stateTimestampDrop) { messageReceived(smsg, smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (smsg.getEventType() != SessionMessage.EVT_GET_ALL_SESSIONS && smsg.getTimestamp() >= stateTransferCreateSendTime) { // FIXME handle EVT_GET_ALL_SESSIONS later messageReceived(smsg,smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.dropMessage",getName(), smsg.getEventTypeString(),new Date(stateTransferCreateSendTime), new Date(smsg.getTimestamp()))); } } } } receivedMessageQueue.clear(); receiverQueue = false ; } }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
finally { // Array must be remove: Current master request send endAccess at recycle. // Don't register this request session again! if(isCrossContext) { if(log.isDebugEnabled()) { log.debug(sm.getString("ReplicationValve.crossContext.remove")); } // crossContextSessions.remove() only exist at Java 5 // register ArrayList at a pool crossContextSessions.set(null); } }
1667
lastModified 10
                  
// in java/org/apache/catalina/startup/HostConfig.java
finally { // Get paths for WAR and expanded WAR in appBase // default to appBase dir + name expandedDocBase = new File(host.getAppBaseFile(), cn.getBaseName()); if (context != null && context.getDocBase() != null) { // first assume docBase is absolute expandedDocBase = new File(context.getDocBase()); if (!expandedDocBase.isAbsolute()) { // if docBase specified and relative, it must be relative to appBase expandedDocBase = new File(host.getAppBaseFile(), context.getDocBase()); } } // Add the eventual unpacked WAR and all the resources which will be // watched inside it if (isExternalWar && unpackWARs) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); deployedApp.redeployResources.put(contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { // Find an existing matching war and expanded folder if (!isExternal) { File warDocBase = new File(expandedDocBase.getAbsolutePath() + ".war"); if (warDocBase.exists()) { deployedApp.redeployResources.put(warDocBase.getAbsolutePath(), Long.valueOf(warDocBase.lastModified())); } } if (expandedDocBase.exists()) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { addWatchedResources(deployedApp, null, context); } // Add the context XML to the list of files which should trigger a redeployment if (!isExternal) { deployedApp.redeployResources.put( contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); } } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { // If we're unpacking WARs, the docBase will be mutated after // starting the context if (unpackWARs && context != null && context.getDocBase() != null) { File docBase = new File(host.getAppBaseFile(), cn.getBaseName()); deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified())); addWatchedResources(deployedApp, docBase.getAbsolutePath(), context); if (deployXML && !copyXML && (xmlInWar || xml.exists())) { deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } } else { addWatchedResources(deployedApp, null, context); } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { deployedApp.redeployResources.put(dir.getAbsolutePath(), Long.valueOf(dir.lastModified())); if (deployXML && xml.exists()) { if (xmlCopy == null) { deployedApp.redeployResources.put( xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } else { deployedApp.redeployResources.put( xmlCopy.getAbsolutePath(), Long.valueOf(xmlCopy.lastModified())); } } addWatchedResources(deployedApp, dir.getAbsolutePath(), context); // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
30
readLock 10
                  
// in java/org/apache/juli/FileHandler.java
finally { writerLock.writeLock().unlock(); // Down grade to read-lock. This ensures the writer remains valid // until the log message is written writerLock.readLock().lock(); }
// in java/org/apache/juli/FileHandler.java
finally { writerLock.readLock().unlock(); }
// in java/org/apache/juli/FileHandler.java
finally { writerLock.readLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { parametersLock.readLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { parametersLock.readLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { mappingsLock.readLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { referencesLock.readLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { referencesLock.readLock().unlock(); }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { parametersLock.readLock().unlock(); }
23
valueOf 10
                  
// in java/org/apache/catalina/startup/HostConfig.java
finally { // Get paths for WAR and expanded WAR in appBase // default to appBase dir + name expandedDocBase = new File(host.getAppBaseFile(), cn.getBaseName()); if (context != null && context.getDocBase() != null) { // first assume docBase is absolute expandedDocBase = new File(context.getDocBase()); if (!expandedDocBase.isAbsolute()) { // if docBase specified and relative, it must be relative to appBase expandedDocBase = new File(host.getAppBaseFile(), context.getDocBase()); } } // Add the eventual unpacked WAR and all the resources which will be // watched inside it if (isExternalWar && unpackWARs) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); deployedApp.redeployResources.put(contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { // Find an existing matching war and expanded folder if (!isExternal) { File warDocBase = new File(expandedDocBase.getAbsolutePath() + ".war"); if (warDocBase.exists()) { deployedApp.redeployResources.put(warDocBase.getAbsolutePath(), Long.valueOf(warDocBase.lastModified())); } } if (expandedDocBase.exists()) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { addWatchedResources(deployedApp, null, context); } // Add the context XML to the list of files which should trigger a redeployment if (!isExternal) { deployedApp.redeployResources.put( contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); } } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { // If we're unpacking WARs, the docBase will be mutated after // starting the context if (unpackWARs && context != null && context.getDocBase() != null) { File docBase = new File(host.getAppBaseFile(), cn.getBaseName()); deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified())); addWatchedResources(deployedApp, docBase.getAbsolutePath(), context); if (deployXML && !copyXML && (xmlInWar || xml.exists())) { deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } } else { addWatchedResources(deployedApp, null, context); } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { deployedApp.redeployResources.put(dir.getAbsolutePath(), Long.valueOf(dir.lastModified())); if (deployXML && xml.exists()) { if (xmlCopy == null) { deployedApp.redeployResources.put( xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } else { deployedApp.redeployResources.put( xmlCopy.getAbsolutePath(), Long.valueOf(xmlCopy.lastModified())); } } addWatchedResources(deployedApp, dir.getAbsolutePath(), context); // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
524
release 9
                  
// in java/org/apache/jasper/JspC.java
finally { if (loader != null) { LogFactory.release(loader); } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
finally { release(); }
// in java/org/apache/catalina/session/JDBCStore.java
finally { try { if (rst != null) { rst.close(); } } catch (SQLException e) { // Ignore } release(_conn); }
// in java/org/apache/catalina/session/JDBCStore.java
finally { try { if (rst != null) rst.close(); } catch (SQLException e) { // Ignore } release(_conn); }
// in java/org/apache/catalina/session/JDBCStore.java
finally { try { if (rst != null) { rst.close(); } } catch (SQLException e) { // Ignore } if (ois != null) { try { ois.close(); } catch (IOException e) { // Ignore } } release(_conn); }
// in java/org/apache/catalina/session/JDBCStore.java
finally { release(_conn); }
// in java/org/apache/catalina/session/JDBCStore.java
finally { release(_conn); }
// in java/org/apache/catalina/session/JDBCStore.java
finally { if (oos != null) { oos.close(); } if (bis != null) { bis.close(); } if (in != null) { in.close(); } release(_conn); }
// in java/org/apache/catalina/valves/SemaphoreValve.java
finally { if (shouldRelease) { semaphore.release(); } }
33
reset 9
                  
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java
finally { digester.reset(); }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { digester.reset(); ruleSet.recycle(); }
// in java/org/apache/catalina/startup/TldConfig.java
finally { tldDigester.reset(); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { digester.reset(); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { digester.reset(); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { if (context == null) { context = new FailedContext(); } context.setConfigFile(new URL("jar:" + war.toURI().toString() + "!/" + Constants.ApplicationContextXml)); if (istream != null) { try { istream.close(); } catch (IOException e) { /* Ignore */ } istream = null; } entry = null; if (jar != null) { try { jar.close(); } catch (IOException e) { /* Ignore */ } jar = null; } digester.reset(); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { digester.reset(); }
// in java/org/apache/catalina/realm/MemoryRealm.java
finally { digester.reset(); }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
finally { digester.reset(); }
113
removeServiced
8
                  
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
finally { removeServiced(name); }
// in java/org/apache/catalina/manager/ManagerServlet.java
finally { removeServiced(name); }
// in java/org/apache/catalina/manager/ManagerServlet.java
finally { removeServiced(name); }
// in java/org/apache/catalina/manager/ManagerServlet.java
finally { removeServiced(name); }
// in java/org/apache/catalina/manager/ManagerServlet.java
finally { removeServiced(name); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
finally { removeServiced(contextName); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
finally { removeServiced(contextName); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
finally { removeServiced(contextName); }
8
socket 7
                  
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
finally { if ( force || closed ) { closed = true; sc.socket().close(); sc.close(); } }
315
addWatchedResources 6
                  
// in java/org/apache/catalina/startup/HostConfig.java
finally { // Get paths for WAR and expanded WAR in appBase // default to appBase dir + name expandedDocBase = new File(host.getAppBaseFile(), cn.getBaseName()); if (context != null && context.getDocBase() != null) { // first assume docBase is absolute expandedDocBase = new File(context.getDocBase()); if (!expandedDocBase.isAbsolute()) { // if docBase specified and relative, it must be relative to appBase expandedDocBase = new File(host.getAppBaseFile(), context.getDocBase()); } } // Add the eventual unpacked WAR and all the resources which will be // watched inside it if (isExternalWar && unpackWARs) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); deployedApp.redeployResources.put(contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { // Find an existing matching war and expanded folder if (!isExternal) { File warDocBase = new File(expandedDocBase.getAbsolutePath() + ".war"); if (warDocBase.exists()) { deployedApp.redeployResources.put(warDocBase.getAbsolutePath(), Long.valueOf(warDocBase.lastModified())); } } if (expandedDocBase.exists()) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { addWatchedResources(deployedApp, null, context); } // Add the context XML to the list of files which should trigger a redeployment if (!isExternal) { deployedApp.redeployResources.put( contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); } } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { // If we're unpacking WARs, the docBase will be mutated after // starting the context if (unpackWARs && context != null && context.getDocBase() != null) { File docBase = new File(host.getAppBaseFile(), cn.getBaseName()); deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified())); addWatchedResources(deployedApp, docBase.getAbsolutePath(), context); if (deployXML && !copyXML && (xmlInWar || xml.exists())) { deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } } else { addWatchedResources(deployedApp, null, context); } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { deployedApp.redeployResources.put(dir.getAbsolutePath(), Long.valueOf(dir.lastModified())); if (deployXML && xml.exists()) { if (xmlCopy == null) { deployedApp.redeployResources.put( xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } else { deployedApp.redeployResources.put( xmlCopy.getAbsolutePath(), Long.valueOf(xmlCopy.lastModified())); } } addWatchedResources(deployedApp, dir.getAbsolutePath(), context); // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
8
getName 6
                  
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } if (jar != null) { jar.close(); } fragment.setURL(url); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } fragment.setURL(file.toURI().toURL()); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
// in java/org/apache/catalina/valves/StuckThreadDetectionValve.java
finally { activeThreads.remove(key); if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) { completedStuckThreadsQueue.add( new CompletedStuckThread(monitoredThread.getThread().getName(), monitoredThread.getActiveTimeInMillis())); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { synchronized(receivedMessageQueue) { for (Iterator<SessionMessage> iter = receivedMessageQueue.iterator(); iter.hasNext();) { SessionMessage smsg = iter.next(); if (!stateTimestampDrop) { messageReceived(smsg, smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (smsg.getEventType() != SessionMessage.EVT_GET_ALL_SESSIONS && smsg.getTimestamp() >= stateTransferCreateSendTime) { // FIXME handle EVT_GET_ALL_SESSIONS later messageReceived(smsg,smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.dropMessage",getName(), smsg.getEventTypeString(),new Date(stateTransferCreateSendTime), new Date(smsg.getTimestamp()))); } } } } receivedMessageQueue.clear(); receiverQueue = false ; } }
1196
setName 6
                  
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } if (jar != null) { jar.close(); } fragment.setURL(url); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } fragment.setURL(file.toURI().toURL()); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
finally { Thread.currentThread().setName(name); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
finally { Thread.currentThread().setName(name); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
finally { Thread.currentThread().setName(name); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
finally { Thread.currentThread().setName(name); }
82
warn 6
                  
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
finally { if (launch) { try { getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN)); } catch (RejectedExecutionException x) { log.warn("Socket reprocessing request was rejected for:"+socket,x); try { //unable to handle connection at this time handler.process(socket, SocketStatus.DISCONNECT); } finally { countDownConnection(); } } catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } } } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
finally { if (is != null) { try { is.close(); } catch (IOException ioe) { log.warn(sm.getString( "webappClassLoader.jdbcRemoveStreamError", contextName), ioe); } } }
// in java/org/apache/catalina/realm/JDBCRealm.java
finally { if (rs!=null) { try { rs.close(); } catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); } } dbConnection.commit(); }
// in java/org/apache/catalina/realm/JDBCRealm.java
finally { if (rs!=null) { try { rs.close(); } catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); } } dbConnection.commit(); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
finally { try { cometEvent.close(); } catch (IOException e) { container.getLogger().warn(sm.getString( "cometConnectionManagerValve.event"), e); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { synchronized(receivedMessageQueue) { for (Iterator<SessionMessage> iter = receivedMessageQueue.iterator(); iter.hasNext();) { SessionMessage smsg = iter.next(); if (!stateTimestampDrop) { messageReceived(smsg, smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (smsg.getEventType() != SessionMessage.EVT_GET_ALL_SESSIONS && smsg.getTimestamp() >= stateTransferCreateSendTime) { // FIXME handle EVT_GET_ALL_SESSIONS later messageReceived(smsg,smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.dropMessage",getName(), smsg.getEventTypeString(),new Date(stateTransferCreateSendTime), new Date(smsg.getTimestamp()))); } } } } receivedMessageQueue.clear(); receiverQueue = false ; } }
306
File 5
                  
// in java/org/apache/catalina/startup/HostConfig.java
finally { // Get paths for WAR and expanded WAR in appBase // default to appBase dir + name expandedDocBase = new File(host.getAppBaseFile(), cn.getBaseName()); if (context != null && context.getDocBase() != null) { // first assume docBase is absolute expandedDocBase = new File(context.getDocBase()); if (!expandedDocBase.isAbsolute()) { // if docBase specified and relative, it must be relative to appBase expandedDocBase = new File(host.getAppBaseFile(), context.getDocBase()); } } // Add the eventual unpacked WAR and all the resources which will be // watched inside it if (isExternalWar && unpackWARs) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); deployedApp.redeployResources.put(contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { // Find an existing matching war and expanded folder if (!isExternal) { File warDocBase = new File(expandedDocBase.getAbsolutePath() + ".war"); if (warDocBase.exists()) { deployedApp.redeployResources.put(warDocBase.getAbsolutePath(), Long.valueOf(warDocBase.lastModified())); } } if (expandedDocBase.exists()) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { addWatchedResources(deployedApp, null, context); } // Add the context XML to the list of files which should trigger a redeployment if (!isExternal) { deployedApp.redeployResources.put( contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); } } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { // If we're unpacking WARs, the docBase will be mutated after // starting the context if (unpackWARs && context != null && context.getDocBase() != null) { File docBase = new File(host.getAppBaseFile(), cn.getBaseName()); deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified())); addWatchedResources(deployedApp, docBase.getAbsolutePath(), context); if (deployXML && !copyXML && (xmlInWar || xml.exists())) { deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } } else { addWatchedResources(deployedApp, null, context); } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
315
PrivilegedSetTccl 5
                  
// in java/org/apache/coyote/AsyncStateMachine.java
finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( oldCL); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldCL); } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(loader); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(loader); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(loader); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(loader); } }
// in java/org/apache/catalina/session/StandardSession.java
finally { if (oldTccl != null) { if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(oldTccl); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldTccl); } } }
// in java/org/apache/catalina/core/AsyncContextImpl.java
finally { if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( oldCL); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldCL); } }
12
debug 5
                  
// in java/org/apache/jasper/compiler/JspReader.java
finally { if (reader != null) { try { reader.close(); } catch (Exception any) { if(log.isDebugEnabled()) { log.debug("Exception closing reader: ", any); } } } }
// in java/org/apache/jasper/JspCompilationContext.java
finally { if (uc != null) { try { uc.getInputStream().close(); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; } } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
finally { try { socket.close(); }catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close socket", e); } } try { reader.close(); }catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close reader", e); } } reader = null; socket = null; }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
finally { // Array must be remove: Current master request send endAccess at recycle. // Don't register this request session again! if(isCrossContext) { if(log.isDebugEnabled()) { log.debug(sm.getString("ReplicationValve.crossContext.remove")); } // crossContextSessions.remove() only exist at Java 5 // register ArrayList at a pool crossContextSessions.set(null); } }
801
doPrivileged 5
                  
// in java/org/apache/coyote/AsyncStateMachine.java
finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( oldCL); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldCL); } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(loader); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(loader); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(loader); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(loader); } }
// in java/org/apache/catalina/session/StandardSession.java
finally { if (oldTccl != null) { if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(oldTccl); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldTccl); } } }
// in java/org/apache/catalina/core/AsyncContextImpl.java
finally { if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( oldCL); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldCL); } }
151
error 5
                  
// in java/org/apache/tomcat/util/net/NioEndpoint.java
finally { if (launch) { try { getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN)); } catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } } } socket = null; status = null; //return to cache processorCache.offer(this); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
finally { if (launch) { try { getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN)); } catch (RejectedExecutionException x) { log.warn("Socket reprocessing request was rejected for:"+socket,x); try { //unable to handle connection at this time handler.process(socket, SocketStatus.DISCONNECT); } finally { countDownConnection(); } } catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } } } }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { log.error(sm.getString("contextConfig.contextClose"), e); } }
// in java/org/apache/catalina/realm/DataSourceRealm.java
finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getPassword.exception", username)); } }
// in java/org/apache/catalina/realm/DataSourceRealm.java
finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getRoles.exception", username)); } }
637
exists 5
                  
// in java/org/apache/catalina/startup/HostConfig.java
finally { // Get paths for WAR and expanded WAR in appBase // default to appBase dir + name expandedDocBase = new File(host.getAppBaseFile(), cn.getBaseName()); if (context != null && context.getDocBase() != null) { // first assume docBase is absolute expandedDocBase = new File(context.getDocBase()); if (!expandedDocBase.isAbsolute()) { // if docBase specified and relative, it must be relative to appBase expandedDocBase = new File(host.getAppBaseFile(), context.getDocBase()); } } // Add the eventual unpacked WAR and all the resources which will be // watched inside it if (isExternalWar && unpackWARs) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); deployedApp.redeployResources.put(contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { // Find an existing matching war and expanded folder if (!isExternal) { File warDocBase = new File(expandedDocBase.getAbsolutePath() + ".war"); if (warDocBase.exists()) { deployedApp.redeployResources.put(warDocBase.getAbsolutePath(), Long.valueOf(warDocBase.lastModified())); } } if (expandedDocBase.exists()) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { addWatchedResources(deployedApp, null, context); } // Add the context XML to the list of files which should trigger a redeployment if (!isExternal) { deployedApp.redeployResources.put( contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); } } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { // If we're unpacking WARs, the docBase will be mutated after // starting the context if (unpackWARs && context != null && context.getDocBase() != null) { File docBase = new File(host.getAppBaseFile(), cn.getBaseName()); deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified())); addWatchedResources(deployedApp, docBase.getAbsolutePath(), context); if (deployXML && !copyXML && (xmlInWar || xml.exists())) { deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } } else { addWatchedResources(deployedApp, null, context); } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { deployedApp.redeployResources.put(dir.getAbsolutePath(), Long.valueOf(dir.lastModified())); if (deployXML && xml.exists()) { if (xmlCopy == null) { deployedApp.redeployResources.put( xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } else { deployedApp.redeployResources.put( xmlCopy.getAbsolutePath(), Long.valueOf(xmlCopy.lastModified())); } } addWatchedResources(deployedApp, dir.getAbsolutePath(), context); // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/session/StandardManager.java
finally { // Close the input stream try { ois.close(); } catch (IOException f) { // ignored } // Delete the persistent storage file if (file.exists() ) file.delete(); }
116
getServletContext 5
                  
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
finally { String capturedlog = SystemLogHandler.stopCapture(); if (capturedlog != null && capturedlog.length() > 0) { getServletContext().log(capturedlog); } }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { // Write captured output if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } }
134
isDebugEnabled 5
                  
// in java/org/apache/jasper/compiler/JspReader.java
finally { if (reader != null) { try { reader.close(); } catch (Exception any) { if(log.isDebugEnabled()) { log.debug("Exception closing reader: ", any); } } } }
// in java/org/apache/jasper/JspCompilationContext.java
finally { if (uc != null) { try { uc.getInputStream().close(); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; } } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
finally { try { socket.close(); }catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close socket", e); } } try { reader.close(); }catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close reader", e); } } reader = null; socket = null; }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
finally { // Array must be remove: Current master request send endAccess at recycle. // Don't register this request session again! if(isCrossContext) { if(log.isDebugEnabled()) { log.debug(sm.getString("ReplicationValve.crossContext.remove")); } // crossContextSessions.remove() only exist at Java 5 // register ArrayList at a pool crossContextSessions.set(null); } }
735
length 5
                  
// in java/org/apache/catalina/core/StandardWrapperValve.java
finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
finally { String capturedlog = SystemLogHandler.stopCapture(); if (capturedlog != null && capturedlog.length() > 0) { getServletContext().log(capturedlog); } }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { // Write captured output if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } }
635
remove 5
                  
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
finally { poller.remove(att,SelectionKey.OP_WRITE); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
finally { poller.remove(att,SelectionKey.OP_READ); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; }
// in java/org/apache/catalina/tribes/group/RpcChannel.java
finally { responseMap.remove(key); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
finally { if (!ok || response.isClosed() || (event.getEventType() == CometEvent.EventType.END) || (event.getEventType() == CometEvent.EventType.ERROR && !(event.getEventSubType() == CometEvent.EventSubType.TIMEOUT))) { // Remove the connection from webapp reload tracking cometRequests.remove(request); // Remove connection from session expiration tracking // Note: can't get the session if it has been invalidated but // OK since session listener will have done clean-up HttpSession session = request.getSession(false); if (session != null) { synchronized (session) { Request[] reqs = null; try { reqs = (Request[]) session.getAttribute(cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } if (reqs != null) { boolean found = false; for (int i = 0; !found && (i < reqs.length); i++) { found = (reqs[i] == request); } if (found) { if (reqs.length > 1) { Request[] newConnectionInfos = new Request[reqs.length - 1]; int pos = 0; for (int i = 0; i < reqs.length; i++) { if (reqs[i] != request) { newConnectionInfos[pos++] = reqs[i]; } } try { session.setAttribute( cometRequestsAttribute, newConnectionInfos); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } else { try { session.removeAttribute( cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } } } } } } }
// in java/org/apache/catalina/valves/StuckThreadDetectionValve.java
finally { activeThreads.remove(key); if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) { completedStuckThreadsQueue.add( new CompletedStuckThread(monitoredThread.getThread().getName(), monitoredThread.getActiveTimeInMillis())); } }
259
stopCapture
5
                  
// in java/org/apache/catalina/core/StandardWrapperValve.java
finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
finally { String capturedlog = SystemLogHandler.stopCapture(); if (capturedlog != null && capturedlog.length() > 0) { getServletContext().log(capturedlog); } }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { // Write captured output if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } }
5
clear 4
                  
// in java/org/apache/jasper/runtime/PageContextImpl.java
finally { servlet = null; config = null; context = null; applicationContext = null; elContext = null; errorPageURL = null; request = null; response = null; depth = -1; baseOut.recycle(); session = null; attributes.clear(); for (BodyContentImpl body: outs) { body.recycle(); } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
finally { sendfileCount += successCount; addS.clear(); addCount = 0; }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
finally { ackbuf.clear(); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { synchronized(receivedMessageQueue) { for (Iterator<SessionMessage> iter = receivedMessageQueue.iterator(); iter.hasNext();) { SessionMessage smsg = iter.next(); if (!stateTimestampDrop) { messageReceived(smsg, smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (smsg.getEventType() != SessionMessage.EVT_GET_ALL_SESSIONS && smsg.getTimestamp() >= stateTransferCreateSendTime) { // FIXME handle EVT_GET_ALL_SESSIONS later messageReceived(smsg,smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.dropMessage",getName(), smsg.getEventTypeString(),new Date(stateTransferCreateSendTime), new Date(smsg.getTimestamp()))); } } } } receivedMessageQueue.clear(); receiverQueue = false ; } }
191
clearEncoders 4
                  
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!success || (!comet && !request.isAsync())) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!comet && !async) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } }
6
getAddress 4
                  
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { synchronized(receivedMessageQueue) { for (Iterator<SessionMessage> iter = receivedMessageQueue.iterator(); iter.hasNext();) { SessionMessage smsg = iter.next(); if (!stateTimestampDrop) { messageReceived(smsg, smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (smsg.getEventType() != SessionMessage.EVT_GET_ALL_SESSIONS && smsg.getTimestamp() >= stateTransferCreateSendTime) { // FIXME handle EVT_GET_ALL_SESSIONS later messageReceived(smsg,smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.dropMessage",getName(), smsg.getEventTypeString(),new Date(stateTransferCreateSendTime), new Date(smsg.getTimestamp()))); } } } } receivedMessageQueue.clear(); receiverQueue = false ; } }
48
getDocBase 4
                  
// in java/org/apache/catalina/startup/HostConfig.java
finally { // Get paths for WAR and expanded WAR in appBase // default to appBase dir + name expandedDocBase = new File(host.getAppBaseFile(), cn.getBaseName()); if (context != null && context.getDocBase() != null) { // first assume docBase is absolute expandedDocBase = new File(context.getDocBase()); if (!expandedDocBase.isAbsolute()) { // if docBase specified and relative, it must be relative to appBase expandedDocBase = new File(host.getAppBaseFile(), context.getDocBase()); } } // Add the eventual unpacked WAR and all the resources which will be // watched inside it if (isExternalWar && unpackWARs) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); deployedApp.redeployResources.put(contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { // Find an existing matching war and expanded folder if (!isExternal) { File warDocBase = new File(expandedDocBase.getAbsolutePath() + ".war"); if (warDocBase.exists()) { deployedApp.redeployResources.put(warDocBase.getAbsolutePath(), Long.valueOf(warDocBase.lastModified())); } } if (expandedDocBase.exists()) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { addWatchedResources(deployedApp, null, context); } // Add the context XML to the list of files which should trigger a redeployment if (!isExternal) { deployedApp.redeployResources.put( contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); } } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { // If we're unpacking WARs, the docBase will be mutated after // starting the context if (unpackWARs && context != null && context.getDocBase() != null) { File docBase = new File(host.getAppBaseFile(), cn.getBaseName()); deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified())); addWatchedResources(deployedApp, docBase.getAbsolutePath(), context); if (deployXML && !copyXML && (xmlInWar || xml.exists())) { deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } } else { addWatchedResources(deployedApp, null, context); } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
27
iterator 4
                  
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
finally { if (!successful) { for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) { FileItem fileItem = iterator.next(); try { fileItem.delete(); } catch (Exception e) { // ignore it } } } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { synchronized(receivedMessageQueue) { for (Iterator<SessionMessage> iter = receivedMessageQueue.iterator(); iter.hasNext();) { SessionMessage smsg = iter.next(); if (!stateTimestampDrop) { messageReceived(smsg, smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (smsg.getEventType() != SessionMessage.EVT_GET_ALL_SESSIONS && smsg.getTimestamp() >= stateTransferCreateSendTime) { // FIXME handle EVT_GET_ALL_SESSIONS later messageReceived(smsg,smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.dropMessage",getName(), smsg.getEventTypeString(),new Date(stateTransferCreateSendTime), new Date(smsg.getTimestamp()))); } } } } receivedMessageQueue.clear(); receiverQueue = false ; } }
239
set 4
                  
// in java/org/apache/tomcat/jni/socket/AprSocket.java
finally { long t1 = System.currentTimeMillis(); t1 -= t0; if (t1 > context.maxHandlerTime.get()) { context.maxHandlerTime.set(t1); } context.totalHandlerTime.addAndGet(t1); context.handlerCount.incrementAndGet(); }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
finally { // Array must be remove: Current master request send endAccess at recycle. // Don't register this request session again! if(isCrossContext) { if(log.isDebugEnabled()) { log.debug(sm.getString("ReplicationValve.crossContext.remove")); } // crossContextSessions.remove() only exist at Java 5 // register ArrayList at a pool crossContextSessions.set(null); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
finally { if (ApplicationDispatcher.WRAP_SAME_OBJECT) { lastServicedRequest.set(null); lastServicedResponse.set(null); } }
111
unbindThread 4
                  
// in java/org/apache/catalina/core/StandardContext.java
finally { // Unbinding thread unbindThread(oldCCL); }
// in java/org/apache/catalina/core/StandardContext.java
finally { // Unbinding thread unbindThread(oldCCL); }
// in java/org/apache/catalina/core/StandardContext.java
finally{ unbindThread(old); }
// in java/org/apache/catalina/core/StandardContext.java
finally { // Unbinding thread unbindThread(oldCCL); }
7
addGlobalRedeployResources
3
                  
// in java/org/apache/catalina/startup/HostConfig.java
finally { // Get paths for WAR and expanded WAR in appBase // default to appBase dir + name expandedDocBase = new File(host.getAppBaseFile(), cn.getBaseName()); if (context != null && context.getDocBase() != null) { // first assume docBase is absolute expandedDocBase = new File(context.getDocBase()); if (!expandedDocBase.isAbsolute()) { // if docBase specified and relative, it must be relative to appBase expandedDocBase = new File(host.getAppBaseFile(), context.getDocBase()); } } // Add the eventual unpacked WAR and all the resources which will be // watched inside it if (isExternalWar && unpackWARs) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); deployedApp.redeployResources.put(contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { // Find an existing matching war and expanded folder if (!isExternal) { File warDocBase = new File(expandedDocBase.getAbsolutePath() + ".war"); if (warDocBase.exists()) { deployedApp.redeployResources.put(warDocBase.getAbsolutePath(), Long.valueOf(warDocBase.lastModified())); } } if (expandedDocBase.exists()) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { addWatchedResources(deployedApp, null, context); } // Add the context XML to the list of files which should trigger a redeployment if (!isExternal) { deployedApp.redeployResources.put( contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); } } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { // If we're unpacking WARs, the docBase will be mutated after // starting the context if (unpackWARs && context != null && context.getDocBase() != null) { File docBase = new File(host.getAppBaseFile(), cn.getBaseName()); deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified())); addWatchedResources(deployedApp, docBase.getAbsolutePath(), context); if (deployXML && !copyXML && (xmlInWar || xml.exists())) { deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } } else { addWatchedResources(deployedApp, null, context); } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { deployedApp.redeployResources.put(dir.getAbsolutePath(), Long.valueOf(dir.lastModified())); if (deployXML && xml.exists()) { if (xmlCopy == null) { deployedApp.redeployResources.put( xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } else { deployedApp.redeployResources.put( xmlCopy.getAbsolutePath(), Long.valueOf(xmlCopy.lastModified())); } } addWatchedResources(deployedApp, dir.getAbsolutePath(), context); // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
3
cancel 3
                  
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
finally { if (key!=null) try {key.cancel();} catch (Exception ignore) {} if (selector!=null) try {selector.close();} catch (Exception ignore) {} }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } }
16
closeRedirector
3
                  
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
finally { closeRedirector(); if (reader != null) { try { reader.close(); } catch (IOException ioe) { // Ignore } reader = null; } if (istream != null) { try { istream.close(); } catch (IOException ioe) { // Ignore } } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
finally { closeRedirector(); }
// in java/org/apache/catalina/ant/ValidatorTask.java
finally { Thread.currentThread().setContextClassLoader(oldCL); closeRedirector(); }
3
delete 3
                  
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
finally { if (!successful) { for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) { FileItem fileItem = iterator.next(); try { fileItem.delete(); } catch (Exception e) { // ignore it } } } }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
finally { if (warPart != null) { warPart.delete(); } warPart = null; }
// in java/org/apache/catalina/session/StandardManager.java
finally { // Close the input stream try { ois.close(); } catch (IOException f) { // ignored } // Delete the persistent storage file if (file.exists() ) file.delete(); }
56
getAppBaseFile 3
                  
// in java/org/apache/catalina/startup/HostConfig.java
finally { // Get paths for WAR and expanded WAR in appBase // default to appBase dir + name expandedDocBase = new File(host.getAppBaseFile(), cn.getBaseName()); if (context != null && context.getDocBase() != null) { // first assume docBase is absolute expandedDocBase = new File(context.getDocBase()); if (!expandedDocBase.isAbsolute()) { // if docBase specified and relative, it must be relative to appBase expandedDocBase = new File(host.getAppBaseFile(), context.getDocBase()); } } // Add the eventual unpacked WAR and all the resources which will be // watched inside it if (isExternalWar && unpackWARs) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); deployedApp.redeployResources.put(contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { // Find an existing matching war and expanded folder if (!isExternal) { File warDocBase = new File(expandedDocBase.getAbsolutePath() + ".war"); if (warDocBase.exists()) { deployedApp.redeployResources.put(warDocBase.getAbsolutePath(), Long.valueOf(warDocBase.lastModified())); } } if (expandedDocBase.exists()) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { addWatchedResources(deployedApp, null, context); } // Add the context XML to the list of files which should trigger a redeployment if (!isExternal) { deployedApp.redeployResources.put( contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); } } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { // If we're unpacking WARs, the docBase will be mutated after // starting the context if (unpackWARs && context != null && context.getDocBase() != null) { File docBase = new File(host.getAppBaseFile(), cn.getBaseName()); deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified())); addWatchedResources(deployedApp, docBase.getAbsolutePath(), context); if (deployXML && !copyXML && (xmlInWar || xml.exists())) { deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } } else { addWatchedResources(deployedApp, null, context); } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
34
getEventType 3
                  
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
finally { if (!ok || response.isClosed() || (event.getEventType() == CometEvent.EventType.END) || (event.getEventType() == CometEvent.EventType.ERROR && !(event.getEventSubType() == CometEvent.EventSubType.TIMEOUT))) { // Remove the connection from webapp reload tracking cometRequests.remove(request); // Remove connection from session expiration tracking // Note: can't get the session if it has been invalidated but // OK since session listener will have done clean-up HttpSession session = request.getSession(false); if (session != null) { synchronized (session) { Request[] reqs = null; try { reqs = (Request[]) session.getAttribute(cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } if (reqs != null) { boolean found = false; for (int i = 0; !found && (i < reqs.length); i++) { found = (reqs[i] == request); } if (found) { if (reqs.length > 1) { Request[] newConnectionInfos = new Request[reqs.length - 1]; int pos = 0; for (int i = 0; i < reqs.length; i++) { if (reqs[i] != request) { newConnectionInfos[pos++] = reqs[i]; } } try { session.setAttribute( cometRequestsAttribute, newConnectionInfos); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } else { try { session.removeAttribute( cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } } } } } } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { synchronized(receivedMessageQueue) { for (Iterator<SessionMessage> iter = receivedMessageQueue.iterator(); iter.hasNext();) { SessionMessage smsg = iter.next(); if (!stateTimestampDrop) { messageReceived(smsg, smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (smsg.getEventType() != SessionMessage.EVT_GET_ALL_SESSIONS && smsg.getTimestamp() >= stateTransferCreateSendTime) { // FIXME handle EVT_GET_ALL_SESSIONS later messageReceived(smsg,smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.dropMessage",getName(), smsg.getEventTypeString(),new Date(stateTransferCreateSendTime), new Date(smsg.getTimestamp()))); } } } } receivedMessageQueue.clear(); receiverQueue = false ; } }
8
getLogger 3
                  
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
finally { try { cometEvent.close(); } catch (IOException e) { container.getLogger().warn(sm.getString( "cometConnectionManagerValve.event"), e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } }
217
getMessage 3
                  
// in java/org/apache/jasper/JspCompilationContext.java
finally { if (uc != null) { try { uc.getInputStream().close(); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; } } }
// in java/org/apache/catalina/tribes/group/interceptors/OrderInterceptor.java
finally { msg.getMessage().trim(4); }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
finally { addAndGetCurrentSize(-msg.getMessage().getLength()); link = link.next(); }
393
getRequestProcessor 3
                  
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (error || response.isClosed() || !request.isComet()) { ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); request.recycle(); request.setFilterChain(null); response.recycle(); } }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!success || (!comet && !request.isAsync())) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!comet && !async) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } }
22
isClosed 3
                  
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
finally { // Should be open here but just in case if (!socket.isClosed()) { socket.close(); } }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
finally { if (!ok || response.isClosed() || (event.getEventType() == CometEvent.EventType.END) || (event.getEventType() == CometEvent.EventType.ERROR && !(event.getEventSubType() == CometEvent.EventSubType.TIMEOUT))) { // Remove the connection from webapp reload tracking cometRequests.remove(request); // Remove connection from session expiration tracking // Note: can't get the session if it has been invalidated but // OK since session listener will have done clean-up HttpSession session = request.getSession(false); if (session != null) { synchronized (session) { Request[] reqs = null; try { reqs = (Request[]) session.getAttribute(cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } if (reqs != null) { boolean found = false; for (int i = 0; !found && (i < reqs.length); i++) { found = (reqs[i] == request); } if (found) { if (reqs.length > 1) { Request[] newConnectionInfos = new Request[reqs.length - 1]; int pos = 0; for (int i = 0; i < reqs.length; i++) { if (reqs[i] != request) { newConnectionInfos[pos++] = reqs[i]; } } try { session.setAttribute( cometRequestsAttribute, newConnectionInfos); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } else { try { session.removeAttribute( cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } } } } } } }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (error || response.isClosed() || !request.isComet()) { ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); request.recycle(); request.setFilterChain(null); response.recycle(); } }
17
jj_save
3
                  
// in java/org/apache/el/parser/ELParser.java
finally { jj_save(0, xla); }
// in java/org/apache/el/parser/ELParser.java
finally { jj_save(1, xla); }
// in java/org/apache/el/parser/ELParser.java
finally { jj_save(2, xla); }
3
lock 3
                  
// in java/org/apache/juli/FileHandler.java
finally { writerLock.writeLock().unlock(); // Down grade to read-lock. This ensures the writer remains valid // until the log message is written writerLock.readLock().lock(); }
79
next 3
                  
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
finally { if (!successful) { for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) { FileItem fileItem = iterator.next(); try { fileItem.delete(); } catch (Exception e) { // ignore it } } } }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
finally { addAndGetCurrentSize(-msg.getMessage().getLength()); link = link.next(); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { synchronized(receivedMessageQueue) { for (Iterator<SessionMessage> iter = receivedMessageQueue.iterator(); iter.hasNext();) { SessionMessage smsg = iter.next(); if (!stateTimestampDrop) { messageReceived(smsg, smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (smsg.getEventType() != SessionMessage.EVT_GET_ALL_SESSIONS && smsg.getTimestamp() >= stateTransferCreateSendTime) { // FIXME handle EVT_GET_ALL_SESSIONS later messageReceived(smsg,smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.dropMessage",getName(), smsg.getEventTypeString(),new Date(stateTransferCreateSendTime), new Date(smsg.getTimestamp()))); } } } } receivedMessageQueue.clear(); receiverQueue = false ; } }
248
removeFromEnvironment 3
                  
// in java/org/apache/catalina/realm/JNDIRealm.java
finally { try { context.removeFromEnvironment( Context.SECURITY_AUTHENTICATION); } catch (NamingException e) { // Ignore } try { context.removeFromEnvironment( "javax.security.sasl.server.authentication"); } catch (NamingException e) { // Ignore } try { context.removeFromEnvironment( "javax.security.sasl.qop"); } catch (NamingException e) { // Ignore } }
7
setAttribute 3
                  
// in java/org/apache/jasper/runtime/PageContextImpl.java
finally { if (includeUri != null) request.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH, includeUri); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
finally { if (!ok || response.isClosed() || (event.getEventType() == CometEvent.EventType.END) || (event.getEventType() == CometEvent.EventType.ERROR && !(event.getEventSubType() == CometEvent.EventSubType.TIMEOUT))) { // Remove the connection from webapp reload tracking cometRequests.remove(request); // Remove connection from session expiration tracking // Note: can't get the session if it has been invalidated but // OK since session listener will have done clean-up HttpSession session = request.getSession(false); if (session != null) { synchronized (session) { Request[] reqs = null; try { reqs = (Request[]) session.getAttribute(cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } if (reqs != null) { boolean found = false; for (int i = 0; !found && (i < reqs.length); i++) { found = (reqs[i] == request); } if (found) { if (reqs.length > 1) { Request[] newConnectionInfos = new Request[reqs.length - 1]; int pos = 0; for (int i = 0; i < reqs.length; i++) { if (reqs[i] != request) { newConnectionInfos[pos++] = reqs[i]; } } try { session.setAttribute( cometRequestsAttribute, newConnectionInfos); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } else { try { session.removeAttribute( cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } } } } } } }
// in java/org/apache/catalina/core/AsyncContextImpl.java
finally { request.setAttribute(Globals.DISPATCHER_TYPE_ATTR, type); }
186
setWorkerThreadName 3
                  
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (error || response.isClosed() || !request.isComet()) { ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); request.recycle(); request.setFilterChain(null); response.recycle(); } }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!success || (!comet && !request.isAsync())) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!comet && !async) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } }
6
toString 3
                  
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } if (jar != null) { jar.close(); } fragment.setURL(url); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } fragment.setURL(file.toURI().toURL()); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { if (context == null) { context = new FailedContext(); } context.setConfigFile(new URL("jar:" + war.toURI().toString() + "!/" + Constants.ApplicationContextXml)); if (istream != null) { try { istream.close(); } catch (IOException e) { /* Ignore */ } istream = null; } entry = null; if (jar != null) { try { jar.close(); } catch (IOException e) { /* Ignore */ } jar = null; } digester.reset(); }
1036
Date 2
                  
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { synchronized(receivedMessageQueue) { for (Iterator<SessionMessage> iter = receivedMessageQueue.iterator(); iter.hasNext();) { SessionMessage smsg = iter.next(); if (!stateTimestampDrop) { messageReceived(smsg, smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (smsg.getEventType() != SessionMessage.EVT_GET_ALL_SESSIONS && smsg.getTimestamp() >= stateTransferCreateSendTime) { // FIXME handle EVT_GET_ALL_SESSIONS later messageReceived(smsg,smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.dropMessage",getName(), smsg.getEventTypeString(),new Date(stateTransferCreateSendTime), new Date(smsg.getTimestamp()))); } } } } receivedMessageQueue.clear(); receiverQueue = false ; } }
54
SocketProcessor 2
                  
// in java/org/apache/tomcat/util/net/NioEndpoint.java
finally { if (launch) { try { getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN)); } catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } } } socket = null; status = null; //return to cache processorCache.offer(this); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
finally { if (launch) { try { getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN)); } catch (RejectedExecutionException x) { log.warn("Socket reprocessing request was rejected for:"+socket,x); try { //unable to handle connection at this time handler.process(socket, SocketStatus.DISCONNECT); } finally { countDownConnection(); } } catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } } } }
8
cancelKey 2
                  
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
finally { poller.remove(att,SelectionKey.OP_WRITE); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
finally { poller.remove(att,SelectionKey.OP_READ); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; }
5
commit 2
                  
// in java/org/apache/catalina/realm/JDBCRealm.java
finally { if (rs!=null) { try { rs.close(); } catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); } } dbConnection.commit(); }
// in java/org/apache/catalina/realm/JDBCRealm.java
finally { if (rs!=null) { try { rs.close(); } catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); } } dbConnection.commit(); }
6
currentTimeMillis 2
                  
// in java/org/apache/tomcat/jni/socket/AprSocket.java
finally { long t1 = System.currentTimeMillis(); t1 -= t0; if (t1 > context.maxHandlerTime.get()) { context.maxHandlerTime.set(t1); } context.totalHandlerTime.addAndGet(t1); context.handlerCount.incrementAndGet(); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (error || response.isClosed() || !request.isComet()) { ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); request.recycle(); request.setFilterChain(null); response.recycle(); } }
235
execute 2
                  
// in java/org/apache/tomcat/util/net/NioEndpoint.java
finally { if (launch) { try { getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN)); } catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } } } socket = null; status = null; //return to cache processorCache.offer(this); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
finally { if (launch) { try { getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN)); } catch (RejectedExecutionException x) { log.warn("Socket reprocessing request was rejected for:"+socket,x); try { //unable to handle connection at this time handler.process(socket, SocketStatus.DISCONNECT); } finally { countDownConnection(); } } catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } } } }
81
getBaseName 2
                  
// in java/org/apache/catalina/startup/HostConfig.java
finally { // Get paths for WAR and expanded WAR in appBase // default to appBase dir + name expandedDocBase = new File(host.getAppBaseFile(), cn.getBaseName()); if (context != null && context.getDocBase() != null) { // first assume docBase is absolute expandedDocBase = new File(context.getDocBase()); if (!expandedDocBase.isAbsolute()) { // if docBase specified and relative, it must be relative to appBase expandedDocBase = new File(host.getAppBaseFile(), context.getDocBase()); } } // Add the eventual unpacked WAR and all the resources which will be // watched inside it if (isExternalWar && unpackWARs) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); deployedApp.redeployResources.put(contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { // Find an existing matching war and expanded folder if (!isExternal) { File warDocBase = new File(expandedDocBase.getAbsolutePath() + ".war"); if (warDocBase.exists()) { deployedApp.redeployResources.put(warDocBase.getAbsolutePath(), Long.valueOf(warDocBase.lastModified())); } } if (expandedDocBase.exists()) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { addWatchedResources(deployedApp, null, context); } // Add the context XML to the list of files which should trigger a redeployment if (!isExternal) { deployedApp.redeployResources.put( contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); } } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { // If we're unpacking WARs, the docBase will be mutated after // starting the context if (unpackWARs && context != null && context.getDocBase() != null) { File docBase = new File(host.getAppBaseFile(), cn.getBaseName()); deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified())); addWatchedResources(deployedApp, docBase.getAbsolutePath(), context); if (deployXML && !copyXML && (xmlInWar || xml.exists())) { deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } } else { addWatchedResources(deployedApp, null, context); } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
21
getCoyoteRequest 2
                  
// in java/org/apache/catalina/valves/RemoteIpValve.java
finally { request.setRemoteAddr(originalRemoteAddr); request.setRemoteHost(originalRemoteHost); request.setSecure(originalSecure); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString(originalScheme); request.setServerPort(originalServerPort); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
finally { // Restore original method so that it is written into access log request.getCoyoteRequest().method().setString(oldMethod); }
36
getExecutor 2
                  
// in java/org/apache/tomcat/util/net/NioEndpoint.java
finally { if (launch) { try { getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN)); } catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } } } socket = null; status = null; //return to cache processorCache.offer(this); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
finally { if (launch) { try { getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN)); } catch (RejectedExecutionException x) { log.warn("Socket reprocessing request was rejected for:"+socket,x); try { //unable to handle connection at this time handler.process(socket, SocketStatus.DISCONNECT); } finally { countDownConnection(); } } catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } } } }
36
getLoader 2
                  
// in java/org/apache/catalina/loader/WebappLoader.java
finally { if (container.getLoader() != null) { Thread.currentThread().setContextClassLoader (container.getLoader().getClassLoader()); } }
42
getTimestamp 2
                  
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { synchronized(receivedMessageQueue) { for (Iterator<SessionMessage> iter = receivedMessageQueue.iterator(); iter.hasNext();) { SessionMessage smsg = iter.next(); if (!stateTimestampDrop) { messageReceived(smsg, smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (smsg.getEventType() != SessionMessage.EVT_GET_ALL_SESSIONS && smsg.getTimestamp() >= stateTransferCreateSendTime) { // FIXME handle EVT_GET_ALL_SESSIONS later messageReceived(smsg,smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.dropMessage",getName(), smsg.getEventTypeString(),new Date(stateTransferCreateSendTime), new Date(smsg.getTimestamp()))); } } } } receivedMessageQueue.clear(); receiverQueue = false ; } }
13
getURL 2
                  
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } if (jar != null) { jar.close(); } fragment.setURL(url); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } fragment.setURL(file.toURI().toURL()); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
42
getWriter 2
                  
// in java/org/apache/jasper/compiler/Compiler.java
finally { if (tfp != null && ctxt.isPrototypeMode()) { tfp.removeProtoTypeFiles(null); } // Make sure these object which are only used during the // generation and compilation of the JSP page get // dereferenced so that they can be GC'd and reduce the // memory footprint. tfp = null; errDispatcher = null; pageInfo = null; // Only get rid of the pageNodes if in production. // In development mode, they are used for detailed // error messages. // http://issues.apache.org/bugzilla/show_bug.cgi?id=37062 if (!this.options.getDevelopment()) { pageNodes = null; } if (ctxt.getWriter() != null) { ctxt.getWriter().close(); ctxt.setWriter(null); } }
26
hasNext 2
                  
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
finally { if (!successful) { for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) { FileItem fileItem = iterator.next(); try { fileItem.delete(); } catch (Exception e) { // ignore it } } } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { synchronized(receivedMessageQueue) { for (Iterator<SessionMessage> iter = receivedMessageQueue.iterator(); iter.hasNext();) { SessionMessage smsg = iter.next(); if (!stateTimestampDrop) { messageReceived(smsg, smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (smsg.getEventType() != SessionMessage.EVT_GET_ALL_SESSIONS && smsg.getTimestamp() >= stateTransferCreateSendTime) { // FIXME handle EVT_GET_ALL_SESSIONS later messageReceived(smsg,smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.dropMessage",getName(), smsg.getEventTypeString(),new Date(stateTransferCreateSendTime), new Date(smsg.getTimestamp()))); } } } } receivedMessageQueue.clear(); receiverQueue = false ; } }
231
heartbeat 2
                  
// in java/org/apache/catalina/tribes/group/interceptors/TwoPhaseCommitInterceptor.java
finally { super.heartbeat(); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
finally { super.heartbeat(); }
13
info 2
                  
// in java/org/apache/catalina/core/StandardWrapperValve.java
finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } }
245
messageReceived 2
                  
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { synchronized(receivedMessageQueue) { for (Iterator<SessionMessage> iter = receivedMessageQueue.iterator(); iter.hasNext();) { SessionMessage smsg = iter.next(); if (!stateTimestampDrop) { messageReceived(smsg, smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (smsg.getEventType() != SessionMessage.EVT_GET_ALL_SESSIONS && smsg.getTimestamp() >= stateTransferCreateSendTime) { // FIXME handle EVT_GET_ALL_SESSIONS later messageReceived(smsg,smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.dropMessage",getName(), smsg.getEventTypeString(),new Date(stateTransferCreateSendTime), new Date(smsg.getTimestamp()))); } } } } receivedMessageQueue.clear(); receiverQueue = false ; } }
28
onClose 2
                  
// in java/org/apache/catalina/websocket/StreamInbound.java
finally { onClose(status); }
// in java/org/apache/catalina/websocket/StreamInbound.java
finally { onClose(Constants.OPCODE_CLOSE); }
3
println 2
                  
// in java/org/apache/catalina/core/StandardWrapper.java
finally { if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } }
// in java/org/apache/catalina/core/StandardWrapper.java
finally { // Write captured output if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } }
540
returnSender 2
                  
// in java/org/apache/catalina/tribes/transport/bio/PooledMultiSender.java
finally { if ( sender != null ) returnSender(sender); }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
finally { returnSender(sender); if (!connected) disconnect(); }
3
selectNow 2
                  
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } }
6
setParseFailed
2
                  
// in java/org/apache/catalina/connector/Request.java
finally { if (partsParseException != null || !success) { parameters.setParseFailed(true); } }
// in java/org/apache/catalina/connector/Request.java
finally { if (!success) { parameters.setParseFailed(true); } }
2
setStatus 2
                  
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
finally { if (error) { // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); } }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
finally { if (error) { // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); } }
97
setString 2
                  
// in java/org/apache/catalina/valves/RemoteIpValve.java
finally { request.setRemoteAddr(originalRemoteAddr); request.setRemoteHost(originalRemoteHost); request.setSecure(originalSecure); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString(originalScheme); request.setServerPort(originalServerPort); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
finally { // Restore original method so that it is written into access log request.getCoyoteRequest().method().setString(oldMethod); }
101
setURL
2
                  
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } if (jar != null) { jar.close(); } fragment.setURL(url); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } fragment.setURL(file.toURI().toURL()); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
2
toURI 2
                  
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } fragment.setURL(file.toURI().toURL()); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
// in java/org/apache/catalina/startup/HostConfig.java
finally { if (context == null) { context = new FailedContext(); } context.setConfigFile(new URL("jar:" + war.toURI().toString() + "!/" + Constants.ApplicationContextXml)); if (istream != null) { try { istream.close(); } catch (IOException e) { /* Ignore */ } istream = null; } entry = null; if (jar != null) { try { jar.close(); } catch (IOException e) { /* Ignore */ } jar = null; } digester.reset(); }
40
userCredentialsRemove 2
                  
// in java/org/apache/catalina/realm/JNDIRealm.java
finally { userCredentialsRemove(context); }
// in java/org/apache/catalina/realm/JNDIRealm.java
finally { if (roleSearchAsUser) { userCredentialsRemove(context); } }
3
CompletedStuckThread
1
                  
// in java/org/apache/catalina/valves/StuckThreadDetectionValve.java
finally { activeThreads.remove(key); if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) { completedStuckThreadsQueue.add( new CompletedStuckThread(monitoredThread.getThread().getName(), monitoredThread.getActiveTimeInMillis())); } }
1
FailedContext 1
                  
// in java/org/apache/catalina/startup/HostConfig.java
finally { if (context == null) { context = new FailedContext(); } context.setConfigFile(new URL("jar:" + war.toURI().toString() + "!/" + Constants.ApplicationContextXml)); if (istream != null) { try { istream.close(); } catch (IOException e) { /* Ignore */ } istream = null; } entry = null; if (jar != null) { try { jar.close(); } catch (IOException e) { /* Ignore */ } jar = null; } digester.reset(); }
4
URL 1
                  
// in java/org/apache/catalina/startup/HostConfig.java
finally { if (context == null) { context = new FailedContext(); } context.setConfigFile(new URL("jar:" + war.toURI().toString() + "!/" + Constants.ApplicationContextXml)); if (istream != null) { try { istream.close(); } catch (IOException e) { /* Ignore */ } istream = null; } entry = null; if (jar != null) { try { jar.close(); } catch (IOException e) { /* Ignore */ } jar = null; } digester.reset(); }
34
add 1
                  
// in java/org/apache/catalina/valves/StuckThreadDetectionValve.java
finally { activeThreads.remove(key); if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) { completedStuckThreadsQueue.add( new CompletedStuckThread(monitoredThread.getThread().getName(), monitoredThread.getActiveTimeInMillis())); } }
555
addAndGet 1
                  
// in java/org/apache/tomcat/jni/socket/AprSocket.java
finally { long t1 = System.currentTimeMillis(); t1 -= t0; if (t1 > context.maxHandlerTime.get()) { context.maxHandlerTime.set(t1); } context.totalHandlerTime.addAndGet(t1); context.handlerCount.incrementAndGet(); }
17
addAndGetCurrentSize 1
                  
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
finally { addAndGetCurrentSize(-msg.getMessage().getLength()); link = link.next(); }
2
arraycopy 1
                  
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
finally { // Restore delimiter. System.arraycopy(boundary, 0, boundary, 2, boundary.length - 2); boundaryLength = boundary.length; boundary[0] = CR; boundary[1] = LF; }
178
closeQuietly
1
                  
// in java/org/apache/tomcat/util/http/fileupload/DeferredFileOutputStream.java
finally { IOUtils.closeQuietly(fis); }
1
countDownConnection 1
                  
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
finally { if (launch) { try { getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN)); } catch (RejectedExecutionException x) { log.warn("Socket reprocessing request was rejected for:"+socket,x); try { //unable to handle connection at this time handler.process(socket, SocketStatus.DISCONNECT); } finally { countDownConnection(); } } catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } } } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
finally { countDownConnection(); }
13
decTripCount
1
                  
// in java/org/apache/jasper/compiler/TagFileProcessor.java
finally { wrapper.decTripCount(); }
1
decrementAndGet 1
                  
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
finally { if ( s == null ) active.decrementAndGet();//we were unable to find a selector }
23
deleteDir 1
                  
// in java/org/apache/catalina/startup/ExpandWar.java
finally { if (!success) { // If something went wrong, delete expanded dir to keep things // clean deleteDir(docBase); } if (input != null) { try { input.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } input = null; } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } }
6
destroy 1
                  
// in java/org/apache/catalina/servlets/CGIServlet.java
finally{ // Close the header reader if (cgiHeaderReader != null) { try { cgiHeaderReader.close(); } catch (IOException ioe) { log ("Exception closing header reader " + ioe); } } // Close the output stream if used if (cgiOutput != null) { try { cgiOutput.close(); } catch (IOException ioe) { log ("Exception closing output stream " + ioe); } } // Make sure the error stream reader has finished if (errReaderThread != null) { try { errReaderThread.join(stderrTimeout); } catch (InterruptedException e) { log ("Interupted waiting for stderr reader thread"); } } if (debug > 4) { log ("Running finally block"); } if (proc != null){ proc.destroy(); proc = null; } }
53
disconnect 1
                  
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
finally { returnSender(sender); if (!connected) disconnect(); }
18
dispose
1
                  
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
finally { if (gssContext != null) { try { gssContext.dispose(); } catch (GSSException e) { // Ignore } } if (lc != null) { try { lc.logout(); } catch (LoginException e) { // Ignore } } }
1
doStatistics 1
                  
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
finally { // FIXME this stats update are not cheap!! if(doStatistics()) { updateStats(totalstart,start); } }
6
get 1
                  
// in java/org/apache/tomcat/jni/socket/AprSocket.java
finally { long t1 = System.currentTimeMillis(); t1 -= t0; if (t1 > context.maxHandlerTime.get()) { context.maxHandlerTime.set(t1); } context.totalHandlerTime.addAndGet(t1); context.handlerCount.incrementAndGet(); }
811
getActiveTimeInMillis 1
                  
// in java/org/apache/catalina/valves/StuckThreadDetectionValve.java
finally { activeThreads.remove(key); if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) { completedStuckThreadsQueue.add( new CompletedStuckThread(monitoredThread.getThread().getName(), monitoredThread.getActiveTimeInMillis())); } }
2
getAttribute 1
                  
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
finally { if (!ok || response.isClosed() || (event.getEventType() == CometEvent.EventType.END) || (event.getEventType() == CometEvent.EventType.ERROR && !(event.getEventSubType() == CometEvent.EventSubType.TIMEOUT))) { // Remove the connection from webapp reload tracking cometRequests.remove(request); // Remove connection from session expiration tracking // Note: can't get the session if it has been invalidated but // OK since session listener will have done clean-up HttpSession session = request.getSession(false); if (session != null) { synchronized (session) { Request[] reqs = null; try { reqs = (Request[]) session.getAttribute(cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } if (reqs != null) { boolean found = false; for (int i = 0; !found && (i < reqs.length); i++) { found = (reqs[i] == request); } if (found) { if (reqs.length > 1) { Request[] newConnectionInfos = new Request[reqs.length - 1]; int pos = 0; for (int i = 0; i < reqs.length; i++) { if (reqs[i] != request) { newConnectionInfos[pos++] = reqs[i]; } } try { session.setAttribute( cometRequestsAttribute, newConnectionInfos); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } else { try { session.removeAttribute( cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } } } } } } }
247
getBufferPool 1
                  
// in java/org/apache/catalina/tribes/group/GroupChannel.java
finally { if ( buffer != null ) BufferPool.getBufferPool().returnBuffer(buffer); }
8
getClassLoader 1
                  
// in java/org/apache/catalina/loader/WebappLoader.java
finally { if (container.getLoader() != null) { Thread.currentThread().setContextClassLoader (container.getLoader().getClassLoader()); } }
122
getDevelopment 1
                  
// in java/org/apache/jasper/compiler/Compiler.java
finally { if (tfp != null && ctxt.isPrototypeMode()) { tfp.removeProtoTypeFiles(null); } // Make sure these object which are only used during the // generation and compilation of the JSP page get // dereferenced so that they can be GC'd and reduce the // memory footprint. tfp = null; errDispatcher = null; pageInfo = null; // Only get rid of the pageNodes if in production. // In development mode, they are used for detailed // error messages. // http://issues.apache.org/bugzilla/show_bug.cgi?id=37062 if (!this.options.getDevelopment()) { pageNodes = null; } if (ctxt.getWriter() != null) { ctxt.getWriter().close(); ctxt.setWriter(null); } }
13
getEventSubType
1
                  
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
finally { if (!ok || response.isClosed() || (event.getEventType() == CometEvent.EventType.END) || (event.getEventType() == CometEvent.EventType.ERROR && !(event.getEventSubType() == CometEvent.EventSubType.TIMEOUT))) { // Remove the connection from webapp reload tracking cometRequests.remove(request); // Remove connection from session expiration tracking // Note: can't get the session if it has been invalidated but // OK since session listener will have done clean-up HttpSession session = request.getSession(false); if (session != null) { synchronized (session) { Request[] reqs = null; try { reqs = (Request[]) session.getAttribute(cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } if (reqs != null) { boolean found = false; for (int i = 0; !found && (i < reqs.length); i++) { found = (reqs[i] == request); } if (found) { if (reqs.length > 1) { Request[] newConnectionInfos = new Request[reqs.length - 1]; int pos = 0; for (int i = 0; i < reqs.length; i++) { if (reqs[i] != request) { newConnectionInfos[pos++] = reqs[i]; } } try { session.setAttribute( cometRequestsAttribute, newConnectionInfos); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } else { try { session.removeAttribute( cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } } } } } } }
1
getEventTypeString 1
                  
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { synchronized(receivedMessageQueue) { for (Iterator<SessionMessage> iter = receivedMessageQueue.iterator(); iter.hasNext();) { SessionMessage smsg = iter.next(); if (!stateTimestampDrop) { messageReceived(smsg, smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (smsg.getEventType() != SessionMessage.EVT_GET_ALL_SESSIONS && smsg.getTimestamp() >= stateTransferCreateSendTime) { // FIXME handle EVT_GET_ALL_SESSIONS later messageReceived(smsg,smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.dropMessage",getName(), smsg.getEventTypeString(),new Date(stateTransferCreateSendTime), new Date(smsg.getTimestamp()))); } } } } receivedMessageQueue.clear(); receiverQueue = false ; } }
4
getInputStream 1
                  
// in java/org/apache/jasper/JspCompilationContext.java
finally { if (uc != null) { try { uc.getInputStream().close(); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; } } }
50
getJspFile 1
                  
// in java/org/apache/jasper/JspCompilationContext.java
finally { if (uc != null) { try { uc.getInputStream().close(); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; } } }
20
getLength 1
                  
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
finally { addAndGetCurrentSize(-msg.getMessage().getLength()); link = link.next(); }
182
getLogManager 1
                  
// in java/org/apache/catalina/startup/Catalina.java
finally { // If JULI is used, shut JULI down *after* the server shuts down // so log messages aren't lost LogManager logManager = LogManager.getLogManager(); if (logManager instanceof ClassLoaderLogManager) { ((ClassLoaderLogManager) logManager).shutdown(); } }
6
getMappingData 1
                  
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (error || response.isClosed() || !request.isComet()) { ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); request.recycle(); request.setFilterChain(null); response.recycle(); } }
20
getRequestCount 1
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
finally { setRequestCount(getRequestCount()+1); keepalive(); if ( exception != null ) throw exception; }
6
getSession 1
                  
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
finally { if (!ok || response.isClosed() || (event.getEventType() == CometEvent.EventType.END) || (event.getEventType() == CometEvent.EventType.ERROR && !(event.getEventSubType() == CometEvent.EventSubType.TIMEOUT))) { // Remove the connection from webapp reload tracking cometRequests.remove(request); // Remove connection from session expiration tracking // Note: can't get the session if it has been invalidated but // OK since session listener will have done clean-up HttpSession session = request.getSession(false); if (session != null) { synchronized (session) { Request[] reqs = null; try { reqs = (Request[]) session.getAttribute(cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } if (reqs != null) { boolean found = false; for (int i = 0; !found && (i < reqs.length); i++) { found = (reqs[i] == request); } if (found) { if (reqs.length > 1) { Request[] newConnectionInfos = new Request[reqs.length - 1]; int pos = 0; for (int i = 0; i < reqs.length; i++) { if (reqs[i] != request) { newConnectionInfos[pos++] = reqs[i]; } } try { session.setAttribute( cometRequestsAttribute, newConnectionInfos); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } else { try { session.removeAttribute( cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } } } } } } }
78
getStartTime 1
                  
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (error || response.isClosed() || !request.isComet()) { ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); request.recycle(); request.setFilterChain(null); response.recycle(); } }
7
getThread 1
                  
// in java/org/apache/catalina/valves/StuckThreadDetectionValve.java
finally { activeThreads.remove(key); if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) { completedStuckThreadsQueue.add( new CompletedStuckThread(monitoredThread.getThread().getName(), monitoredThread.getActiveTimeInMillis())); } }
5
incrementAndGet 1
                  
// in java/org/apache/tomcat/jni/socket/AprSocket.java
finally { long t1 = System.currentTimeMillis(); t1 -= t0; if (t1 > context.maxHandlerTime.get()) { context.maxHandlerTime.set(t1); } context.totalHandlerTime.addAndGet(t1); context.handlerCount.incrementAndGet(); }
34
isAbsolute 1
                  
// in java/org/apache/catalina/startup/HostConfig.java
finally { // Get paths for WAR and expanded WAR in appBase // default to appBase dir + name expandedDocBase = new File(host.getAppBaseFile(), cn.getBaseName()); if (context != null && context.getDocBase() != null) { // first assume docBase is absolute expandedDocBase = new File(context.getDocBase()); if (!expandedDocBase.isAbsolute()) { // if docBase specified and relative, it must be relative to appBase expandedDocBase = new File(host.getAppBaseFile(), context.getDocBase()); } } // Add the eventual unpacked WAR and all the resources which will be // watched inside it if (isExternalWar && unpackWARs) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); deployedApp.redeployResources.put(contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { // Find an existing matching war and expanded folder if (!isExternal) { File warDocBase = new File(expandedDocBase.getAbsolutePath() + ".war"); if (warDocBase.exists()) { deployedApp.redeployResources.put(warDocBase.getAbsolutePath(), Long.valueOf(warDocBase.lastModified())); } } if (expandedDocBase.exists()) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { addWatchedResources(deployedApp, null, context); } // Add the context XML to the list of files which should trigger a redeployment if (!isExternal) { deployedApp.redeployResources.put( contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); } } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); }
33
isAsync 1
                  
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!success || (!comet && !request.isAsync())) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } }
31
isComet 1
                  
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (error || response.isClosed() || !request.isComet()) { ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); request.recycle(); request.setFilterChain(null); response.recycle(); } }
11
isPrototypeMode 1
                  
// in java/org/apache/jasper/compiler/Compiler.java
finally { if (tfp != null && ctxt.isPrototypeMode()) { tfp.removeProtoTypeFiles(null); } // Make sure these object which are only used during the // generation and compilation of the JSP page get // dereferenced so that they can be GC'd and reduce the // memory footprint. tfp = null; errDispatcher = null; pageInfo = null; // Only get rid of the pageNodes if in production. // In development mode, they are used for detailed // error messages. // http://issues.apache.org/bugzilla/show_bug.cgi?id=37062 if (!this.options.getDevelopment()) { pageNodes = null; } if (ctxt.getWriter() != null) { ctxt.getWriter().close(); ctxt.setWriter(null); } }
6
isUseContextClassLoader 1
                  
// in java/org/apache/catalina/realm/JAASRealm.java
finally { if(!isUseContextClassLoader()) { Thread.currentThread().setContextClassLoader(ocl); } }
3
isWarnEnabled 1
                  
// in java/org/apache/catalina/ha/session/DeltaManager.java
finally { synchronized(receivedMessageQueue) { for (Iterator<SessionMessage> iter = receivedMessageQueue.iterator(); iter.hasNext();) { SessionMessage smsg = iter.next(); if (!stateTimestampDrop) { messageReceived(smsg, smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (smsg.getEventType() != SessionMessage.EVT_GET_ALL_SESSIONS && smsg.getTimestamp() >= stateTransferCreateSendTime) { // FIXME handle EVT_GET_ALL_SESSIONS later messageReceived(smsg,smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.dropMessage",getName(), smsg.getEventTypeString(),new Date(stateTransferCreateSendTime), new Date(smsg.getTimestamp()))); } } } } receivedMessageQueue.clear(); receiverQueue = false ; } }
44
join 1
                  
// in java/org/apache/catalina/servlets/CGIServlet.java
finally{ // Close the header reader if (cgiHeaderReader != null) { try { cgiHeaderReader.close(); } catch (IOException ioe) { log ("Exception closing header reader " + ioe); } } // Close the output stream if used if (cgiOutput != null) { try { cgiOutput.close(); } catch (IOException ioe) { log ("Exception closing output stream " + ioe); } } // Make sure the error stream reader has finished if (errReaderThread != null) { try { errReaderThread.join(stderrTimeout); } catch (InterruptedException e) { log ("Interupted waiting for stderr reader thread"); } } if (debug > 4) { log ("Running finally block"); } if (proc != null){ proc.destroy(); proc = null; } }
8
keepalive 1
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
finally { setRequestCount(getRequestCount()+1); keepalive(); if ( exception != null ) throw exception; }
10
logAccess 1
                  
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (error || response.isClosed() || !request.isComet()) { ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); request.recycle(); request.setFilterChain(null); response.recycle(); } }
13
logout 1
                  
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
finally { if (gssContext != null) { try { gssContext.dispose(); } catch (GSSException e) { // Ignore } } if (lc != null) { try { lc.logout(); } catch (LoginException e) { // Ignore } } }
7
markAsDone
1
                  
// in java/org/apache/catalina/valves/StuckThreadDetectionValve.java
finally { activeThreads.remove(key); if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) { completedStuckThreadsQueue.add( new CompletedStuckThread(monitoredThread.getThread().getName(), monitoredThread.getActiveTimeInMillis())); } }
1
method 1
                  
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
finally { // Restore original method so that it is written into access log request.getCoyoteRequest().method().setString(oldMethod); }
138
nodeArity 1
                  
// in java/org/apache/el/parser/ELParser.java
finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, jjtree.nodeArity() > 1); } }
3
offer 1
                  
// in java/org/apache/tomcat/util/net/NioEndpoint.java
finally { if (launch) { try { getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN)); } catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } } } socket = null; status = null; //return to cache processorCache.offer(this); }
37
optSet 1
                  
// in java/org/apache/coyote/http11/upgrade/UpgradeAprProcessor.java
finally { if (!block) { Socket.optSet(socket, Socket.APR_SO_NONBLOCK, 0); } }
17
position 1
                  
// in java/org/apache/catalina/websocket/Utf8Decoder.java
finally { in.position(pos); }
57
process 1
                  
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
finally { if (launch) { try { getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN)); } catch (RejectedExecutionException x) { log.warn("Socket reprocessing request was rejected for:"+socket,x); try { //unable to handle connection at this time handler.process(socket, SocketStatus.DISCONNECT); } finally { countDownConnection(); } } catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } } } }
32
read 1
                  
// in java/org/apache/catalina/servlets/CGIServlet.java
finally { // Attempt to consume any leftover byte if something bad happens, // such as a socket disconnect on the servlet side; otherwise, the // external process could hang if (bufRead != -1) { while ((bufRead = cgiOutput.read(bBuf)) != -1) { // NOOP - just read the data } } }
169
removeAttribute 1
                  
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
finally { if (!ok || response.isClosed() || (event.getEventType() == CometEvent.EventType.END) || (event.getEventType() == CometEvent.EventType.ERROR && !(event.getEventSubType() == CometEvent.EventSubType.TIMEOUT))) { // Remove the connection from webapp reload tracking cometRequests.remove(request); // Remove connection from session expiration tracking // Note: can't get the session if it has been invalidated but // OK since session listener will have done clean-up HttpSession session = request.getSession(false); if (session != null) { synchronized (session) { Request[] reqs = null; try { reqs = (Request[]) session.getAttribute(cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } if (reqs != null) { boolean found = false; for (int i = 0; !found && (i < reqs.length); i++) { found = (reqs[i] == request); } if (found) { if (reqs.length > 1) { Request[] newConnectionInfos = new Request[reqs.length - 1]; int pos = 0; for (int i = 0; i < reqs.length; i++) { if (reqs[i] != request) { newConnectionInfos[pos++] = reqs[i]; } } try { session.setAttribute( cometRequestsAttribute, newConnectionInfos); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } else { try { session.removeAttribute( cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } } } } } } }
59
removeFactory
1
                  
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
finally { removeFactory(fmsg); }
1
removeProtoTypeFiles 1
                  
// in java/org/apache/jasper/compiler/Compiler.java
finally { if (tfp != null && ctxt.isPrototypeMode()) { tfp.removeProtoTypeFiles(null); } // Make sure these object which are only used during the // generation and compilation of the JSP page get // dereferenced so that they can be GC'd and reduce the // memory footprint. tfp = null; errDispatcher = null; pageInfo = null; // Only get rid of the pageNodes if in production. // In development mode, they are used for detailed // error messages. // http://issues.apache.org/bugzilla/show_bug.cgi?id=37062 if (!this.options.getDevelopment()) { pageNodes = null; } if (ctxt.getWriter() != null) { ctxt.getWriter().close(); ctxt.setWriter(null); } }
2
returnBuffer 1
                  
// in java/org/apache/catalina/tribes/group/GroupChannel.java
finally { if ( buffer != null ) BufferPool.getBufferPool().returnBuffer(buffer); }
4
scheme 1
                  
// in java/org/apache/catalina/valves/RemoteIpValve.java
finally { request.setRemoteAddr(originalRemoteAddr); request.setRemoteHost(originalRemoteHost); request.setSecure(originalSecure); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString(originalScheme); request.setServerPort(originalServerPort); }
23
setCluster 1
                  
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
finally { if ( manager != null && (manager instanceof ClusterManager)) ((ClusterManager)manager).setCluster(this); }
15
setConfigFile 1
                  
// in java/org/apache/catalina/startup/HostConfig.java
finally { if (context == null) { context = new FailedContext(); } context.setConfigFile(new URL("jar:" + war.toURI().toString() + "!/" + Constants.ApplicationContextXml)); if (istream != null) { try { istream.close(); } catch (IOException e) { /* Ignore */ } istream = null; } entry = null; if (jar != null) { try { jar.close(); } catch (IOException e) { /* Ignore */ } jar = null; } digester.reset(); }
6
setFilterChain 1
                  
// in java/org/apache/catalina/connector/CoyoteAdapter.java
finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (error || response.isClosed() || !request.isComet()) { ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); request.recycle(); request.setFilterChain(null); response.recycle(); } }
5
setPrototypeMode 1
                  
// in java/org/apache/jasper/servlet/JspServletWrapper.java
finally { ctxt.setPrototypeMode(false); }
2
setRemoteAddr 1
                  
// in java/org/apache/catalina/valves/RemoteIpValve.java
finally { request.setRemoteAddr(originalRemoteAddr); request.setRemoteHost(originalRemoteHost); request.setSecure(originalSecure); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString(originalScheme); request.setServerPort(originalServerPort); }
3
setRemoteHost 1
                  
// in java/org/apache/catalina/valves/RemoteIpValve.java
finally { request.setRemoteAddr(originalRemoteAddr); request.setRemoteHost(originalRemoteHost); request.setSecure(originalSecure); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString(originalScheme); request.setServerPort(originalServerPort); }
3
setRequestCount 1
                  
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
finally { setRequestCount(getRequestCount()+1); keepalive(); if ( exception != null ) throw exception; }
9
setSecure 1
                  
// in java/org/apache/catalina/valves/RemoteIpValve.java
finally { request.setRemoteAddr(originalRemoteAddr); request.setRemoteHost(originalRemoteHost); request.setSecure(originalSecure); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString(originalScheme); request.setServerPort(originalServerPort); }
12
setSendFile 1
                  
// in java/org/apache/tomcat/util/net/NioEndpoint.java
finally { if (sc!=null) sc.setSendFile(false); }
2
setServerPort 1
                  
// in java/org/apache/catalina/valves/RemoteIpValve.java
finally { request.setRemoteAddr(originalRemoteAddr); request.setRemoteHost(originalRemoteHost); request.setSecure(originalSecure); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString(originalScheme); request.setServerPort(originalServerPort); }
13
setStartChildren 1
                  
// in java/org/apache/catalina/mbeans/ContainerMBean.java
finally { if(container != null) { container.setStartChildren(oldValue); } }
2
setWriter 1
                  
// in java/org/apache/jasper/compiler/Compiler.java
finally { if (tfp != null && ctxt.isPrototypeMode()) { tfp.removeProtoTypeFiles(null); } // Make sure these object which are only used during the // generation and compilation of the JSP page get // dereferenced so that they can be GC'd and reduce the // memory footprint. tfp = null; errDispatcher = null; pageInfo = null; // Only get rid of the pageNodes if in production. // In development mode, they are used for detailed // error messages. // http://issues.apache.org/bugzilla/show_bug.cgi?id=37062 if (!this.options.getDevelopment()) { pageNodes = null; } if (ctxt.getWriter() != null) { ctxt.getWriter().close(); ctxt.setWriter(null); } }
4
shutdown 1
                  
// in java/org/apache/catalina/startup/Catalina.java
finally { // If JULI is used, shut JULI down *after* the server shuts down // so log messages aren't lost LogManager logManager = LogManager.getLogManager(); if (logManager instanceof ClassLoaderLogManager) { ((ClassLoaderLogManager) logManager).shutdown(); } }
6
toURL 1
                  
// in java/org/apache/catalina/startup/ContextConfig.java
finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } fragment.setURL(file.toURI().toURL()); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); }
30
trim 1
                  
// in java/org/apache/catalina/tribes/group/interceptors/OrderInterceptor.java
finally { msg.getMessage().trim(4); }
116
unlockAdd
1
                  
// in java/org/apache/catalina/tribes/transport/bio/util/FastQueue.java
finally { lock.unlockAdd(true); }
1
unlockRemove
1
                  
// in java/org/apache/catalina/tribes/transport/bio/util/FastQueue.java
finally { lock.unlockRemove(); }
1
updateStats
1
                  
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
finally { // FIXME this stats update are not cheap!! if(doStatistics()) { updateStats(totalstart,start); } }
1

Reference Table

This table concatenates the results of the previous tables.

Checked/Runtime Type Exception Thrown Thrown from Catch Declared Caught directly Caught
with Thrown
Caught
with Thrown Runtime
unknown (Lib) . 0 0 0 0 0 0
unknown (Lib) AbstractMethodError 0 0 0 1
            
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (AbstractMethodError ame) { // Almost certainly a pre Tomcat 7.0.17 compiled JSP using the old // version of the interface. Force a re-compile. return ALWAYS_OUTDATED_DEPENDENCIES; }
0 0
unknown (Lib) AccessControlException 0 0 0 6
            
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (AccessControlException ace) { // No permission to configure logging in context // Log and carry on ClassLoaderLogInfo info = classLoaderLoggers.get(ClassLoader.getSystemClassLoader()); if (info != null) { Logger log = info.loggers.get(""); if (log != null) { Permission perm = ace.getPermission(); if (perm instanceof FilePermission && perm.getActions().equals("read")) { log.warning("Reading " + perm.getName() + " is not permitted. See \"per context logging\" in the default catalina.policy file."); } else { log.warning("Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file."); log.warning("Original error was: " + ace.getMessage()); } } } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (AccessControlException e) { // Some policy files may restrict this, even for the core, // so this exception is ignored }
// in java/org/apache/catalina/core/StandardServer.java
catch (AccessControlException ace) { log.warn("StandardServer.accept security exception: " + ace.getMessage(), ace); continue; }
3
            
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
0
unknown (Lib) AccountExpiredException 0 0 0 1
            
// in java/org/apache/catalina/realm/JAASRealm.java
catch (AccountExpiredException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.accountExpired", username)); return (null); }
0 0
unknown (Lib) ArithmeticException 1 0 0 2
            
// in java/org/apache/el/parser/AstInteger.java
catch (ArithmeticException e1) { this.number = new BigInteger(this.image); }
// in java/org/apache/el/parser/AstFloatingPoint.java
catch (ArithmeticException e0) { this.number = new BigDecimal(this.image); }
0 0
unknown (Lib) ArrayIndexOutOfBoundsException 11
            
// in java/org/apache/coyote/ajp/AjpMessage.java
private void validatePos(int posToTest) { if (posToTest > len + 4) { // Trying to read data beyond the end of the AJP message throw new ArrayIndexOutOfBoundsException(sm.getString( "ajpMessage.invalidPos", Integer.valueOf(posToTest))); } }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public void setLength(int size) { if ( size > buf.length ) throw new ArrayIndexOutOfBoundsException("Size is larger than existing buffer."); bufSize = size; }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public void trim(int length) { if ( (bufSize - length) < 0 ) throw new ArrayIndexOutOfBoundsException("Can't trim more bytes than are available. length:"+bufSize+" trim:"+length); bufSize -= length; }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static byte[] createDataPackage(byte[] data, int doff, int dlength, byte[] buffer, int bufoff) { if ( (buffer.length-bufoff) > getDataPackageLength(dlength) ) { throw new ArrayIndexOutOfBoundsException("Unable to create data package, buffer is too small."); } System.arraycopy(START_DATA, 0, buffer, bufoff, START_DATA.length); toBytes(data.length,buffer, bufoff+START_DATA.length); System.arraycopy(data, doff, buffer, bufoff+START_DATA.length + 4, dlength); System.arraycopy(END_DATA, 0, buffer, bufoff+START_DATA.length + 4 + data.length, END_DATA.length); return buffer; }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static int firstIndexOf(byte[] src, int srcOff, byte[] find){ int result = -1; if (find.length > src.length) return result; if (find.length == 0 || src.length == 0) return result; if (srcOff >= src.length ) throw new java.lang.ArrayIndexOutOfBoundsException(); boolean found = false; int srclen = src.length; int findlen = find.length; byte first = find[0]; int pos = srcOff; while (!found) { //find the first byte while (pos < srclen){ if (first == src[pos]) break; pos++; } if (pos >= srclen) return -1; //we found the first character //match the rest of the bytes - they have to match if ( (srclen - pos) < findlen) return -1; //assume it does exist found = true; for (int i = 1; ( (i < findlen) && found); i++) found = found && (find[i] == src[pos + i]
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
public static MemberImpl getMember(byte[] data, int offset, int length, MemberImpl member) { //package looks like //start package TRIBES_MBR_BEGIN.length //package length - 4 bytes //alive - 8 bytes //port - 4 bytes //secure port - 4 bytes //udp port - 4 bytes //host length - 1 byte //host - hl bytes //clen - 4 bytes //command - clen bytes //dlen - 4 bytes //domain - dlen bytes //uniqueId - 16 bytes //payload length - 4 bytes //payload plen bytes //end package TRIBES_MBR_END.length int pos = offset; if (XByteBuffer.firstIndexOf(data,offset,TRIBES_MBR_BEGIN)!=pos) { throw new IllegalArgumentException("Invalid package, should start with:"+org.apache.catalina.tribes.util.Arrays.toString(TRIBES_MBR_BEGIN)); } if ( length < (TRIBES_MBR_BEGIN.length+4) ) { throw new ArrayIndexOutOfBoundsException("Member package to small to validate."); } pos += TRIBES_MBR_BEGIN.length; int bodylength = XByteBuffer.toInt(data,pos); pos += 4; if ( length < (bodylength+4+TRIBES_MBR_BEGIN.length+TRIBES_MBR_END.length) ) { throw new ArrayIndexOutOfBoundsException("Not enough bytes in member package."); } int endpos = pos+bodylength; if (XByteBuffer.firstIndexOf(data,endpos,TRIBES_MBR_END)!=endpos) { throw new IllegalArgumentException("Invalid package, should end with:"+org.apache.catalina.tribes.util.Arrays.toString(TRIBES_MBR_END)); } byte[] alived = new byte[8]; System.arraycopy(data, pos, alived, 0, 8); pos += 8; byte[] portd = new byte[4]; System.arraycopy(data, pos, portd, 0, 4); pos += 4; byte[] sportd = new byte[4]; System.arraycopy(data, pos, sportd, 0, 4); pos += 4; byte[] uportd = new byte[4]; System.arraycopy(data, pos, uportd, 0, 4); pos += 4; byte hl = data[pos++]; byte[] addr = new byte[hl]; System.arraycopy(data, pos, addr, 0, hl); pos += hl; int cl = XByteBuffer.toInt(data, pos); pos += 4; byte[] command = new byte[cl]; System.arraycopy(data, pos, command, 0, command.length); pos += command.length; int dl = XByteBuffer.toInt(data, pos); pos += 4; byte[] domain = new byte[dl]; System.arraycopy(data, pos, domain, 0, domain.length); pos += domain.length; byte[] uniqueId = new byte[16]; System.arraycopy(data, pos, uniqueId, 0, 16); pos += 16; int pl = XByteBuffer.toInt(data, pos); pos += 4; byte[] payload = new byte[pl]; System.arraycopy(data, pos, payload, 0, payload.length); pos += payload.length; member.setHost(addr); member.setPort(XByteBuffer.toInt(portd, 0)); member.setSecurePort(XByteBuffer.toInt(sportd, 0)); member.setUdpPort(XByteBuffer.toInt(uportd, 0)); member.setMemberAliveTime(XByteBuffer.toLong(alived, 0)); member.setUniqueId(uniqueId); member.payload = payload; member.domain = domain; member.command = command; member.dataPkg = new byte[length]; System.arraycopy(data, offset, member.dataPkg, 0, length); return member; }
// in java/org/apache/catalina/tribes/util/UUIDGenerator.java
public static byte[] randomUUID(boolean secure, byte[] into, int offset) { if ( (offset+UUID_LENGTH)>into.length ) throw new ArrayIndexOutOfBoundsException("Unable to fit "+UUID_LENGTH+" bytes into the array. length:"+into.length+" required length:"+(offset+UUID_LENGTH)); Random r = (secure&&(secrand!=null))?secrand:rand; nextBytes(into,offset,UUID_LENGTH,r); into[6+offset] &= 0x0F; into[6+offset] |= (UUID_VERSION << 4); into[8+offset] &= 0x3F; //0011 1111 into[8+offset] |= 0x80; //1000 0000 return into; }
// in java/org/apache/catalina/tribes/util/Arrays.java
public static boolean contains(byte[] source, int srcoffset, byte[] key, int keyoffset, int length) { if ( srcoffset < 0 || srcoffset >= source.length) throw new ArrayIndexOutOfBoundsException("srcoffset is out of bounds."); if ( keyoffset < 0 || keyoffset >= key.length) throw new ArrayIndexOutOfBoundsException("keyoffset is out of bounds."); if ( length > (key.length-keyoffset) ) throw new ArrayIndexOutOfBoundsException("not enough data elements in the key, length is out of bounds."); //we don't have enough data to validate it if ( length > (source.length-srcoffset) ) return false; boolean match = true; int pos = keyoffset; for ( int i=srcoffset; match && i<length; i++ ) { match = (source[i] == key[pos++]); } return match; }
0 0 2
            
// in java/org/apache/jasper/compiler/Node.java
catch (ArrayIndexOutOfBoundsException e) { }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( ArrayIndexOutOfBoundsException ax ) { //we can ignore this, as it means we have an invalid package //but we will log it to debug if ( log.isDebugEnabled() ) log.debug("Invalid member mcast package.",ax); }
0 0
unknown (Lib) AttributeNotFoundException 6
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
Method getGetter(String aname, BaseModelMBean mbean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); // Look up the actual operation to be used if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname + " for " + resource); String getMethod = attrInfo.getGetMethod(); if (getMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " get method name"); Object object = null; NoSuchMethodException exception = null; try { object = mbean; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find getter method " + getMethod); return m; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getSetter(String aname, BaseModelMBean bean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname); // Look up the actual operation to be used String setMethod = attrInfo.getSetMethod(); if (setMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " set method name"); String argType=attrInfo.getType(); Class<?> signature[] = new Class[] { BaseModelMBean.getAttributeClass( argType ) }; Object object = null; NoSuchMethodException exception = null; try { object = bean; m = object.getClass().getMethod(setMethod, signature); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(setMethod, signature); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find setter method " + setMethod + " " + resource); return m; }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("auth".equals(name)) { return (cr.getAuth()); } else if ("description".equals(name)) { return (cr.getDescription()); } else if ("name".equals(name)) { return (cr.getName()); } else if ("scope".equals(name)) { return (cr.getScope()); } else if ("type".equals(name)) { return (cr.getType()); } else { value = (String) cr.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink cl = null; try { cl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("global".equals(name)) { return (cl.getGlobal()); } else if ("description".equals(name)) { return (cl.getDescription()); } else if ("name".equals(name)) { return (cl.getName()); } else if ("type".equals(name)) { return (cl.getType()); } else { value = (String) cl.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
0 11
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
Method getGetter(String aname, BaseModelMBean mbean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); // Look up the actual operation to be used if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname + " for " + resource); String getMethod = attrInfo.getGetMethod(); if (getMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " get method name"); Object object = null; NoSuchMethodException exception = null; try { object = mbean; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find getter method " + getMethod); return m; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getSetter(String aname, BaseModelMBean bean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname); // Look up the actual operation to be used String setMethod = attrInfo.getSetMethod(); if (setMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " set method name"); String argType=attrInfo.getType(); Class<?> signature[] = new Class[] { BaseModelMBean.getAttributeClass( argType ) }; Object object = null; NoSuchMethodException exception = null; try { object = bean; m = object.getClass().getMethod(setMethod, signature); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(setMethod, signature); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find setter method " + setMethod + " " + resource); return m; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).getAttribute(name); } Method m=managedBean.getGetter(name, this, resource); Object result = null; try { Class<?> declaring = m.getDeclaringClass(); // workaround for catalina weird mbeans - the declaring class is BaseModelMBean. // but this is the catalina class. if( declaring.isAssignableFrom(this.getClass()) ) { result = m.invoke(this, NO_ARGS_PARAM ); } else { result = m.invoke(resource, NO_ARGS_PARAM ); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if( log.isDebugEnabled() ) log.debug("Setting attribute " + this + " " + attribute ); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { try { ((DynamicMBean)resource).setAttribute(attribute); } catch (InvalidAttributeValueException e) { throw new MBeanException(e); } return; } // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); Object oldValue=null; //if( getAttMap.get(name) != null ) // oldValue=getAttribute( name ); Method m=managedBean.getSetter(name,this,resource); try { if( m.getDeclaringClass().isAssignableFrom( this.getClass()) ) { m.invoke(this, new Object[] { value }); } else { m.invoke(resource, new Object[] { value }); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } try { sendAttributeChangeNotification(new Attribute( name, oldValue), attribute); } catch(Exception ex) { log.error("Error sending notification " + name, ex); } //attributes.put( name, value ); // if( source != null ) { // // this mbean is associated with a source - maybe we want to persist // source.updateField(oname, name, value); // } }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); Object result = null; try { Connector connector = (Connector) getManagedResource(); result = IntrospectionUtils.getProperty(connector, name); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return result; }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); try { Connector connector = (Connector) getManagedResource(); IntrospectionUtils.setProperty(connector, name, String.valueOf(value)); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("auth".equals(name)) { return (cr.getAuth()); } else if ("description".equals(name)) { return (cr.getDescription()); } else if ("name".equals(name)) { return (cr.getName()); } else if ("scope".equals(name)) { return (cr.getScope()); } else if ("type".equals(name)) { return (cr.getType()); } else { value = (String) cr.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("auth".equals(name)) { cr.setAuth((String)value); } else if ("description".equals(name)) { cr.setDescription((String)value); } else if ("name".equals(name)) { cr.setName((String)value); } else if ("scope".equals(name)) { cr.setScope((String)value); } else if ("type".equals(name)) { cr.setType((String)value); } else { cr.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = cr.getNamingResources(); nr.removeResource(cr.getName()); nr.addResource(cr); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink cl = null; try { cl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("global".equals(name)) { return (cl.getGlobal()); } else if ("description".equals(name)) { return (cl.getDescription()); } else if ("name".equals(name)) { return (cl.getName()); } else if ("type".equals(name)) { return (cl.getType()); } else { value = (String) cl.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink crl = null; try { crl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("global".equals(name)) { crl.setGlobal((String)value); } else if ("description".equals(name)) { crl.setDescription((String)value); } else if ("name".equals(name)) { crl.setName((String)value); } else if ("type".equals(name)) { crl.setType((String)value); } else { crl.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = crl.getNamingResources(); nr.removeResourceLink(crl.getName()); nr.addResourceLink(crl); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { super.setAttribute(attribute); ContextEnvironment ce = null; try { ce = (ContextEnvironment) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = ce.getNamingResources(); nr.removeEnvironment(ce.getName()); nr.addEnvironment(ce); }
0 0 0
unknown (Lib) AuthenticationException 0 0 0 1
            
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (AuthenticationException e) { if (containerLog.isTraceEnabled()) { containerLog.trace(" bind attempt failed"); } }
0 0
unknown (Lib) BindException 0 0 0 2
            
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (BindException orig) { String msg; if (getAddress() == null) msg = orig.getMessage() + " <null>:" + getPort(); else msg = orig.getMessage() + " " + getAddress().toString() + ":" + getPort(); BindException be = new BindException(msg); be.initCause(orig); throw be; }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (BindException e) { /* * On some platforms (e.g. Linux) it is not possible to bind * to the multicast address. In this case only bind to the * port. */ log.info("Binding to multicast address, failed. Binding to port only."); socket = new MulticastSocket(port); }
1
            
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (BindException orig) { String msg; if (getAddress() == null) msg = orig.getMessage() + " <null>:" + getPort(); else msg = orig.getMessage() + " " + getAddress().toString() + ":" + getPort(); BindException be = new BindException(msg); be.initCause(orig); throw be; }
0
unknown (Lib) BuildException 56
            
// in java/org/apache/tomcat/buildutil/CheckEol.java
Override public void execute() throws BuildException { Mode mode = null; if ("\n".equals(eoln)) { mode = Mode.LF; } else if ("\r\n".equals(eoln)) { mode = Mode.CRLF; } else { log("Line ends check skipped, because OS line ends setting is neither LF nor CRLF.", Project.MSG_VERBOSE); return; } int count = 0; List<CheckFailure> errors = new ArrayList<CheckFailure>(); // Step through each file and check. for (FileSet fs : filesets) { DirectoryScanner ds = fs.getDirectoryScanner(getProject()); File basedir = ds.getBasedir(); String[] files = ds.getIncludedFiles(); if (files.length > 0) { log("Checking line ends in " + files.length + " file(s)"); for (int i = 0; i < files.length; i++) { File file = new File(basedir, files[i]); log("Checking file '" + file + "' for correct line ends", Project.MSG_DEBUG); try { check(file, errors, mode); } catch (IOException e) { throw new BuildException("Could not check file '" + file.getAbsolutePath() + "'", e); } count++; } } } if (count > 0) { log("Done line ends check in " + count + " file(s), " + errors.size() + " error(s) found."); } if (errors.size() > 0) { String message = "The following files have wrong line ends: " + errors; // We need to explicitly write the message to the log, because // long BuildException messages may be trimmed. E.g. I observed // this problem with Eclipse IDE 3.7. log(message, Project.MSG_ERR); throw new BuildException(message); } }
// in java/org/apache/tomcat/buildutil/Txt2Html.java
Override public void execute() throws BuildException { int count = 0; // Step through each file and convert. Iterator<FileSet> iter = filesets.iterator(); while( iter.hasNext() ) { FileSet fs = iter.next(); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); File basedir = ds.getBasedir(); String[] files = ds.getIncludedFiles(); for( int i = 0; i < files.length; i++ ) { File from = new File( basedir, files[i] ); File to = new File( todir, files[i] + ".html" ); if( !to.exists() || (from.lastModified() > to.lastModified()) ) { log( "Converting file '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath(), Project.MSG_VERBOSE ); try { convert( from, to ); } catch( IOException e ) { throw new BuildException( "Could not convert '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath() + "'", e ); } count++; } } if( count > 0 ) { log( "Converted " + count + " file" + (count > 1 ? "s" : "") + " to " + todir.getAbsolutePath() ); } } }
// in java/org/apache/catalina/ant/JMXSetTask.java
Override public void execute() throws BuildException { super.execute(); if (bean == null || attribute == null || value == null) { throw new BuildException ("Must specify 'bean', 'attribute' and 'value' attributes"); } log("Setting attribute " + attribute + " in bean " + bean + " to " + value); try { execute("/jmxproxy/?set=" + URLEncoder.encode(bean, getCharset()) + "&att=" + URLEncoder.encode(attribute, getCharset()) + "&val=" + URLEncoder.encode(value, getCharset())); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } }
// in java/org/apache/catalina/ant/ResourcesTask.java
Override public void execute() throws BuildException { super.execute(); if (type != null) { try { execute("/resources?type=" + URLEncoder.encode(type, getCharset())); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } } else { execute("/resources"); } }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
Override public void execute() throws BuildException { if ((username == null) || (password == null) || (url == null)) { throw new BuildException ("Must specify all of 'username', 'password', and 'url'"); } }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
public void execute(String command, InputStream istream, String contentType, int contentLength) throws BuildException { URLConnection conn = null; InputStreamReader reader = null; try { // Create a connection for this command conn = (new URL(url + command)).openConnection(); HttpURLConnection hconn = (HttpURLConnection) conn; // Set up standard connection characteristics hconn.setAllowUserInteraction(false); hconn.setDoInput(true); hconn.setUseCaches(false); if (istream != null) { hconn.setDoOutput(true); hconn.setRequestMethod("PUT"); if (contentType != null) { hconn.setRequestProperty("Content-Type", contentType); } if (contentLength >= 0) { hconn.setRequestProperty("Content-Length", "" + contentLength); hconn.setFixedLengthStreamingMode(contentLength); } } else { hconn.setDoOutput(false); hconn.setRequestMethod("GET"); } hconn.setRequestProperty("User-Agent", "Catalina-Ant-Task/1.0"); // Set up an authorization header with our credentials String input = username + ":" + password; String output = Base64.encode(input.getBytes(B2CConverter.ISO_8859_1)); hconn.setRequestProperty("Authorization", "Basic " + output); // Establish the connection with the server hconn.connect(); // Send the request data (if any) if (istream != null) { BufferedOutputStream ostream = new BufferedOutputStream(hconn.getOutputStream(), 1024); byte buffer[] = new byte[1024]; while (true) { int n = istream.read(buffer); if (n < 0) { break; } ostream.write(buffer, 0, n); } ostream.flush(); ostream.close(); istream.close(); } // Process the response message reader = new InputStreamReader(hconn.getInputStream(), CHARSET); StringBuilder buff = new StringBuilder(); String error = null; int msgPriority = Project.MSG_INFO; boolean first = true; while (true) { int ch = reader.read(); if (ch < 0) { break; } else if ((ch == '\r') || (ch == '\n')) { // in Win \r\n would cause handleOutput() to be called // twice, the second time with an empty string, // producing blank lines if (buff.length() > 0) { String line = buff.toString(); buff.setLength(0); if (first) { if (!line.startsWith("OK -")) { error = line; msgPriority = Project.MSG_ERR; } first = false; } handleOutput(line, msgPriority); } } else { buff.append((char) ch); } } if (buff.length() > 0) { handleOutput(buff.toString(), msgPriority); } if (error != null && isFailOnError()) { // exception should be thrown only if failOnError == true // or error line will be logged twice throw new BuildException(error); } } catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } } finally { closeRedirector(); if (reader != null) { try { reader.close(); } catch (IOException ioe) { // Ignore } reader = null; } if (istream != null) { try { istream.close(); } catch (IOException ioe) { // Ignore } } } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
Override public void execute() throws BuildException { if (testIfCondition() && testUnlessCondition()) { try { String error = null; MBeanServerConnection jmxServerConnection = getJMXConnection(); error = jmxExecute(jmxServerConnection); if (error != null && isFailOnError()) { // exception should be thrown only if failOnError == true // or error line will be logged twice throw new BuildException(error); } } catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } } finally { closeRedirector(); } } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if ((jmxServerConnection == null)) { throw new BuildException("Must open a connection!"); } else if (isEcho()) { handleOutput("JMX Connection ref=" + ref + " is open!"); } return null; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorSetTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((attribute == null || value == null)) { throw new BuildException( "Must specify a 'attribute' and 'value' for set"); } return jmxSet(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorEqualsCondition.java
Override public boolean eval() { if (value == null) { throw new BuildException("value attribute is not set"); } if ((name == null || attribute == null)) { throw new BuildException( "Must specify a 'attribute', name for equals condition"); } //FIXME check url or host/parameter String jmxValue = accessJMXValue(); if(jmxValue != null) return jmxValue.equals(value); return false; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorGetTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((attribute == null)) { throw new BuildException( "Must specify a 'attribute' for get"); } return jmxGet(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorCondition.java
Override public boolean eval() { if (operation == null) { throw new BuildException("operation attribute is not set"); } if (value == null) { throw new BuildException("value attribute is not set"); } if ((name == null || attribute == null)) { throw new BuildException( "Must specify a 'attribute', name for equals condition"); } if (testIfCondition() && testUnlessCondition()) { String jmxValue = accessJMXValue(); if (jmxValue != null) { String op = getOperation(); if ("==".equals(op)) { return jmxValue.equals(value); } else if ("!=".equals(op)) { return !jmxValue.equals(value); } else { if ("long".equals(type)) { long jvalue = Long.parseLong(jmxValue); long lvalue = Long.parseLong(value); if (">".equals(op)) { return jvalue > lvalue; } else if (">=".equals(op)) { return jvalue >= lvalue; } else if ("<".equals(op)) { return jvalue < lvalue; } else if ("<=".equals(op)) { return jvalue <= lvalue; } } else if ("double".equals(type)) { double jvalue = Double.parseDouble(jmxValue); double dvalue = Double.parseDouble(value); if (">".equals(op)) { return jvalue > dvalue; } else if (">=".equals(op)) { return jvalue >= dvalue; } else if ("<".equals(op)) { return jvalue < dvalue; } else if ("<=".equals(op)) { return jvalue <= dvalue; } } } } return false; } return true; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } return jmxQuery(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorUnregisterTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } return jmxUuregister(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorCreateTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((className == null)) { throw new BuildException( "Must specify a 'className' for get"); } return jmxCreate(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorInvokeTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((operation == null)) { throw new BuildException( "Must specify a 'operation' for call"); } return jmxInvoke(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/JMXGetTask.java
Override public void execute() throws BuildException { super.execute(); if (bean == null || attribute == null) { throw new BuildException ("Must specify 'bean' and 'attribute' attributes"); } log("Getting attribute " + attribute + " in bean " + bean ); try { execute("/jmxproxy/?get=" + URLEncoder.encode(bean, getCharset()) + "&att=" + URLEncoder.encode(attribute, getCharset())); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } }
// in java/org/apache/catalina/ant/ValidatorTask.java
Override public void execute() throws BuildException { if (path == null) { throw new BuildException("Must specify 'path'"); } File file = new File(path, Constants.ApplicationWebXml); if ((!file.exists()) || (!file.canRead())) { throw new BuildException("Cannot find web.xml"); } // Commons-logging likes having the context classloader set ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader (ValidatorTask.class.getClassLoader()); Digester digester = DigesterFactory.newDigester(true, true, null); try { file = file.getCanonicalFile(); InputStream stream = new BufferedInputStream(new FileInputStream(file)); InputSource is = new InputSource(file.toURI().toURL().toExternalForm()); is.setByteStream(stream); digester.parse(is); handleOutput("web.xml validated"); } catch (Exception e) { if (isFailOnError()) { throw new BuildException("Validation failure", e); } else { handleErrorOutput("Validation failure: " + e); } } finally { Thread.currentThread().setContextClassLoader(oldCL); closeRedirector(); } }
// in java/org/apache/catalina/ant/AbstractCatalinaCommandTask.java
public StringBuilder createQueryString(String command) throws BuildException { StringBuilder buffer = new StringBuilder(); try { buffer.append(command); if (path == null) { throw new BuildException("Must specify 'path' attribute"); } else { buffer.append("?path="); buffer.append(URLEncoder.encode(this.path, getCharset())); if (this.version != null) { buffer.append("&version="); buffer.append(URLEncoder.encode(this.version, getCharset())); } } } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } return buffer; }
// in java/org/apache/catalina/ant/JKStatusUpdateTask.java
private StringBuilder createLink() { // Building URL StringBuilder sb = new StringBuilder(); try { sb.append("?cmd=update&mime=txt"); sb.append("&w="); sb.append(URLEncoder.encode(worker, getCharset())); if (isLBMode) { //http://localhost/status?cmd=update&mime=txt&w=lb&lf=false&ls=true if ((lbRetries != null)) { // > 0 sb.append("&lr="); sb.append(lbRetries); } if ((lbRecovertime != null)) { // > 59 sb.append("&lt="); sb.append(lbRecovertime); } if ((lbStickySession != null)) { sb.append("&ls="); sb.append(lbStickySession); } if ((lbForceSession != null)) { sb.append("&lf="); sb.append(lbForceSession); } } else { //http://localhost/status?cmd=update&mime=txt&w=node1&l=lb&wf=1&wd=false&ws=false if ((workerLb != null)) { // must be configured sb.append("&l="); sb.append(URLEncoder.encode(workerLb, getCharset())); } if ((workerLoadFactor != null)) { // >= 1 sb.append("&wf="); sb.append(workerLoadFactor); } if ((workerDisabled != null)) { sb.append("&wd="); sb.append(workerDisabled); } if ((workerStopped != null)) { sb.append("&ws="); sb.append(workerStopped); } if ((workerRedirect != null)) { // other worker conrecte lb's sb.append("&wr="); } if ((workerClusterDomain != null)) { sb.append("&wc="); sb.append(URLEncoder.encode(workerClusterDomain, getCharset())); } } } catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); } return sb; }
// in java/org/apache/catalina/ant/JKStatusUpdateTask.java
protected void checkParameter() { if (worker == null) { throw new BuildException("Must specify 'worker' attribute"); } if (workerType == null) { throw new BuildException("Must specify 'workerType' attribute"); } if ("lb".equals(workerType)) { if (lbRecovertime == null && lbRetries == null) { throw new BuildException( "Must specify at a lb worker either 'lbRecovertime' or" + "'lbRetries' attribute"); } if (lbStickySession == null || lbForceSession == null) { throw new BuildException("Must specify at a lb worker either" + "'lbStickySession' and 'lbForceSession' attribute"); } if (null != lbRecovertime && 60 < lbRecovertime.intValue()) { throw new BuildException( "The 'lbRecovertime' must be greater than 59"); } if (null != lbRetries && 1 < lbRetries.intValue()) { throw new BuildException( "The 'lbRetries' must be greater than 1"); } isLBMode = true; } else if ("worker".equals(workerType)) { if (workerDisabled == null) { throw new BuildException( "Must specify at a node worker 'workerDisabled' attribute"); } if (workerStopped == null) { throw new BuildException( "Must specify at a node worker 'workerStopped' attribute"); } if (workerLoadFactor == null ) { throw new BuildException( "Must specify at a node worker 'workerLoadFactor' attribute"); } if (workerClusterDomain == null) { throw new BuildException( "Must specify at a node worker 'workerClusterDomain' attribute"); } if (workerRedirect == null) { throw new BuildException( "Must specify at a node worker 'workerRedirect' attribute"); } if (workerLb == null) { throw new BuildException("Must specify 'workerLb' attribute"); } if (workerLoadFactor.intValue() < 1) { throw new BuildException( "The 'workerLoadFactor' must be greater or equal 1"); } isLBMode = false; } else { throw new BuildException( "Only 'lb' and 'worker' supported as workerType attribute"); } }
// in java/org/apache/catalina/ant/DeployTask.java
Override public void execute() throws BuildException { super.execute(); if (path == null) { throw new BuildException ("Must specify 'path' attribute"); } if ((war == null) && (localWar == null) && (config == null) && (tag == null)) { throw new BuildException ("Must specify either 'war', 'localWar', 'config', or 'tag' attribute"); } // Building an input stream on the WAR to upload, if any BufferedInputStream stream = null; String contentType = null; int contentLength = -1; if (war != null) { if (war.startsWith("file:")) { try { URL url = new URL(war); URLConnection conn = url.openConnection(); contentLength = conn.getContentLength(); stream = new BufferedInputStream (conn.getInputStream(), 1024); } catch (IOException e) { throw new BuildException(e); } } else { try { FileInputStream fsInput = new FileInputStream(war); long size = fsInput.getChannel().size(); if (size > Integer.MAX_VALUE) throw new UnsupportedOperationException( "DeployTask does not support WAR files " + "greater than 2 Gb"); contentLength = (int) size; stream = new BufferedInputStream(fsInput, 1024); } catch (IOException e) { throw new BuildException(e); } } contentType = "application/octet-stream"; } // Building URL StringBuilder sb = new StringBuilder("/deploy?path="); try { sb.append(URLEncoder.encode(this.path, getCharset())); if ((war == null) && (config != null)) { sb.append("&config="); sb.append(URLEncoder.encode(config, getCharset())); } if ((war == null) && (localWar != null)) { sb.append("&war="); sb.append(URLEncoder.encode(localWar, getCharset())); } if (update) { sb.append("&update=true"); } if (tag != null) { sb.append("&tag="); sb.append(URLEncoder.encode(tag, getCharset())); } } catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); } execute(sb.toString(), stream, contentType, contentLength); }
// in java/org/apache/catalina/ant/BaseRedirectorHelperTask.java
public void addConfiguredRedirector(RedirectorElement redirectorElement) { if (this.redirectorElement != null) { throw new BuildException("Cannot have > 1 nested <redirector>s"); } else { this.redirectorElement = redirectorElement; } }
// in java/org/apache/catalina/ant/JMXQueryTask.java
Override public void execute() throws BuildException { super.execute(); String queryString; if (query == null) { queryString = ""; } else { try { queryString = "?qry=" + URLEncoder.encode(query, getCharset()); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } } log("Query string is " + queryString); execute ("/jmxproxy/" + queryString); }
14
            
// in java/org/apache/tomcat/buildutil/CheckEol.java
catch (IOException e) { throw new BuildException("Could not check file '" + file.getAbsolutePath() + "'", e); }
// in java/org/apache/tomcat/buildutil/Txt2Html.java
catch( IOException e ) { throw new BuildException( "Could not convert '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath() + "'", e ); }
// in java/org/apache/catalina/ant/JMXSetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/ResourcesTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/JMXGetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/ValidatorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException("Validation failure", e); } else { handleErrorOutput("Validation failure: " + e); } }
// in java/org/apache/catalina/ant/AbstractCatalinaCommandTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JKStatusUpdateTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (IOException e) { throw new BuildException(e); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (IOException e) { throw new BuildException(e); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JMXQueryTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
22
            
// in java/org/apache/tomcat/buildutil/CheckEol.java
Override public void execute() throws BuildException { Mode mode = null; if ("\n".equals(eoln)) { mode = Mode.LF; } else if ("\r\n".equals(eoln)) { mode = Mode.CRLF; } else { log("Line ends check skipped, because OS line ends setting is neither LF nor CRLF.", Project.MSG_VERBOSE); return; } int count = 0; List<CheckFailure> errors = new ArrayList<CheckFailure>(); // Step through each file and check. for (FileSet fs : filesets) { DirectoryScanner ds = fs.getDirectoryScanner(getProject()); File basedir = ds.getBasedir(); String[] files = ds.getIncludedFiles(); if (files.length > 0) { log("Checking line ends in " + files.length + " file(s)"); for (int i = 0; i < files.length; i++) { File file = new File(basedir, files[i]); log("Checking file '" + file + "' for correct line ends", Project.MSG_DEBUG); try { check(file, errors, mode); } catch (IOException e) { throw new BuildException("Could not check file '" + file.getAbsolutePath() + "'", e); } count++; } } } if (count > 0) { log("Done line ends check in " + count + " file(s), " + errors.size() + " error(s) found."); } if (errors.size() > 0) { String message = "The following files have wrong line ends: " + errors; // We need to explicitly write the message to the log, because // long BuildException messages may be trimmed. E.g. I observed // this problem with Eclipse IDE 3.7. log(message, Project.MSG_ERR); throw new BuildException(message); } }
// in java/org/apache/tomcat/buildutil/Txt2Html.java
Override public void execute() throws BuildException { int count = 0; // Step through each file and convert. Iterator<FileSet> iter = filesets.iterator(); while( iter.hasNext() ) { FileSet fs = iter.next(); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); File basedir = ds.getBasedir(); String[] files = ds.getIncludedFiles(); for( int i = 0; i < files.length; i++ ) { File from = new File( basedir, files[i] ); File to = new File( todir, files[i] + ".html" ); if( !to.exists() || (from.lastModified() > to.lastModified()) ) { log( "Converting file '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath(), Project.MSG_VERBOSE ); try { convert( from, to ); } catch( IOException e ) { throw new BuildException( "Could not convert '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath() + "'", e ); } count++; } } if( count > 0 ) { log( "Converted " + count + " file" + (count > 1 ? "s" : "") + " to " + todir.getAbsolutePath() ); } } }
// in java/org/apache/catalina/ant/JMXSetTask.java
Override public void execute() throws BuildException { super.execute(); if (bean == null || attribute == null || value == null) { throw new BuildException ("Must specify 'bean', 'attribute' and 'value' attributes"); } log("Setting attribute " + attribute + " in bean " + bean + " to " + value); try { execute("/jmxproxy/?set=" + URLEncoder.encode(bean, getCharset()) + "&att=" + URLEncoder.encode(attribute, getCharset()) + "&val=" + URLEncoder.encode(value, getCharset())); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } }
// in java/org/apache/catalina/ant/StartTask.java
Override public void execute() throws BuildException { super.execute(); execute(createQueryString("/start").toString()); }
// in java/org/apache/catalina/ant/ResourcesTask.java
Override public void execute() throws BuildException { super.execute(); if (type != null) { try { execute("/resources?type=" + URLEncoder.encode(type, getCharset())); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } } else { execute("/resources"); } }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
Override public void execute() throws BuildException { if ((username == null) || (password == null) || (url == null)) { throw new BuildException ("Must specify all of 'username', 'password', and 'url'"); } }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
public void execute(String command) throws BuildException { execute(command, null, null, -1); }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
public void execute(String command, InputStream istream, String contentType, int contentLength) throws BuildException { URLConnection conn = null; InputStreamReader reader = null; try { // Create a connection for this command conn = (new URL(url + command)).openConnection(); HttpURLConnection hconn = (HttpURLConnection) conn; // Set up standard connection characteristics hconn.setAllowUserInteraction(false); hconn.setDoInput(true); hconn.setUseCaches(false); if (istream != null) { hconn.setDoOutput(true); hconn.setRequestMethod("PUT"); if (contentType != null) { hconn.setRequestProperty("Content-Type", contentType); } if (contentLength >= 0) { hconn.setRequestProperty("Content-Length", "" + contentLength); hconn.setFixedLengthStreamingMode(contentLength); } } else { hconn.setDoOutput(false); hconn.setRequestMethod("GET"); } hconn.setRequestProperty("User-Agent", "Catalina-Ant-Task/1.0"); // Set up an authorization header with our credentials String input = username + ":" + password; String output = Base64.encode(input.getBytes(B2CConverter.ISO_8859_1)); hconn.setRequestProperty("Authorization", "Basic " + output); // Establish the connection with the server hconn.connect(); // Send the request data (if any) if (istream != null) { BufferedOutputStream ostream = new BufferedOutputStream(hconn.getOutputStream(), 1024); byte buffer[] = new byte[1024]; while (true) { int n = istream.read(buffer); if (n < 0) { break; } ostream.write(buffer, 0, n); } ostream.flush(); ostream.close(); istream.close(); } // Process the response message reader = new InputStreamReader(hconn.getInputStream(), CHARSET); StringBuilder buff = new StringBuilder(); String error = null; int msgPriority = Project.MSG_INFO; boolean first = true; while (true) { int ch = reader.read(); if (ch < 0) { break; } else if ((ch == '\r') || (ch == '\n')) { // in Win \r\n would cause handleOutput() to be called // twice, the second time with an empty string, // producing blank lines if (buff.length() > 0) { String line = buff.toString(); buff.setLength(0); if (first) { if (!line.startsWith("OK -")) { error = line; msgPriority = Project.MSG_ERR; } first = false; } handleOutput(line, msgPriority); } } else { buff.append((char) ch); } } if (buff.length() > 0) { handleOutput(buff.toString(), msgPriority); } if (error != null && isFailOnError()) { // exception should be thrown only if failOnError == true // or error line will be logged twice throw new BuildException(error); } } catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } } finally { closeRedirector(); if (reader != null) { try { reader.close(); } catch (IOException ioe) { // Ignore } reader = null; } if (istream != null) { try { istream.close(); } catch (IOException ioe) { // Ignore } } } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
Override public void execute() throws BuildException { if (testIfCondition() && testUnlessCondition()) { try { String error = null; MBeanServerConnection jmxServerConnection = getJMXConnection(); error = jmxExecute(jmxServerConnection); if (error != null && isFailOnError()) { // exception should be thrown only if failOnError == true // or error line will be logged twice throw new BuildException(error); } } catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } } finally { closeRedirector(); } } }
// in java/org/apache/catalina/ant/JMXGetTask.java
Override public void execute() throws BuildException { super.execute(); if (bean == null || attribute == null) { throw new BuildException ("Must specify 'bean' and 'attribute' attributes"); } log("Getting attribute " + attribute + " in bean " + bean ); try { execute("/jmxproxy/?get=" + URLEncoder.encode(bean, getCharset()) + "&att=" + URLEncoder.encode(attribute, getCharset())); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } }
// in java/org/apache/catalina/ant/ValidatorTask.java
Override public void execute() throws BuildException { if (path == null) { throw new BuildException("Must specify 'path'"); } File file = new File(path, Constants.ApplicationWebXml); if ((!file.exists()) || (!file.canRead())) { throw new BuildException("Cannot find web.xml"); } // Commons-logging likes having the context classloader set ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader (ValidatorTask.class.getClassLoader()); Digester digester = DigesterFactory.newDigester(true, true, null); try { file = file.getCanonicalFile(); InputStream stream = new BufferedInputStream(new FileInputStream(file)); InputSource is = new InputSource(file.toURI().toURL().toExternalForm()); is.setByteStream(stream); digester.parse(is); handleOutput("web.xml validated"); } catch (Exception e) { if (isFailOnError()) { throw new BuildException("Validation failure", e); } else { handleErrorOutput("Validation failure: " + e); } } finally { Thread.currentThread().setContextClassLoader(oldCL); closeRedirector(); } }
// in java/org/apache/catalina/ant/AbstractCatalinaCommandTask.java
public StringBuilder createQueryString(String command) throws BuildException { StringBuilder buffer = new StringBuilder(); try { buffer.append(command); if (path == null) { throw new BuildException("Must specify 'path' attribute"); } else { buffer.append("?path="); buffer.append(URLEncoder.encode(this.path, getCharset())); if (this.version != null) { buffer.append("&version="); buffer.append(URLEncoder.encode(this.version, getCharset())); } } } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } return buffer; }
// in java/org/apache/catalina/ant/StopTask.java
Override public void execute() throws BuildException { super.execute(); execute(createQueryString("/stop").toString()); }
// in java/org/apache/catalina/ant/JKStatusUpdateTask.java
Override public void execute() throws BuildException { super.execute(); checkParameter(); StringBuilder sb = createLink(); execute(sb.toString(), null, null, -1); }
// in java/org/apache/catalina/ant/UndeployTask.java
Override public void execute() throws BuildException { super.execute(); execute(createQueryString("/undeploy").toString()); }
// in java/org/apache/catalina/ant/DeployTask.java
Override public void execute() throws BuildException { super.execute(); if (path == null) { throw new BuildException ("Must specify 'path' attribute"); } if ((war == null) && (localWar == null) && (config == null) && (tag == null)) { throw new BuildException ("Must specify either 'war', 'localWar', 'config', or 'tag' attribute"); } // Building an input stream on the WAR to upload, if any BufferedInputStream stream = null; String contentType = null; int contentLength = -1; if (war != null) { if (war.startsWith("file:")) { try { URL url = new URL(war); URLConnection conn = url.openConnection(); contentLength = conn.getContentLength(); stream = new BufferedInputStream (conn.getInputStream(), 1024); } catch (IOException e) { throw new BuildException(e); } } else { try { FileInputStream fsInput = new FileInputStream(war); long size = fsInput.getChannel().size(); if (size > Integer.MAX_VALUE) throw new UnsupportedOperationException( "DeployTask does not support WAR files " + "greater than 2 Gb"); contentLength = (int) size; stream = new BufferedInputStream(fsInput, 1024); } catch (IOException e) { throw new BuildException(e); } } contentType = "application/octet-stream"; } // Building URL StringBuilder sb = new StringBuilder("/deploy?path="); try { sb.append(URLEncoder.encode(this.path, getCharset())); if ((war == null) && (config != null)) { sb.append("&config="); sb.append(URLEncoder.encode(config, getCharset())); } if ((war == null) && (localWar != null)) { sb.append("&war="); sb.append(URLEncoder.encode(localWar, getCharset())); } if (update) { sb.append("&update=true"); } if (tag != null) { sb.append("&tag="); sb.append(URLEncoder.encode(tag, getCharset())); } } catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); } execute(sb.toString(), stream, contentType, contentLength); }
// in java/org/apache/catalina/ant/ServerinfoTask.java
Override public void execute() throws BuildException { super.execute(); execute("/serverinfo"); }
// in java/org/apache/catalina/ant/SessionsTask.java
Override public void execute() throws BuildException { super.execute(); execute(createQueryString("/sessions").toString()); }
// in java/org/apache/catalina/ant/ReloadTask.java
Override public void execute() throws BuildException { super.execute(); execute(createQueryString("/reload").toString()); }
// in java/org/apache/catalina/ant/ListTask.java
Override public void execute() throws BuildException { super.execute(); execute("/list"); }
// in java/org/apache/catalina/ant/FindLeaksTask.java
Override public void execute() throws BuildException { super.execute(); execute("/findleaks?statusLine=" + Boolean.toString(statusLine)); }
// in java/org/apache/catalina/ant/JMXQueryTask.java
Override public void execute() throws BuildException { super.execute(); String queryString; if (query == null) { queryString = ""; } else { try { queryString = "?qry=" + URLEncoder.encode(query, getCharset()); } catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); } } log("Query string is " + queryString); execute ("/jmxproxy/" + queryString); }
1
            
// in java/org/apache/jasper/compiler/AntCompiler.java
catch (BuildException e) { be = e; log.error(Localizer.getMessage("jsp.error.javac"), e); log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString()); }
0 0
unknown (Lib) CRLException 1
            
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected CertPathParameters getParameters(String algorithm, String crlf, KeyStore trustStore) throws Exception { CertPathParameters params = null; if("PKIX".equalsIgnoreCase(algorithm)) { PKIXBuilderParameters xparams = new PKIXBuilderParameters(trustStore, new X509CertSelector()); Collection<? extends CRL> crls = getCRLs(crlf); CertStoreParameters csp = new CollectionCertStoreParameters(crls); CertStore store = CertStore.getInstance("Collection", csp); xparams.addCertStore(store); xparams.setRevocationEnabled(true); String trustLength = endpoint.getTrustMaxCertLength(); if(trustLength != null) { try { xparams.setMaxPathLength(Integer.parseInt(trustLength)); } catch(Exception ex) { log.warn("Bad maxCertLength: "+trustLength); } } params = xparams; } else { throw new CRLException("CRLs not supported for type: "+algorithm); } return params; }
0 1
            
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected Collection<? extends CRL> getCRLs(String crlf) throws IOException, CRLException, CertificateException { File crlFile = new File(crlf); if( !crlFile.isAbsolute() ) { crlFile = new File( System.getProperty(Constants.CATALINA_BASE_PROP), crlf); } Collection<? extends CRL> crls = null; InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlFile); crls = cf.generateCRLs(is); } catch(IOException iex) { throw iex; } catch(CRLException crle) { throw crle; } catch(CertificateException ce) { throw ce; } finally { if(is != null) { try{ is.close(); } catch(Exception ex) { // Ignore } } } return crls; }
1
            
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(CRLException crle) { throw crle; }
1
            
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(CRLException crle) { throw crle; }
0
unknown (Lib) CancelledKeyException 0 0 0 13
            
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (CancelledKeyException cx) { cancel(sk,key,ops); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (CancelledKeyException cx) { if (sk!=null) { sk.cancel(); sk.attach(null); } }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch ( CancelledKeyException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); continue; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (CancelledKeyException ckx) { sk.cancel(); countDown(attachment.getReadLatch()); countDown(attachment.getWriteLatch()); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (CancelledKeyException ckx) { try { socket.getPoller().cancelledKey(key,SocketStatus.DISCONNECT); }catch (Exception ignore) {} }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( CancelledKeyException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( CancelledKeyException ckx ) { cancelledKey(sk, SocketStatus.ERROR); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( CancelledKeyException ckx ) { cancelledKey(key, SocketStatus.ERROR); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( CancelledKeyException ckx ) { handshake = -1; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch(CancelledKeyException cx) { socket.getPoller().cancelledKey(key,null); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (CancelledKeyException ckx ) { NioReceiver.cancelledKey(key); if ( log.isTraceEnabled() ) log.trace("CKX Cancelling key:"+key); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch ( CancelledKeyException ckx ) { cancelledKey(key); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (java.nio.channels.CancelledKeyException nx) { log.warn("Replication client disconnected, error when polling key. Ignoring client."); }
1
            
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( CancelledKeyException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; }
0
unknown (Lib) CertificateException 0 0 1
            
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected Collection<? extends CRL> getCRLs(String crlf) throws IOException, CRLException, CertificateException { File crlFile = new File(crlf); if( !crlFile.isAbsolute() ) { crlFile = new File( System.getProperty(Constants.CATALINA_BASE_PROP), crlf); } Collection<? extends CRL> crls = null; InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlFile); crls = cf.generateCRLs(is); } catch(IOException iex) { throw iex; } catch(CRLException crle) { throw crle; } catch(CertificateException ce) { throw ce; } finally { if(is != null) { try{ is.close(); } catch(Exception ex) { // Ignore } } } return crls; }
4
            
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (java.security.cert.CertificateException e) { getLog().error(sm.getString("ajpprocessor.certs.fail"), e); return; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (CertificateException ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(CertificateException ce) { throw ce; }
// in java/org/apache/catalina/valves/SSLValve.java
catch (java.security.cert.CertificateException e) { log.warn(sm.getString("sslValve.certError", strcerts), e); }
2
            
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (CertificateException ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(CertificateException ce) { throw ce; }
0
checked (Domain) ChannelException
public class ChannelException extends Exception {
    private static final long serialVersionUID = 1L;
    /**
     * Empty list to avoid reinstatiating lists
     */
    protected static final FaultyMember[] EMPTY_LIST = new FaultyMember[0];
    /*
     * Holds a list of faulty members
     */
    private ArrayList<FaultyMember> faultyMembers=null;

    /**
     * Constructor, creates a ChannelException
     * @see java.lang.Exception#Exception()
     */
    public ChannelException() {
        super();
    }

    /**
     * Constructor, creates a ChannelException with an error message
     * @see java.lang.Exception#Exception(String)
     */
    public ChannelException(String message) {
        super(message);
    }

    /**
     * Constructor, creates a ChannelException with an error message and a cause
     * @param message String
     * @param cause Throwable
     * @see java.lang.Exception#Exception(String,Throwable)
     */
    public ChannelException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Constructor, creates a ChannelException with a cause
     * @param cause Throwable
     * @see java.lang.Exception#Exception(Throwable)
     */
    public ChannelException(Throwable cause) {
        super(cause);
    }

    /**
     * Returns the message for this exception
     * @return String
     * @see java.lang.Exception#getMessage()
     */
    @Override
    public String getMessage() {
        StringBuilder buf = new StringBuilder(super.getMessage());
        if (faultyMembers==null || faultyMembers.size() == 0 ) {
            buf.append("; No faulty members identified.");
        } else {
            buf.append("; Faulty members:");
            for ( int i=0; i<faultyMembers.size(); i++ ) {
                FaultyMember mbr = faultyMembers.get(i);
                buf.append(mbr.getMember().getName());
                buf.append("; ");
            }
        }
        return buf.toString();
    }

    /**
     * Adds a faulty member, and the reason the member failed.
     * @param mbr Member
     * @param x Exception
     */
    public boolean addFaultyMember(Member mbr, Exception x ) {
        return addFaultyMember(new FaultyMember(mbr,x));
    }

    /**
     * Adds a list of faulty members
     * @param mbrs FaultyMember[]
     */
    public int addFaultyMember(FaultyMember[] mbrs) {
        int result = 0;
        for (int i=0; mbrs!=null && i<mbrs.length; i++ ) {
            if ( addFaultyMember(mbrs[i]) ) result++;
        }
        return result;
    }

    /**
     * Adds a faulty member
     * @param mbr FaultyMember
     */
    public boolean addFaultyMember(FaultyMember mbr) {
        if ( this.faultyMembers==null ) this.faultyMembers = new ArrayList<FaultyMember>();
        if ( !faultyMembers.contains(mbr) ) return faultyMembers.add(mbr);
        else return false;
    }

    /**
     * Returns an array of members that failed and the reason they failed.
     * @return FaultyMember[]
     */
    public FaultyMember[] getFaultyMembers() {
        if ( this.faultyMembers==null ) return EMPTY_LIST;
        return faultyMembers.toArray(new FaultyMember[faultyMembers.size()]);
    }

    /**
     *
     * <p>Title: FaultyMember class</p>
     *
     * <p>Description: Represent a failure to a specific member when a message was sent
     * to more than one member</p>
     *
     * @author Filip Hanik
     * @version 1.0
     */
    public static class FaultyMember {
        protected Exception cause;
        protected Member member;
        public FaultyMember(Member mbr, Exception x) {
            this.member = mbr;
            this.cause = x;
        }

        public Member getMember() {
            return member;
        }

        public Exception getCause() {
            return cause;
        }

        @Override
        public String toString() {
            return "FaultyMember:"+member.toString();
        }

        @Override
        public int hashCode() {
            return (member!=null)?member.hashCode():0;
        }

        @Override
        public boolean equals(Object o) {
            if (member==null || (!(o instanceof FaultyMember)) || (((FaultyMember)o).member==null)) return false;
            return member.equals(((FaultyMember)o).member);
        }
    }

}
16
            
// in java/org/apache/catalina/tribes/group/GroupChannel.java
Override public UniqueId send(Member[] destination, Serializable msg, int options, ErrorHandler handler) throws ChannelException { if ( msg == null ) throw new ChannelException("Cant send a NULL message"); XByteBuffer buffer = null; try { if ( destination == null || destination.length == 0) throw new ChannelException("No destination given"); ChannelData data = new ChannelData(true);//generates a unique Id data.setAddress(getLocalMember(false)); data.setTimestamp(System.currentTimeMillis()); byte[] b = null; if ( msg instanceof ByteMessage ){ b = ((ByteMessage)msg).getMessage(); options = options | SEND_OPTIONS_BYTE_MESSAGE; } else { b = XByteBuffer.serialize(msg); options = options & (~SEND_OPTIONS_BYTE_MESSAGE); } data.setOptions(options); //XByteBuffer buffer = new XByteBuffer(b.length+128,false); buffer = BufferPool.getBufferPool().getBuffer(b.length+128, false); buffer.append(b,0,b.length); data.setMessage(buffer); InterceptorPayload payload = null; if ( handler != null ) { payload = new InterceptorPayload(); payload.setErrorHandler(handler); } getFirstInterceptor().sendMessage(destination, data, payload); if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("GroupChannel - Sent msg:" + new UniqueId(data.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " to "+Arrays.toNameString(destination)); Logs.MESSAGES.trace("GroupChannel - Send Message:" + new UniqueId(data.getUniqueId()) + " is " +msg); } return new UniqueId(data.getUniqueId()); }catch ( Exception x ) { if ( x instanceof ChannelException ) throw (ChannelException)x; throw new ChannelException(x); } finally { if ( buffer != null ) BufferPool.getBufferPool().returnBuffer(buffer); } }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
protected synchronized void setupDefaultStack() throws ChannelException { if ( getFirstInterceptor() != null && ((getFirstInterceptor().getNext() instanceof ChannelCoordinator))) { ChannelInterceptor interceptor = null; Class<?> clazz = null; try { clazz = Class.forName("org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor", true,GroupChannel.class.getClassLoader()); clazz.newInstance(); } catch ( Throwable x ) { clazz = MessageDispatchInterceptor.class; }//catch try { interceptor = (ChannelInterceptor) clazz.newInstance(); } catch (Exception x) { throw new ChannelException("Unable to add MessageDispatchInterceptor to interceptor chain.",x); } this.addInterceptor(interceptor); } }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
protected void checkOptionFlags() throws ChannelException { StringBuilder conflicts = new StringBuilder(); ChannelInterceptor first = interceptors; while ( first != null ) { int flag = first.getOptionFlag(); if ( flag != 0 ) { ChannelInterceptor next = first.getNext(); while ( next != null ) { int nflag = next.getOptionFlag(); if (nflag!=0 && (((flag & nflag) == flag ) || ((flag & nflag) == nflag)) ) { conflicts.append("["); conflicts.append(first.getClass().getName()); conflicts.append(":"); conflicts.append(flag); conflicts.append(" == "); conflicts.append(next.getClass().getName()); conflicts.append(":"); conflicts.append(nflag); conflicts.append("] "); }//end if next = next.getNext(); }//while }//end if first = first.getNext(); }//while if ( conflicts.length() > 0 ) throw new ChannelException("Interceptor option flag conflict: "+conflicts.toString()); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
protected synchronized void internalStart(int svc) throws ChannelException { try { boolean valid = false; //make sure we don't pass down any flags that are unrelated to the bottom layer svc = svc & Channel.DEFAULT; if (startLevel == Channel.DEFAULT) return; //we have already started up all components if (svc == 0 ) return;//nothing to start if (svc == (svc & startLevel)) throw new ChannelException("Channel already started for level:"+svc); //must start the receiver first so that we can coordinate the port it //listens to with the local membership settings if ( Channel.SND_RX_SEQ==(svc & Channel.SND_RX_SEQ) ) { clusterReceiver.setMessageListener(this); clusterReceiver.start(); //synchronize, big time FIXME membershipService.setLocalMemberProperties(getClusterReceiver().getHost(), getClusterReceiver().getPort(), getClusterReceiver().getSecurePort(), getClusterReceiver().getUdpPort()); valid = true; } if ( Channel.SND_TX_SEQ==(svc & Channel.SND_TX_SEQ) ) { clusterSender.start(); valid = true; } if ( Channel.MBR_RX_SEQ==(svc & Channel.MBR_RX_SEQ) ) { membershipService.setMembershipListener(this); if (membershipService instanceof McastService) { ((McastService)membershipService).setMessageListener(this); } membershipService.start(MembershipService.MBR_RX); valid = true; } if ( Channel.MBR_TX_SEQ==(svc & Channel.MBR_TX_SEQ) ) { membershipService.start(MembershipService.MBR_TX); valid = true; } if ( !valid) { throw new IllegalArgumentException("Invalid start level, valid levels are:SND_RX_SEQ,SND_TX_SEQ,MBR_TX_SEQ,MBR_RX_SEQ"); } startLevel = (startLevel | svc); }catch ( ChannelException cx ) { throw cx; }catch ( Exception x ) { throw new ChannelException(x); } }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
protected synchronized void internalStop(int svc) throws ChannelException { try { //make sure we don't pass down any flags that are unrelated to the bottom layer svc = svc & Channel.DEFAULT; if (startLevel == 0) return; //we have already stopped up all components if (svc == 0 ) return;//nothing to stop boolean valid = false; if ( Channel.SND_RX_SEQ==(svc & Channel.SND_RX_SEQ) ) { clusterReceiver.stop(); clusterReceiver.setMessageListener(null); valid = true; } if ( Channel.SND_TX_SEQ==(svc & Channel.SND_TX_SEQ) ) { clusterSender.stop(); valid = true; } if ( Channel.MBR_RX_SEQ==(svc & Channel.MBR_RX_SEQ) ) { membershipService.stop(MembershipService.MBR_RX); membershipService.setMembershipListener(null); valid = true; } if ( Channel.MBR_TX_SEQ==(svc & Channel.MBR_TX_SEQ) ) { valid = true; membershipService.stop(MembershipService.MBR_TX); } if ( !valid) { throw new IllegalArgumentException("Invalid start level, valid levels are:SND_RX_SEQ,SND_TX_SEQ,MBR_TX_SEQ,MBR_RX_SEQ"); } startLevel = (startLevel & (~svc)); }catch ( Exception x ) { throw new ChannelException(x); } finally { } }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { try { byte[] data = compress(msg.getMessage().getBytes()); msg.getMessage().trim(msg.getMessage().getLength()); msg.getMessage().append(data,0,data.length); getNext().sendMessage(destination, msg, payload); } catch ( IOException x ) { log.error("Unable to compress byte contents"); throw new ChannelException(x); } }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { boolean async = (msg.getOptions() & Channel.SEND_OPTIONS_ASYNCHRONOUS) == Channel.SEND_OPTIONS_ASYNCHRONOUS; if ( async && run ) { if ( (getCurrentSize()+msg.getMessage().getLength()) > maxQueueSize ) { if ( alwaysSend ) { super.sendMessage(destination,msg,payload); return; } else { throw new ChannelException("Asynchronous queue is full, reached its limit of " + maxQueueSize +" bytes, current:" + getCurrentSize() + " bytes."); }//end if }//end if //add to queue if ( useDeepClone ) msg = (ChannelMessage)msg.deepclone(); if (!addToQueue(msg, destination, payload) ) { throw new ChannelException("Unable to add the message to the async queue, queue bug?"); } addAndGetCurrentSize(msg.getMessage().getLength()); } else { super.sendMessage(destination, msg, payload); } }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
Override public void sendMessage(Member[] destination, ChannelMessage message) throws ChannelException { if ( !connected ) throw new ChannelException("Sender not connected."); ParallelNioSender sender = (ParallelNioSender)getSender(); if (sender == null) { ChannelException cx = new ChannelException("Unable to retrieve a data sender, time out error."); for (int i = 0; i < destination.length; i++) cx.addFaultyMember(destination[i], new NullPointerException("Unable to retrieve a sender from the sender pool")); throw cx; } else { try { sender.sendMessage(destination, message); sender.keepalive(); } catch (ChannelException x) { sender.disconnect(); throw x; } finally { returnSender(sender); if (!connected) disconnect(); } } }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
Override public synchronized void sendMessage(Member[] destination, ChannelMessage msg) throws ChannelException { long start = System.currentTimeMillis(); this.setUdpBased((msg.getOptions()&Channel.SEND_OPTIONS_UDP) == Channel.SEND_OPTIONS_UDP); byte[] data = XByteBuffer.createDataPackage((ChannelData)msg); NioSender[] senders = setupForSend(destination); connect(senders); setData(senders,data); int remaining = senders.length; ChannelException cx = null; try { //loop until complete, an error happens, or we timeout long delta = System.currentTimeMillis() - start; boolean waitForAck = (Channel.SEND_OPTIONS_USE_ACK & msg.getOptions()) == Channel.SEND_OPTIONS_USE_ACK; while ( (remaining>0) && (delta<getTimeout()) ) { try { remaining -= doLoop(selectTimeout, getMaxRetryAttempts(),waitForAck,msg); } catch (Exception x ) { if (log.isTraceEnabled()) log.trace("Error sending message", x); int faulty = (cx == null)?0:cx.getFaultyMembers().length; if ( cx == null ) { if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException("Parallel NIO send failed.", x); } else { if (x instanceof ChannelException) cx.addFaultyMember( ( (ChannelException) x).getFaultyMembers()); } //count down the remaining on an error if (faulty<cx.getFaultyMembers().length) remaining -= (cx.getFaultyMembers().length-faulty); } //bail out if all remaining senders are failing if ( cx != null && cx.getFaultyMembers().length == remaining ) throw cx; delta = System.currentTimeMillis() - start; } if ( remaining > 0 ) { //timeout has occurred ChannelException cxtimeout = new ChannelException("Operation has timed out("+getTimeout()+" ms.)."); if ( cx==null ) cx = new ChannelException("Operation has timed out("+getTimeout()+" ms.)."); for (int i=0; i<senders.length; i++ ) { if (!senders[i].isComplete() ) cx.addFaultyMember(senders[i].getDestination(),cxtimeout); } throw cx; } else if ( cx != null ) { //there was an error throw cx; } } catch (Exception x ) { try { this.disconnect(); } catch (Exception e) {/*Ignore*/} if ( x instanceof ChannelException ) throw (ChannelException)x; else throw new ChannelException(x); } }
// in java/org/apache/catalina/tribes/membership/McastService.java
Override public void broadcast(ChannelMessage message) throws ChannelException { if (impl==null || (impl.startLevel & Channel.MBR_TX_SEQ)!=Channel.MBR_TX_SEQ ) throw new ChannelException("Multicast send is not started or enabled."); byte[] data = XByteBuffer.createDataPackage((ChannelData)message); if (data.length>McastServiceImpl.MAX_PACKET_SIZE) { throw new ChannelException("Packet length["+data.length+"] exceeds max packet size of "+McastServiceImpl.MAX_PACKET_SIZE+" bytes."); } DatagramPacket packet = new DatagramPacket(data,0,data.length); try { impl.send(false, packet); } catch (Exception x) { throw new ChannelException(x); } }
7
            
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { if ( x instanceof ChannelException ) throw (ChannelException)x; throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch (Exception x) { throw new ChannelException("Unable to add MessageDispatchInterceptor to interceptor chain.",x); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( Exception x ) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( Exception x ) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
catch ( IOException x ) { log.error("Unable to compress byte contents"); throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x ) { try { this.disconnect(); } catch (Exception e) {/*Ignore*/} if ( x instanceof ChannelException ) throw (ChannelException)x; else throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch (Exception x) { throw new ChannelException(x); }
58
            
// in java/org/apache/catalina/tribes/group/GroupChannel.java
Override public UniqueId send(Member[] destination, Serializable msg, int options) throws ChannelException { return send(destination,msg,options,null); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
Override public UniqueId send(Member[] destination, Serializable msg, int options, ErrorHandler handler) throws ChannelException { if ( msg == null ) throw new ChannelException("Cant send a NULL message"); XByteBuffer buffer = null; try { if ( destination == null || destination.length == 0) throw new ChannelException("No destination given"); ChannelData data = new ChannelData(true);//generates a unique Id data.setAddress(getLocalMember(false)); data.setTimestamp(System.currentTimeMillis()); byte[] b = null; if ( msg instanceof ByteMessage ){ b = ((ByteMessage)msg).getMessage(); options = options | SEND_OPTIONS_BYTE_MESSAGE; } else { b = XByteBuffer.serialize(msg); options = options & (~SEND_OPTIONS_BYTE_MESSAGE); } data.setOptions(options); //XByteBuffer buffer = new XByteBuffer(b.length+128,false); buffer = BufferPool.getBufferPool().getBuffer(b.length+128, false); buffer.append(b,0,b.length); data.setMessage(buffer); InterceptorPayload payload = null; if ( handler != null ) { payload = new InterceptorPayload(); payload.setErrorHandler(handler); } getFirstInterceptor().sendMessage(destination, data, payload); if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("GroupChannel - Sent msg:" + new UniqueId(data.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " to "+Arrays.toNameString(destination)); Logs.MESSAGES.trace("GroupChannel - Send Message:" + new UniqueId(data.getUniqueId()) + " is " +msg); } return new UniqueId(data.getUniqueId()); }catch ( Exception x ) { if ( x instanceof ChannelException ) throw (ChannelException)x; throw new ChannelException(x); } finally { if ( buffer != null ) BufferPool.getBufferPool().returnBuffer(buffer); } }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
protected synchronized void setupDefaultStack() throws ChannelException { if ( getFirstInterceptor() != null && ((getFirstInterceptor().getNext() instanceof ChannelCoordinator))) { ChannelInterceptor interceptor = null; Class<?> clazz = null; try { clazz = Class.forName("org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor", true,GroupChannel.class.getClassLoader()); clazz.newInstance(); } catch ( Throwable x ) { clazz = MessageDispatchInterceptor.class; }//catch try { interceptor = (ChannelInterceptor) clazz.newInstance(); } catch (Exception x) { throw new ChannelException("Unable to add MessageDispatchInterceptor to interceptor chain.",x); } this.addInterceptor(interceptor); } }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
protected void checkOptionFlags() throws ChannelException { StringBuilder conflicts = new StringBuilder(); ChannelInterceptor first = interceptors; while ( first != null ) { int flag = first.getOptionFlag(); if ( flag != 0 ) { ChannelInterceptor next = first.getNext(); while ( next != null ) { int nflag = next.getOptionFlag(); if (nflag!=0 && (((flag & nflag) == flag ) || ((flag & nflag) == nflag)) ) { conflicts.append("["); conflicts.append(first.getClass().getName()); conflicts.append(":"); conflicts.append(flag); conflicts.append(" == "); conflicts.append(next.getClass().getName()); conflicts.append(":"); conflicts.append(nflag); conflicts.append("] "); }//end if next = next.getNext(); }//while }//end if first = first.getNext(); }//while if ( conflicts.length() > 0 ) throw new ChannelException("Interceptor option flag conflict: "+conflicts.toString()); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
Override public synchronized void start(int svc) throws ChannelException { setupDefaultStack(); if (optionCheck) checkOptionFlags(); super.start(svc); if ( hbthread == null && heartbeat ) { hbthread = new HeartbeatThread(this,heartbeatSleeptime); hbthread.start(); } }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
Override public synchronized void stop(int svc) throws ChannelException { if (hbthread != null) { hbthread.stopHeartbeat(); hbthread = null; } super.stop(svc); }
// in java/org/apache/catalina/tribes/group/RpcChannel.java
public Response[] send(Member[] destination, Serializable message, int rpcOptions, int channelOptions, long timeout) throws ChannelException { if ( destination==null || destination.length == 0 ) return new Response[0]; //avoid dead lock int sendOptions = channelOptions & ~Channel.SEND_OPTIONS_SYNCHRONIZED_ACK; RpcCollectorKey key = new RpcCollectorKey(UUIDGenerator.randomUUID(false)); RpcCollector collector = new RpcCollector(key,rpcOptions,destination.length,timeout); try { synchronized (collector) { if ( rpcOptions != NO_REPLY ) responseMap.put(key, collector); RpcMessage rmsg = new RpcMessage(rpcId, key.id, message); channel.send(destination, rmsg, sendOptions); if ( rpcOptions != NO_REPLY ) collector.wait(timeout); } } catch ( InterruptedException ix ) { Thread.currentThread().interrupt(); }finally { responseMap.remove(key); } return collector.getResponses(); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { if ( destination == null ) destination = membershipService.getMembers(); if ((msg.getOptions()&Channel.SEND_OPTIONS_MULTICAST) == Channel.SEND_OPTIONS_MULTICAST) { membershipService.broadcast(msg); } else { clusterSender.sendMessage(msg,destination); } if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("ChannelCoordinator - Sent msg:" + new UniqueId(msg.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " to "+Arrays.toNameString(destination)); } }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
Override public void start(int svc) throws ChannelException { this.internalStart(svc); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
Override public void stop(int svc) throws ChannelException { this.internalStop(svc); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
protected synchronized void internalStart(int svc) throws ChannelException { try { boolean valid = false; //make sure we don't pass down any flags that are unrelated to the bottom layer svc = svc & Channel.DEFAULT; if (startLevel == Channel.DEFAULT) return; //we have already started up all components if (svc == 0 ) return;//nothing to start if (svc == (svc & startLevel)) throw new ChannelException("Channel already started for level:"+svc); //must start the receiver first so that we can coordinate the port it //listens to with the local membership settings if ( Channel.SND_RX_SEQ==(svc & Channel.SND_RX_SEQ) ) { clusterReceiver.setMessageListener(this); clusterReceiver.start(); //synchronize, big time FIXME membershipService.setLocalMemberProperties(getClusterReceiver().getHost(), getClusterReceiver().getPort(), getClusterReceiver().getSecurePort(), getClusterReceiver().getUdpPort()); valid = true; } if ( Channel.SND_TX_SEQ==(svc & Channel.SND_TX_SEQ) ) { clusterSender.start(); valid = true; } if ( Channel.MBR_RX_SEQ==(svc & Channel.MBR_RX_SEQ) ) { membershipService.setMembershipListener(this); if (membershipService instanceof McastService) { ((McastService)membershipService).setMessageListener(this); } membershipService.start(MembershipService.MBR_RX); valid = true; } if ( Channel.MBR_TX_SEQ==(svc & Channel.MBR_TX_SEQ) ) { membershipService.start(MembershipService.MBR_TX); valid = true; } if ( !valid) { throw new IllegalArgumentException("Invalid start level, valid levels are:SND_RX_SEQ,SND_TX_SEQ,MBR_TX_SEQ,MBR_RX_SEQ"); } startLevel = (startLevel | svc); }catch ( ChannelException cx ) { throw cx; }catch ( Exception x ) { throw new ChannelException(x); } }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
protected synchronized void internalStop(int svc) throws ChannelException { try { //make sure we don't pass down any flags that are unrelated to the bottom layer svc = svc & Channel.DEFAULT; if (startLevel == 0) return; //we have already stopped up all components if (svc == 0 ) return;//nothing to stop boolean valid = false; if ( Channel.SND_RX_SEQ==(svc & Channel.SND_RX_SEQ) ) { clusterReceiver.stop(); clusterReceiver.setMessageListener(null); valid = true; } if ( Channel.SND_TX_SEQ==(svc & Channel.SND_TX_SEQ) ) { clusterSender.stop(); valid = true; } if ( Channel.MBR_RX_SEQ==(svc & Channel.MBR_RX_SEQ) ) { membershipService.stop(MembershipService.MBR_RX); membershipService.setMembershipListener(null); valid = true; } if ( Channel.MBR_TX_SEQ==(svc & Channel.MBR_TX_SEQ) ) { valid = true; membershipService.stop(MembershipService.MBR_TX); } if ( !valid) { throw new IllegalArgumentException("Invalid start level, valid levels are:SND_RX_SEQ,SND_TX_SEQ,MBR_TX_SEQ,MBR_RX_SEQ"); } startLevel = (startLevel & (~svc)); }catch ( Exception x ) { throw new ChannelException(x); } finally { } }
// in java/org/apache/catalina/tribes/group/interceptors/TcpPingInterceptor.java
Override public synchronized void start(int svc) throws ChannelException { super.start(svc); running = true; if ( thread == null ) { thread = new PingThread(); thread.setDaemon(true); thread.setName("TcpPingInterceptor.PingThread-"+cnt.addAndGet(1)); thread.start(); } //acquire the interceptors to invoke on send ping events ChannelInterceptor next = getNext(); while ( next != null ) { if ( next instanceof TcpFailureDetector ) failureDetector = new WeakReference<TcpFailureDetector>((TcpFailureDetector)next); if ( next instanceof StaticMembershipInterceptor ) staticMembers = new WeakReference<StaticMembershipInterceptor>((StaticMembershipInterceptor)next); next = next.getNext(); } }
// in java/org/apache/catalina/tribes/group/interceptors/TcpPingInterceptor.java
Override public void stop(int svc) throws ChannelException { running = false; if ( thread != null ) thread.interrupt(); thread = null; super.stop(svc); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { try { super.sendMessage(destination, msg, payload); }catch ( ChannelException cx ) { FaultyMember[] mbrs = cx.getFaultyMembers(); for ( int i=0; i<mbrs.length; i++ ) { if ( mbrs[i].getCause()!=null && (!(mbrs[i].getCause() instanceof RemoteProcessException)) ) {//RemoteProcessException's are ok this.memberDisappeared(mbrs[i].getMember()); }//end if }//for throw cx; } }
// in java/org/apache/catalina/tribes/group/interceptors/StaticMembershipInterceptor.java
Override public void start(int svc) throws ChannelException { if ( (Channel.SND_RX_SEQ&svc)==Channel.SND_RX_SEQ ) super.start(Channel.SND_RX_SEQ); if ( (Channel.SND_TX_SEQ&svc)==Channel.SND_TX_SEQ ) super.start(Channel.SND_TX_SEQ); final Member[] mbrs = members.toArray(new Member[members.size()]); final ChannelInterceptorBase base = this; Thread t = new Thread() { @Override public void run() { for (int i=0; i<mbrs.length; i++ ) { base.memberAdded(mbrs[i]); } } }; t.start(); super.start(svc & (~Channel.SND_RX_SEQ) & (~Channel.SND_TX_SEQ)); }
// in java/org/apache/catalina/tribes/group/interceptors/OrderInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { if ( !okToProcess(msg.getOptions()) ) { super.sendMessage(destination, msg, payload); return; } ChannelException cx = null; for (int i=0; i<destination.length; i++ ) { try { int nr = 0; try { outLock.writeLock().lock(); nr = incCounter(destination[i]); } finally { outLock.writeLock().unlock(); } //reduce byte copy msg.getMessage().append(nr); try { getNext().sendMessage(new Member[] {destination[i]}, msg, payload); } finally { msg.getMessage().trim(4); } }catch ( ChannelException x ) { if ( cx == null ) cx = x; cx.addFaultyMember(x.getFaultyMembers()); } }//for if ( cx != null ) throw cx; }
// in java/org/apache/catalina/tribes/group/interceptors/TwoPhaseCommitInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { //todo, optimize, if destination.length==1, then we can do //msg.setOptions(msg.getOptions() & (~getOptionFlag()) //and just send one message if (okToProcess(msg.getOptions()) ) { super.sendMessage(destination, msg, null); ChannelMessage confirmation = null; if ( deepclone ) confirmation = (ChannelMessage)msg.deepclone(); else confirmation = (ChannelMessage)msg.clone(); confirmation.getMessage().reset(); UUIDGenerator.randomUUID(false,confirmation.getUniqueId(),0); confirmation.getMessage().append(START_DATA,0,START_DATA.length); confirmation.getMessage().append(msg.getUniqueId(),0,msg.getUniqueId().length); confirmation.getMessage().append(END_DATA,0,END_DATA.length); super.sendMessage(destination,confirmation,payload); } else { //turn off two phase commit //this wont work if the interceptor has 0 as a flag //since there is no flag to turn off //msg.setOptions(msg.getOptions() & (~getOptionFlag())); super.sendMessage(destination, msg, payload); } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
public void startElection(boolean force) throws ChannelException { synchronized (electionMutex) { MemberImpl local = (MemberImpl)getLocalMember(false); MemberImpl[] others = membership.getMembers(); fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_START_ELECT,this,"Election initated")); if ( others.length == 0 ) { this.viewId = new UniqueId(UUIDGenerator.randomUUID(false)); this.view = new Membership(local,AbsoluteOrder.comp, true); this.handleViewConf(this.createElectionMsg(local,others,local), view); return; //the only member, no need for an election } if ( suggestedviewId != null ) { if ( view != null && Arrays.diff(view,suggestedView,local).length == 0 && Arrays.diff(suggestedView,view,local).length == 0) { suggestedviewId = null; suggestedView = null; fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_ELECT_ABANDONED,this,"Election abandoned, running election matches view")); } else { fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_ELECT_ABANDONED,this,"Election abandoned, election running")); } return; //election already running, I'm not allowed to have two of them } if ( view != null && Arrays.diff(view,membership,local).length == 0 && Arrays.diff(membership,view,local).length == 0) { fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_ELECT_ABANDONED,this,"Election abandoned, view matches membership")); return; //already have this view installed } int prio = AbsoluteOrder.comp.compare(local,others[0]); MemberImpl leader = ( prio < 0 )?local:others[0];//am I the leader in my view? if ( local.equals(leader) || force ) { CoordinationMessage msg = createElectionMsg(local, others, leader); suggestedviewId = msg.getId(); suggestedView = new Membership(local,AbsoluteOrder.comp,true); Arrays.fill(suggestedView,msg.getMembers()); fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_PROCESS_ELECT,this,"Election, sending request")); sendElectionMsg(local,others[0],msg); } else { try { coordMsgReceived.set(false); fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_WAIT_FOR_MSG,this,"Election, waiting for request")); electionMutex.wait(waitForCoordMsgTimeout); }catch ( InterruptedException x ) { Thread.interrupted(); } if ( suggestedviewId == null && (!coordMsgReceived.get())) { //no message arrived, send the coord msg // fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_WAIT_FOR_MSG,this,"Election, waiting timed out.")); // startElection(true); fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_ELECT_ABANDONED,this,"Election abandoned, waiting timed out.")); } else { fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_ELECT_ABANDONED,this,"Election abandoned, received a message")); } }//end if } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
protected void sendElectionMsg(MemberImpl local, MemberImpl next, CoordinationMessage msg) throws ChannelException { fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_SEND_MSG,this,"Sending election message to("+next.getName()+")")); super.sendMessage(new Member[] {next}, createData(msg, local), null); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
protected void sendElectionMsgToNextInline(MemberImpl local, CoordinationMessage msg) throws ChannelException { int next = Arrays.nextIndex(local,msg.getMembers()); int current = next; msg.leader = msg.getMembers()[0]; boolean sent = false; while ( !sent && current >= 0 ) { try { sendElectionMsg(local, msg.getMembers()[current], msg); sent = true; }catch ( ChannelException x ) { log.warn("Unable to send election message to:"+msg.getMembers()[current]); current = Arrays.nextIndex(msg.getMembers()[current],msg.getMembers()); if ( current == next ) throw x; } } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
protected void processCoordMessage(CoordinationMessage msg) throws ChannelException { if ( !coordMsgReceived.get() ) { coordMsgReceived.set(true); synchronized (electionMutex) { electionMutex.notifyAll();} } msg.timestamp = System.currentTimeMillis(); Membership merged = mergeOnArrive(msg); if (isViewConf(msg)) handleViewConf(msg, merged); else handleToken(msg, merged); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
protected void handleToken(CoordinationMessage msg, Membership merged) throws ChannelException { MemberImpl local = (MemberImpl)getLocalMember(false); if ( local.equals(msg.getSource()) ) { //my message msg.src=local handleMyToken(local, msg, merged); } else { handleOtherToken(local, msg, merged); } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
protected void handleMyToken(MemberImpl local, CoordinationMessage msg, Membership merged) throws ChannelException { if ( local.equals(msg.getLeader()) ) { //no leadership change if ( Arrays.sameMembers(msg.getMembers(),merged.getMembers()) ) { msg.type = COORD_CONF; super.sendMessage(Arrays.remove(msg.getMembers(),local),createData(msg,local),null); handleViewConf(msg, merged); } else { //membership change suggestedView = new Membership(local,AbsoluteOrder.comp,true); suggestedviewId = msg.getId(); Arrays.fill(suggestedView,merged.getMembers()); msg.view = merged.getMembers(); sendElectionMsgToNextInline(local,msg); } } else { //leadership change suggestedView = null; suggestedviewId = null; msg.view = merged.getMembers(); sendElectionMsgToNextInline(local,msg); } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
protected void handleOtherToken(MemberImpl local, CoordinationMessage msg, Membership merged) throws ChannelException { if ( local.equals(msg.getLeader()) ) { //I am the new leader //startElection(false); } else { msg.view = merged.getMembers(); sendElectionMsgToNextInline(local,msg); } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
protected void handleViewConf(CoordinationMessage msg, Membership merged) throws ChannelException { if ( viewId != null && msg.getId().equals(viewId) ) return;//we already have this view view = new Membership((MemberImpl)getLocalMember(false),AbsoluteOrder.comp,true); Arrays.fill(view,msg.getMembers()); viewId = msg.getId(); if ( viewId.equals(suggestedviewId) ) { suggestedView = null; suggestedviewId = null; } if (suggestedView != null && AbsoluteOrder.comp.compare(suggestedView.getMembers()[0],merged.getMembers()[0])<0 ) { suggestedView = null; suggestedviewId = null; } fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_CONF_RX,this,"Accepted View")); if ( suggestedviewId == null && hasHigherPriority(merged.getMembers(),membership.getMembers()) ) { startElection(false); } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
Override public void start(int svc) throws ChannelException { if (membership == null) setupMembership(); if (started)return; fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_START, this, "Before start")); super.start(startsvc); started = true; if (view == null) view = new Membership( (MemberImpl)super.getLocalMember(true), AbsoluteOrder.comp, true); fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_START, this, "After start")); startElection(false); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
Override public void stop(int svc) throws ChannelException { try { halt(); synchronized (electionMutex) { if (!started)return; started = false; fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_STOP, this, "Before stop")); super.stop(startsvc); this.view = null; this.viewId = null; this.suggestedView = null; this.suggestedviewId = null; this.membership.reset(); fireInterceptorEvent(new CoordinationEvent(CoordinationEvent.EVT_STOP, this, "After stop")); } }finally { release(); } }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { waitForRelease(); super.sendMessage(destination, msg, payload); }
// in java/org/apache/catalina/tribes/group/interceptors/SimpleCoordinator.java
Override public void start(int svc) throws ChannelException { super.start(svc); installViewWhenStable(); }
// in java/org/apache/catalina/tribes/group/interceptors/SimpleCoordinator.java
Override public void stop(int svc) throws ChannelException { super.stop(svc); }
// in java/org/apache/catalina/tribes/group/interceptors/FragmentationInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { int size = msg.getMessage().getLength(); boolean frag = (size>maxSize) && okToProcess(msg.getOptions()); if ( frag ) { frag(destination, msg, payload); } else { msg.getMessage().append(frag); super.sendMessage(destination, msg, payload); } }
// in java/org/apache/catalina/tribes/group/interceptors/FragmentationInterceptor.java
public void frag(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { int size = msg.getMessage().getLength(); int count = ((size / maxSize )+(size%maxSize==0?0:1)); ChannelMessage[] messages = new ChannelMessage[count]; int remaining = size; for ( int i=0; i<count; i++ ) { ChannelMessage tmp = (ChannelMessage)msg.clone(); int offset = (i*maxSize); int length = Math.min(remaining,maxSize); tmp.getMessage().clear(); tmp.getMessage().append(msg.getMessage().getBytesDirect(),offset,length); //add the msg nr //tmp.getMessage().append(XByteBuffer.toBytes(i),0,4); tmp.getMessage().append(i); //add the total nr of messages //tmp.getMessage().append(XByteBuffer.toBytes(count),0,4); tmp.getMessage().append(count); //add true as the frag flag //byte[] flag = XByteBuffer.toBytes(true); //tmp.getMessage().append(flag,0,flag.length); tmp.getMessage().append(true); messages[i] = tmp; remaining -= length; } for ( int i=0; i<messages.length; i++ ) { super.sendMessage(destination,messages[i],payload); } }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { try { byte[] data = compress(msg.getMessage().getBytes()); msg.getMessage().trim(msg.getMessage().getLength()); msg.getMessage().append(data,0,data.length); getNext().sendMessage(destination, msg, payload); } catch ( IOException x ) { log.error("Unable to compress byte contents"); throw new ChannelException(x); } }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { boolean async = (msg.getOptions() & Channel.SEND_OPTIONS_ASYNCHRONOUS) == Channel.SEND_OPTIONS_ASYNCHRONOUS; if ( async && run ) { if ( (getCurrentSize()+msg.getMessage().getLength()) > maxQueueSize ) { if ( alwaysSend ) { super.sendMessage(destination,msg,payload); return; } else { throw new ChannelException("Asynchronous queue is full, reached its limit of " + maxQueueSize +" bytes, current:" + getCurrentSize() + " bytes."); }//end if }//end if //add to queue if ( useDeepClone ) msg = (ChannelMessage)msg.deepclone(); if (!addToQueue(msg, destination, payload) ) { throw new ChannelException("Unable to add the message to the async queue, queue bug?"); } addAndGetCurrentSize(msg.getMessage().getLength()); } else { super.sendMessage(destination, msg, payload); } }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
Override public void start(int svc) throws ChannelException { //start the thread if (!run ) { synchronized (this) { if ( !run && ((svc & Channel.SND_TX_SEQ)==Channel.SND_TX_SEQ) ) {//only start with the sender startQueue(); }//end if }//sync }//end if super.start(svc); }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
Override public void stop(int svc) throws ChannelException { //stop the thread if ( run ) { synchronized (this) { if ( run && ((svc & Channel.SND_TX_SEQ)==Channel.SND_TX_SEQ)) { stopQueue(); }//end if }//sync }//end if super.stop(svc); }
// in java/org/apache/catalina/tribes/group/interceptors/ThroughputInterceptor.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { if ( access.addAndGet(1) == 1 ) txStart = System.currentTimeMillis(); long bytes = XByteBuffer.getDataPackageLength(((ChannelData)msg).getDataPackageLength()); try { super.sendMessage(destination, msg, payload); }catch ( ChannelException x ) { msgTxErr.addAndGet(1); if ( access.get() == 1 ) access.addAndGet(-1); throw x; } mbTx += (bytes*destination.length)/(1024d*1024d); mbAppTx += bytes/(1024d*1024d); if ( access.addAndGet(-1) == 0 ) { long stop = System.currentTimeMillis(); timeTx += (stop - txStart) / 1000d; if ((msgTxCnt.get() / interval) >= lastCnt) { lastCnt++; report(timeTx); } } msgTxCnt.addAndGet(1); }
// in java/org/apache/catalina/tribes/group/ChannelInterceptorBase.java
Override public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException { if (getNext() != null) getNext().sendMessage(destination, msg, payload); }
// in java/org/apache/catalina/tribes/group/ChannelInterceptorBase.java
Override public void start(int svc) throws ChannelException { if ( getNext()!=null ) getNext().start(svc); }
// in java/org/apache/catalina/tribes/group/ChannelInterceptorBase.java
Override public void stop(int svc) throws ChannelException { if (getNext() != null) getNext().stop(svc); }
// in java/org/apache/catalina/tribes/transport/bio/PooledMultiSender.java
Override public void sendMessage(Member[] destination, ChannelMessage msg) throws ChannelException { MultiPointSender sender = null; try { sender = (MultiPointSender)getSender(); if (sender == null) { ChannelException cx = new ChannelException("Unable to retrieve a data sender, time out error."); for (int i = 0; i < destination.length; i++) cx.addFaultyMember(destination[i], new NullPointerException("Unable to retrieve a sender from the sender pool")); throw cx; } else { sender.sendMessage(destination, msg); } sender.keepalive(); }finally { if ( sender != null ) returnSender(sender); } }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
Override public synchronized void sendMessage(Member[] destination, ChannelMessage msg) throws ChannelException { byte[] data = XByteBuffer.createDataPackage((ChannelData)msg); BioSender[] senders = setupForSend(destination); ChannelException cx = null; for ( int i=0; i<senders.length; i++ ) { try { senders[i].sendMessage(data,(msg.getOptions()&Channel.SEND_OPTIONS_USE_ACK)==Channel.SEND_OPTIONS_USE_ACK); } catch (Exception x) { if (cx == null) cx = new ChannelException(x); cx.addFaultyMember(destination[i],x); } } if (cx!=null ) throw cx; }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
protected BioSender[] setupForSend(Member[] destination) throws ChannelException { ChannelException cx = null; BioSender[] result = new BioSender[destination.length]; for ( int i=0; i<destination.length; i++ ) { try { BioSender sender = bioSenders.get(destination[i]); if (sender == null) { sender = new BioSender(); AbstractSender.transferProperties(this,sender); sender.setDestination(destination[i]); bioSenders.put(destination[i], sender); } result[i] = sender; if (!result[i].isConnected() ) result[i].connect(); result[i].keepalive(); }catch (Exception x ) { if ( cx== null ) cx = new ChannelException(x); cx.addFaultyMember(destination[i],x); } } if ( cx!=null ) throw cx; else return result; }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
private synchronized void close() throws ChannelException { ChannelException x = null; Object[] members = bioSenders.keySet().toArray(); for (int i=0; i<members.length; i++ ) { Member mbr = (Member)members[i]; try { BioSender sender = bioSenders.get(mbr); sender.disconnect(); }catch ( Exception e ) { if ( x == null ) x = new ChannelException(e); x.addFaultyMember(mbr,e); } bioSenders.remove(mbr); } if ( x != null ) throw x; }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
Override public void sendMessage(Member[] destination, ChannelMessage message) throws ChannelException { if ( !connected ) throw new ChannelException("Sender not connected."); ParallelNioSender sender = (ParallelNioSender)getSender(); if (sender == null) { ChannelException cx = new ChannelException("Unable to retrieve a data sender, time out error."); for (int i = 0; i < destination.length; i++) cx.addFaultyMember(destination[i], new NullPointerException("Unable to retrieve a sender from the sender pool")); throw cx; } else { try { sender.sendMessage(destination, message); sender.keepalive(); } catch (ChannelException x) { sender.disconnect(); throw x; } finally { returnSender(sender); if (!connected) disconnect(); } } }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
Override public synchronized void sendMessage(Member[] destination, ChannelMessage msg) throws ChannelException { long start = System.currentTimeMillis(); this.setUdpBased((msg.getOptions()&Channel.SEND_OPTIONS_UDP) == Channel.SEND_OPTIONS_UDP); byte[] data = XByteBuffer.createDataPackage((ChannelData)msg); NioSender[] senders = setupForSend(destination); connect(senders); setData(senders,data); int remaining = senders.length; ChannelException cx = null; try { //loop until complete, an error happens, or we timeout long delta = System.currentTimeMillis() - start; boolean waitForAck = (Channel.SEND_OPTIONS_USE_ACK & msg.getOptions()) == Channel.SEND_OPTIONS_USE_ACK; while ( (remaining>0) && (delta<getTimeout()) ) { try { remaining -= doLoop(selectTimeout, getMaxRetryAttempts(),waitForAck,msg); } catch (Exception x ) { if (log.isTraceEnabled()) log.trace("Error sending message", x); int faulty = (cx == null)?0:cx.getFaultyMembers().length; if ( cx == null ) { if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException("Parallel NIO send failed.", x); } else { if (x instanceof ChannelException) cx.addFaultyMember( ( (ChannelException) x).getFaultyMembers()); } //count down the remaining on an error if (faulty<cx.getFaultyMembers().length) remaining -= (cx.getFaultyMembers().length-faulty); } //bail out if all remaining senders are failing if ( cx != null && cx.getFaultyMembers().length == remaining ) throw cx; delta = System.currentTimeMillis() - start; } if ( remaining > 0 ) { //timeout has occurred ChannelException cxtimeout = new ChannelException("Operation has timed out("+getTimeout()+" ms.)."); if ( cx==null ) cx = new ChannelException("Operation has timed out("+getTimeout()+" ms.)."); for (int i=0; i<senders.length; i++ ) { if (!senders[i].isComplete() ) cx.addFaultyMember(senders[i].getDestination(),cxtimeout); } throw cx; } else if ( cx != null ) { //there was an error throw cx; } } catch (Exception x ) { try { this.disconnect(); } catch (Exception e) {/*Ignore*/} if ( x instanceof ChannelException ) throw (ChannelException)x; else throw new ChannelException(x); } }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
private int doLoop(long selectTimeOut, int maxAttempts, boolean waitForAck, ChannelMessage msg) throws IOException, ChannelException { int completed = 0; int selectedKeys = selector.select(selectTimeOut); if (selectedKeys == 0) { return 0; } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey sk = it.next(); it.remove(); int readyOps = sk.readyOps(); sk.interestOps(sk.interestOps() & ~readyOps); NioSender sender = (NioSender) sk.attachment(); try { if (sender.process(sk,waitForAck)) { completed++; sender.setComplete(true); if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("ParallelNioSender - Sent msg:" + new UniqueId(msg.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " to "+sender.getDestination().getName()); } SenderState.getSenderState(sender.getDestination()).setReady(); }//end if } catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if } } return completed; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
private void connect(NioSender[] senders) throws ChannelException { ChannelException x = null; for (int i=0; i<senders.length; i++ ) { try { senders[i].connect(); }catch ( IOException io ) { if ( x==null ) x = new ChannelException(io); x.addFaultyMember(senders[i].getDestination(),io); } } if ( x != null ) throw x; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
private void setData(NioSender[] senders, byte[] data) throws ChannelException { ChannelException x = null; for (int i=0; i<senders.length; i++ ) { try { senders[i].setMessage(data); }catch ( IOException io ) { if ( x==null ) x = new ChannelException(io); x.addFaultyMember(senders[i].getDestination(),io); } } if ( x != null ) throw x; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
private NioSender[] setupForSend(Member[] destination) throws ChannelException { ChannelException cx = null; NioSender[] result = new NioSender[destination.length]; for ( int i=0; i<destination.length; i++ ) { NioSender sender = nioSenders.get(destination[i]); try { if (sender == null) { sender = new NioSender(); AbstractSender.transferProperties(this, sender); nioSenders.put(destination[i], sender); } sender.reset(); sender.setDestination(destination[i]); sender.setSelector(selector); sender.setUdpBased(isUdpBased()); result[i] = sender; }catch ( UnknownHostException x ) { if (cx == null) cx = new ChannelException("Unable to setup NioSender.", x); cx.addFaultyMember(destination[i], x); } } if ( cx != null ) throw cx; else return result; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
private synchronized void close() throws ChannelException { ChannelException x = null; Object[] members = nioSenders.keySet().toArray(); for (int i=0; i<members.length; i++ ) { Member mbr = (Member)members[i]; try { NioSender sender = nioSenders.get(mbr); sender.disconnect(); }catch ( Exception e ) { if ( x == null ) x = new ChannelException(e); x.addFaultyMember(mbr,e); } nioSenders.remove(mbr); } if ( x != null ) throw x; }
// in java/org/apache/catalina/tribes/transport/ReplicationTransmitter.java
Override public void sendMessage(ChannelMessage message, Member[] destination) throws ChannelException { MultiPointSender sender = getTransport(); sender.sendMessage(destination,message); }
// in java/org/apache/catalina/tribes/tipis/LazyReplicatedMap.java
Override protected Member[] publishEntryInfo(Object key, Object value) throws ChannelException { if (! (key instanceof Serializable && value instanceof Serializable) ) return new Member[0]; Member[] members = getMapMembers(); int firstIdx = getNextBackupIndex(); int nextIdx = firstIdx; Member[] backup = new Member[0]; //there are no backups if ( members.length == 0 || firstIdx == -1 ) return backup; boolean success = false; do { //select a backup node Member next = members[nextIdx]; //increment for the next round of back up selection nextIdx = nextIdx + 1; if ( nextIdx >= members.length ) nextIdx = 0; if (next == null) { continue; } MapMessage msg = null; try { backup = wrap(next); //publish the backup data to one node msg = new MapMessage(getMapContextName(), MapMessage.MSG_BACKUP, false, (Serializable) key, (Serializable) value, null, channel.getLocalMember(false), backup); if ( log.isTraceEnabled() ) log.trace("Publishing backup data:"+msg+" to: "+next.getName()); UniqueId id = getChannel().send(backup, msg, getChannelSendOptions()); if ( log.isTraceEnabled() ) log.trace("Data published:"+msg+" msg Id:"+id); //we published out to a backup, mark the test success success = true; }catch ( ChannelException x ) { log.error("Unable to replicate backup key:"+key+" to backup:"+next+". Reason:"+x.getMessage(),x); } try { //publish the data out to all nodes Member[] proxies = excludeFromSet(backup, getMapMembers()); if (success && proxies.length > 0 ) { msg = new MapMessage(getMapContextName(), MapMessage.MSG_PROXY, false, (Serializable) key, null, null, channel.getLocalMember(false),backup); if ( log.isTraceEnabled() ) log.trace("Publishing proxy data:"+msg+" to: "+Arrays.toNameString(proxies)); getChannel().send(proxies, msg, getChannelSendOptions()); } }catch ( ChannelException x ) { //log the error, but proceed, this should only happen if a node went down, //and if the node went down, then it can't receive the message, the others //should still get it. log.error("Unable to replicate proxy key:"+key+" to backup:"+next+". Reason:"+x.getMessage(),x); } } while ( !success && (firstIdx!=nextIdx)); return backup; }
// in java/org/apache/catalina/tribes/tipis/ReplicatedMap.java
Override protected Member[] publishEntryInfo(Object key, Object value) throws ChannelException { if (! (key instanceof Serializable && value instanceof Serializable) ) return new Member[0]; //select a backup node Member[] backup = getMapMembers(); if (backup == null || backup.length == 0) return null; //publish the data out to all nodes MapMessage msg = new MapMessage(getMapContextName(), MapMessage.MSG_COPY, false, (Serializable) key, (Serializable) value, null,channel.getLocalMember(false), backup); getChannel().send(getMapMembers(), msg, getChannelSendOptions()); return backup; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
protected void ping(long timeout) throws ChannelException { //send out a map membership message, only wait for the first reply MapMessage msg = new MapMessage(this.mapContextName, MapMessage.MSG_INIT, false, null, null, null, channel.getLocalMember(false), null); if ( channel.getMembers().length > 0 ) { try { //send a ping, wait for all nodes to reply Response[] resp = rpcChannel.send(channel.getMembers(), msg, RpcChannel.ALL_REPLY, (channelSendOptions), (int) accessTimeout); for (int i = 0; i < resp.length; i++) { memberAlive(resp[i].getSource()); } } catch (ChannelException ce) { // Handle known failed members FaultyMember[] faultyMembers = ce.getFaultyMembers(); for (FaultyMember faultyMember : faultyMembers) { memberDisappeared(faultyMember.getMember()); } } } //update our map of members, expire some if we didn't receive a ping back synchronized (mapMembers) { Iterator<Map.Entry<Member, Long>> it = mapMembers.entrySet().iterator(); long now = System.currentTimeMillis(); while ( it.hasNext() ) { Map.Entry<Member,Long> entry = it.next(); long access = entry.getValue().longValue(); if ( (now - access) > timeout ) { it.remove(); memberDisappeared(entry.getKey()); } } }//synch }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
protected void broadcast(int msgtype, boolean rpc) throws ChannelException { Member[] members = channel.getMembers(); // No destination. if (members.length == 0 ) return; //send out a map membership message, only wait for the first reply MapMessage msg = new MapMessage(this.mapContextName, msgtype, false, null, null, null, channel.getLocalMember(false), null); if ( rpc) { Response[] resp = rpcChannel.send(members, msg, RpcChannel.FIRST_REPLY, (channelSendOptions), rpcTimeout); if (resp.length > 0) { for (int i = 0; i < resp.length; i++) { mapMemberAdded(resp[i].getSource()); messageReceived(resp[i].getMessage(), resp[i].getSource()); } } else { log.warn("broadcast received 0 replies, probably a timeout."); } } else { channel.send(channel.getMembers(),msg,channelSendOptions); } }
// in java/org/apache/catalina/tribes/membership/McastService.java
Override public void broadcast(ChannelMessage message) throws ChannelException { if (impl==null || (impl.startLevel & Channel.MBR_TX_SEQ)!=Channel.MBR_TX_SEQ ) throw new ChannelException("Multicast send is not started or enabled."); byte[] data = XByteBuffer.createDataPackage((ChannelData)message); if (data.length>McastServiceImpl.MAX_PACKET_SIZE) { throw new ChannelException("Packet length["+data.length+"] exceeds max packet size of "+McastServiceImpl.MAX_PACKET_SIZE+" bytes."); } DatagramPacket packet = new DatagramPacket(data,0,data.length); try { impl.send(false, packet); } catch (Exception x) { throw new ChannelException(x); } }
21
            
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( ChannelException cx ) { throw cx; }
// in java/org/apache/catalina/tribes/group/interceptors/TcpPingInterceptor.java
catch (ChannelException x) { log.warn("Unable to send TCP ping.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( ChannelException cx ) { FaultyMember[] mbrs = cx.getFaultyMembers(); for ( int i=0; i<mbrs.length; i++ ) { if ( mbrs[i].getCause()!=null && (!(mbrs[i].getCause() instanceof RemoteProcessException)) ) {//RemoteProcessException's are ok this.memberDisappeared(mbrs[i].getMember()); }//end if }//for throw cx; }
// in java/org/apache/catalina/tribes/group/interceptors/OrderInterceptor.java
catch ( ChannelException x ) { if ( cx == null ) cx = x; cx.addFaultyMember(x.getFaultyMembers()); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.warn("Unable to send election message to:"+msg.getMembers()[current]); current = Arrays.nextIndex(msg.getMembers()[current],msg.getMembers()); if ( current == next ) throw x; }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.error("Error processing coordination message. Could be fatal.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.error("Unable to start election when member was added.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.error("Unable to start election when member was removed.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/ThroughputInterceptor.java
catch ( ChannelException x ) { msgTxErr.addAndGet(1); if ( access.get() == 1 ) access.addAndGet(-1); throw x; }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
catch (ChannelException x) { sender.disconnect(); throw x; }
// in java/org/apache/catalina/tribes/tipis/LazyReplicatedMap.java
catch ( ChannelException x ) { log.error("Unable to replicate backup key:"+key+" to backup:"+next+". Reason:"+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/tipis/LazyReplicatedMap.java
catch ( ChannelException x ) { //log the error, but proceed, this should only happen if a node went down, //and if the node went down, then it can't receive the message, the others //should still get it. log.error("Unable to replicate proxy key:"+key+" to backup:"+next+". Reason:"+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.warn("Unable to send map start message."); // remove listener from channel this.rpcChannel.breakdown(); this.channel.removeChannelListener(this); this.channel.removeMembershipListener(this); throw new RuntimeException("Unable to start replicated map.",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException ce) { // Handle known failed members FaultyMember[] faultyMembers = ce.getFaultyMembers(); for (FaultyMember faultyMember : faultyMembers) { memberDisappeared(faultyMember.getMember()); } }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to replicate data.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to transfer LazyReplicatedMap state.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to select backup node.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to relocate[" + entry.getKey() + "] to a new backup node", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to relocate[" + entry.getKey() + "] to a new backup node", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( ChannelException x ) { log.error("Unable to replicate out data for a LazyReplicatedMap.remove operation",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.error("Unable to replicate out data for a LazyReplicatedMap.put operation", x); }
6
            
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( ChannelException cx ) { throw cx; }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( ChannelException cx ) { FaultyMember[] mbrs = cx.getFaultyMembers(); for ( int i=0; i<mbrs.length; i++ ) { if ( mbrs[i].getCause()!=null && (!(mbrs[i].getCause() instanceof RemoteProcessException)) ) {//RemoteProcessException's are ok this.memberDisappeared(mbrs[i].getMember()); }//end if }//for throw cx; }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( ChannelException x ) { log.warn("Unable to send election message to:"+msg.getMembers()[current]); current = Arrays.nextIndex(msg.getMembers()[current],msg.getMembers()); if ( current == next ) throw x; }
// in java/org/apache/catalina/tribes/group/interceptors/ThroughputInterceptor.java
catch ( ChannelException x ) { msgTxErr.addAndGet(1); if ( access.get() == 1 ) access.addAndGet(-1); throw x; }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
catch (ChannelException x) { sender.disconnect(); throw x; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.warn("Unable to send map start message."); // remove listener from channel this.rpcChannel.breakdown(); this.channel.removeChannelListener(this); this.channel.removeMembershipListener(this); throw new RuntimeException("Unable to start replicated map.",x); }
1
unknown (Lib) CharConversionException 1
            
// in java/javax/servlet/ServletOutputStream.java
public void print(String s) throws IOException { if (s == null) s = "null"; int len = s.length(); for (int i = 0; i < len; i++) { char c = s.charAt(i); // // XXX NOTE: This is clearly incorrect for many strings, // but is the only consistent approach within the current // servlet framework. It must suffice until servlet output // streams properly encode their output. // if ((c & 0xff00) != 0) { // high order byte must be zero String errMsg = lStrings.getString("err.not_iso8859_1"); Object[] errArgs = new Object[1]; errArgs[0] = Character.valueOf(c); errMsg = MessageFormat.format(errMsg, errArgs); throw new CharConversionException(errMsg); } write(c); } }
0 0 0 0 0
unknown (Lib) ClassCastException 2
            
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data, int offset, int length, ClassLoader[] cls) throws IOException, ClassNotFoundException, ClassCastException { invokecount.addAndGet(1); Object message = null; if ( cls == null ) cls = new ClassLoader[0]; if (data != null && length > 0) { InputStream instream = new ByteArrayInputStream(data,offset,length); ObjectInputStream stream = null; stream = (cls.length>0)? new ReplicationStream(instream,cls):new ObjectInputStream(instream); message = stream.readObject(); instream.close(); stream.close(); } if ( message == null ) { return null; } else if (message instanceof Serializable) return (Serializable) message; else { throw new ClassCastException("Message has the wrong class. It should implement Serializable, instead it is:"+message.getClass().getName()); } }
// in java/javax/el/ArrayELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); checkBounds(base, idx); if (value != null && !base.getClass().getComponentType().isAssignableFrom( value.getClass())) { throw new ClassCastException(message(context, "objectNotAssignable", new Object[] {value.getClass().getName(), base.getClass().getComponentType().getName()})); } Array.set(base, idx, value); } }
0 6
            
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data) throws IOException, ClassNotFoundException, ClassCastException { return deserialize(data,0,data.length); }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data, int offset, int length) throws IOException, ClassNotFoundException, ClassCastException { return deserialize(data,offset,length,null); }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data, int offset, int length, ClassLoader[] cls) throws IOException, ClassNotFoundException, ClassCastException { invokecount.addAndGet(1); Object message = null; if ( cls == null ) cls = new ClassLoader[0]; if (data != null && length > 0) { InputStream instream = new ByteArrayInputStream(data,offset,length); ObjectInputStream stream = null; stream = (cls.length>0)? new ReplicationStream(instream,cls):new ObjectInputStream(instream); message = stream.readObject(); instream.close(); stream.close(); } if ( message == null ) { return null; } else if (message instanceof Serializable) return (Serializable) message; else { throw new ClassCastException("Message has the wrong class. It should implement Serializable, instead it is:"+message.getClass().getName()); } }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
Filter getFilter() throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { // Return the existing filter instance, if any if (this.filter != null) return (this.filter); // Identify the class loader we will be using String filterClass = filterDef.getFilterClass(); this.filter = (Filter) getInstanceManager().newInstance(filterClass); initFilter(); return (this.filter); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
void setFilterDef(FilterDef filterDef) throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { this.filterDef = filterDef; if (filterDef == null) { // Release any previously allocated filter instance if (this.filter != null){ if (Globals.IS_SECURITY_ENABLED) { try{ SecurityUtil.doAsPrivilege("destroy", filter); } catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); } SecurityUtil.remove(filter); } else { filter.destroy(); } if (!context.getIgnoreAnnotations()) { try { ((StandardContext) context).getInstanceManager().destroyInstance(this.filter); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); } } } this.filter = null; } else { // Allocate a new filter instance if necessary if (filterDef.getFilter() == null) { getFilter(); } } }
12
            
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassCastException e) { log.error(sm.getString("contextConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/TldConfig.java
catch (ClassCastException e) { log.error(sm.getString("tldConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/EngineConfig.java
catch (ClassCastException e) { log.error(sm.getString("engineConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/HostConfig.java
catch (ClassCastException e) { log.error(sm.getString("hostConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/UserConfig.java
catch (ClassCastException e) { log.error(sm.getString("hostConfig.cce", event.getLifecycle()), e); return; }
// in java/org/apache/catalina/startup/Tomcat.java
catch (ClassCastException e) { return; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassCastException e) { log.error(" Failed tracking modifications of '" + getJarPath() + "' : " + e.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassCastException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (ClassCastException cce) { project.log("wrong object reference " + refId + " - " + pref.getClass()); return null; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (ClassCastException cce) { getProject().log( "Wrong object reference " + getRef() + " - " + pref.getClass()); return null; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ClassCastException e) { unavailable(null); // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.notServlet", servletClass), e); }
// in java/javax/servlet/http/HttpServlet.java
catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); }
3
            
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassCastException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ClassCastException e) { unavailable(null); // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.notServlet", servletClass), e); }
// in java/javax/servlet/http/HttpServlet.java
catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); }
0
unknown (Lib) ClassFormatError 0 0 0 1
            
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassFormatError e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); return null; }
0 0
runtime (Domain) ClassFormatException
public class ClassFormatException extends RuntimeException {

    private static final long serialVersionUID = 3243149520175287759L;

    public ClassFormatException() {
        super();
    }


    public ClassFormatException(String s) {
        super(s);
    }

    public ClassFormatException(String s, Throwable initCause) {
        super(s, initCause);
    }
}
14
            
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
public static final String codeToString( byte[] code, ConstantPool constant_pool, int index, int length, boolean verbose ) { StringBuilder buf = new StringBuilder(code.length * 20); // Should be sufficient ByteSequence stream = new ByteSequence(code); try { for (int i = 0; i < index; i++) { codeToString(stream, constant_pool, verbose); } for (int i = 0; stream.available() > 0; i++) { if ((length < 0) || (i < length)) { String indices = fillup(stream.getIndex() + ":", 6, true, ' '); buf.append(indices).append(codeToString(stream, constant_pool, verbose)) .append('\n'); } } } catch (IOException e) { System.out.println(buf.toString()); e.printStackTrace(); throw new ClassFormatException("Byte code error: " + e, e); } return buf.toString(); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
public static final String methodSignatureToString( String signature, String name, String access, boolean chopit, LocalVariableTable vars ) throws ClassFormatException { StringBuilder buf = new StringBuilder("("); String type; int index; int var_index = (access.indexOf("static") >= 0) ? 0 : 1; try { // Read all declarations between for `(' and `)' if (signature.charAt(0) != '(') { throw new ClassFormatException("Invalid method signature: " + signature); } index = 1; // current string position while (signature.charAt(index) != ')') { String param_type = signatureToString(signature.substring(index), chopit); buf.append(param_type); if (vars != null) { LocalVariable l = vars.getLocalVariable(var_index); if (l != null) { buf.append(" ").append(l.getName()); } } else { buf.append(" arg").append(var_index); } if ("double".equals(param_type) || "long".equals(param_type)) { var_index += 2; } else { var_index++; } buf.append(", "); //corrected concurrent private static field acess index += unwrap(consumed_chars); // update position } index++; // update position // Read return type after `)' type = signatureToString(signature.substring(index), chopit); } catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); } if (buf.length() > 1) { buf.setLength(buf.length() - 2); } buf.append(")"); return access + ((access.length() > 0) ? " " : "") + // May be an empty string type + " " + name + buf.toString(); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
public static final String signatureToString( String signature, boolean chopit ) { //corrected concurrent private static field acess wrap(consumed_chars, 1); // This is the default, read just one char like `B' try { switch (signature.charAt(0)) { case 'B': return "byte"; case 'C': return "char"; case 'D': return "double"; case 'F': return "float"; case 'I': return "int"; case 'J': return "long"; case 'L': { // Full class name int index = signature.indexOf(';'); // Look for closing `;' if (index < 0) { throw new ClassFormatException("Invalid signature: " + signature); } //corrected concurrent private static field acess wrap(consumed_chars, index + 1); // "Lblabla;" `L' and `;' are removed return compactClassName(signature.substring(1, index), chopit); } case 'S': return "short"; case 'Z': return "boolean"; case '[': { // Array declaration int n; StringBuilder brackets; String type; int consumed_chars; // Shadows global var brackets = new StringBuilder(); // Accumulate []'s // Count opening brackets and look for optional size argument for (n = 0; signature.charAt(n) == '['; n++) { brackets.append("[]"); } consumed_chars = n; // Remember value // The rest of the string denotes a `<field_type>' type = signatureToString(signature.substring(n), chopit); //corrected concurrent private static field acess //Utility.consumed_chars += consumed_chars; is replaced by: int _temp = unwrap(Utility.consumed_chars) + consumed_chars; wrap(Utility.consumed_chars, _temp); return type + brackets.toString(); } case 'V': return "void"; default: throw new ClassFormatException("Invalid signature: `" + signature + "'"); } } catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid signature: " + signature, e); } }
// in java/org/apache/tomcat/util/bcel/classfile/Constant.java
static final Constant readConstant( DataInputStream file ) throws IOException, ClassFormatException { byte b = file.readByte(); // Read tag byte switch (b) { case Constants.CONSTANT_Class: return new ConstantClass(file); case Constants.CONSTANT_Fieldref: return new ConstantFieldref(file); case Constants.CONSTANT_Methodref: return new ConstantMethodref(file); case Constants.CONSTANT_InterfaceMethodref: return new ConstantInterfaceMethodref(file); case Constants.CONSTANT_String: return new ConstantString(file); case Constants.CONSTANT_Integer: return new ConstantInteger(file); case Constants.CONSTANT_Float: return new ConstantFloat(file); case Constants.CONSTANT_Long: return new ConstantLong(file); case Constants.CONSTANT_Double: return new ConstantDouble(file); case Constants.CONSTANT_NameAndType: return new ConstantNameAndType(file); case Constants.CONSTANT_Utf8: return new ConstantUtf8(file); default: throw new ClassFormatException("Invalid byte tag in constant pool: " + b); } }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public Constant getConstant( int index ) { if (index >= constant_pool.length || index < 0) { throw new ClassFormatException("Invalid constant pool reference: " + index + ". Constant pool size is: " + constant_pool.length); } return constant_pool[index]; }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public Constant getConstant( int index, byte tag ) throws ClassFormatException { Constant c; c = getConstant(index); if (c == null) { throw new ClassFormatException("Constant pool at index " + index + " is null."); } if (c.getTag() != tag) { throw new ClassFormatException("Expected class `" + Constants.CONSTANT_NAMES[tag] + "' at index " + index + " and got " + c); } return c; }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapTableEntry.java
public final void dump( DataOutputStream file ) throws IOException { file.write(frame_type); if (frame_type >= Constants.SAME_FRAME && frame_type <= Constants.SAME_FRAME_MAX) { // nothing to be done } else if (frame_type >= Constants.SAME_LOCALS_1_STACK_ITEM_FRAME && frame_type <= Constants.SAME_LOCALS_1_STACK_ITEM_FRAME_MAX) { types_of_stack_items[0].dump(file); } else if (frame_type == Constants.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { file.writeShort(byte_code_offset_delta); types_of_stack_items[0].dump(file); } else if (frame_type >= Constants.CHOP_FRAME && frame_type <= Constants.CHOP_FRAME_MAX) { file.writeShort(byte_code_offset_delta); } else if (frame_type == Constants.SAME_FRAME_EXTENDED) { file.writeShort(byte_code_offset_delta); } else if (frame_type >= Constants.APPEND_FRAME && frame_type <= Constants.APPEND_FRAME_MAX) { file.writeShort(byte_code_offset_delta); for (int i = 0; i < number_of_locals; i++) { types_of_locals[i].dump(file); } } else if (frame_type == Constants.FULL_FRAME) { file.writeShort(byte_code_offset_delta); file.writeShort(number_of_locals); for (int i = 0; i < number_of_locals; i++) { types_of_locals[i].dump(file); } file.writeShort(number_of_stack_items); for (int i = 0; i < number_of_stack_items; i++) { types_of_stack_items[i].dump(file); } } else { /* Can't happen */ throw new ClassFormatException ("Invalid Stack map table tag: " + frame_type); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readClassInfo() throws IOException, ClassFormatException { access_flags = file.readUnsignedShort(); /* Interfaces are implicitely abstract, the flag should be set * according to the JVM specification. */ if ((access_flags & Constants.ACC_INTERFACE) != 0) { access_flags |= Constants.ACC_ABSTRACT; } if (((access_flags & Constants.ACC_ABSTRACT) != 0) && ((access_flags & Constants.ACC_FINAL) != 0)) { throw new ClassFormatException("Class " + file_name + " can't be both final and abstract"); } class_name_index = file.readUnsignedShort(); superclass_name_index = file.readUnsignedShort(); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readID() throws IOException, ClassFormatException { int magic = 0xCAFEBABE; if (file.readInt() != magic) { throw new ClassFormatException(file_name + " is not a Java .class file"); } }
3
            
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (IOException e) { System.out.println(buf.toString()); e.printStackTrace(); throw new ClassFormatException("Byte code error: " + e, e); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid signature: " + signature, e); }
21
            
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
public static final String methodSignatureToString( String signature, String name, String access, boolean chopit, LocalVariableTable vars ) throws ClassFormatException { StringBuilder buf = new StringBuilder("("); String type; int index; int var_index = (access.indexOf("static") >= 0) ? 0 : 1; try { // Read all declarations between for `(' and `)' if (signature.charAt(0) != '(') { throw new ClassFormatException("Invalid method signature: " + signature); } index = 1; // current string position while (signature.charAt(index) != ')') { String param_type = signatureToString(signature.substring(index), chopit); buf.append(param_type); if (vars != null) { LocalVariable l = vars.getLocalVariable(var_index); if (l != null) { buf.append(" ").append(l.getName()); } } else { buf.append(" arg").append(var_index); } if ("double".equals(param_type) || "long".equals(param_type)) { var_index += 2; } else { var_index++; } buf.append(", "); //corrected concurrent private static field acess index += unwrap(consumed_chars); // update position } index++; // update position // Read return type after `)' type = signatureToString(signature.substring(index), chopit); } catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); } if (buf.length() > 1) { buf.setLength(buf.length() - 2); } buf.append(")"); return access + ((access.length() > 0) ? " " : "") + // May be an empty string type + " " + name + buf.toString(); }
// in java/org/apache/tomcat/util/bcel/classfile/Constant.java
static final Constant readConstant( DataInputStream file ) throws IOException, ClassFormatException { byte b = file.readByte(); // Read tag byte switch (b) { case Constants.CONSTANT_Class: return new ConstantClass(file); case Constants.CONSTANT_Fieldref: return new ConstantFieldref(file); case Constants.CONSTANT_Methodref: return new ConstantMethodref(file); case Constants.CONSTANT_InterfaceMethodref: return new ConstantInterfaceMethodref(file); case Constants.CONSTANT_String: return new ConstantString(file); case Constants.CONSTANT_Integer: return new ConstantInteger(file); case Constants.CONSTANT_Float: return new ConstantFloat(file); case Constants.CONSTANT_Long: return new ConstantLong(file); case Constants.CONSTANT_Double: return new ConstantDouble(file); case Constants.CONSTANT_NameAndType: return new ConstantNameAndType(file); case Constants.CONSTANT_Utf8: return new ConstantUtf8(file); default: throw new ClassFormatException("Invalid byte tag in constant pool: " + b); } }
// in java/org/apache/tomcat/util/bcel/classfile/Attribute.java
public static final Attribute readAttribute(DataInputStream file, ConstantPool constant_pool) throws IOException, ClassFormatException { ConstantUtf8 c; String name; int name_index; int length; byte tag = Constants.ATTR_UNKNOWN; // Unknown attribute // Get class name from constant pool via `name_index' indirection name_index = file.readUnsignedShort(); c = (ConstantUtf8) constant_pool.getConstant(name_index, Constants.CONSTANT_Utf8); name = c.getBytes(); // Length of data in bytes length = file.readInt(); // Compare strings to find known attribute // System.out.println(name); for (byte i = 0; i < Constants.KNOWN_ATTRIBUTES; i++) { if (name.equals(Constants.ATTRIBUTE_NAMES[i])) { tag = i; // found! break; } } // Call proper constructor, depending on `tag' switch (tag) { case Constants.ATTR_UNKNOWN: AttributeReader r = readers.get(name); if (r != null) { return r.createAttribute(name_index, length, file, constant_pool); } return new Unknown(name_index, length, file, constant_pool); case Constants.ATTR_CONSTANT_VALUE: return new ConstantValue(name_index, length, file, constant_pool); case Constants.ATTR_SOURCE_FILE: return new SourceFile(name_index, length, file, constant_pool); case Constants.ATTR_CODE: return new Code(name_index, length, file, constant_pool); case Constants.ATTR_EXCEPTIONS: return new ExceptionTable(name_index, length, file, constant_pool); case Constants.ATTR_LINE_NUMBER_TABLE: return new LineNumberTable(name_index, length, file, constant_pool); case Constants.ATTR_LOCAL_VARIABLE_TABLE: return new LocalVariableTable(name_index, length, file, constant_pool); case Constants.ATTR_INNER_CLASSES: return new InnerClasses(name_index, length, file, constant_pool); case Constants.ATTR_SYNTHETIC: return new Synthetic(name_index, length, file, constant_pool); case Constants.ATTR_DEPRECATED: return new Deprecated(name_index, length, file, constant_pool); case Constants.ATTR_PMG: return new PMGClass(name_index, length, file, constant_pool); case Constants.ATTR_SIGNATURE: return new Signature(name_index, length, file, constant_pool); case Constants.ATTR_STACK_MAP: return new StackMap(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIME_VISIBLE_ANNOTATIONS: return new RuntimeVisibleAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIMEIN_VISIBLE_ANNOTATIONS: return new RuntimeInvisibleAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS: return new RuntimeVisibleParameterAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIMEIN_VISIBLE_PARAMETER_ANNOTATIONS: return new RuntimeInvisibleParameterAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_ANNOTATION_DEFAULT: return new AnnotationDefault(name_index, length, file, constant_pool); case Constants.ATTR_LOCAL_VARIABLE_TYPE_TABLE: return new LocalVariableTypeTable(name_index, length, file, constant_pool); case Constants.ATTR_ENCLOSING_METHOD: return new EnclosingMethod(name_index, length, file, constant_pool); case Constants.ATTR_STACK_MAP_TABLE: return new StackMapTable(name_index, length, file, constant_pool); default: // Never reached throw new IllegalStateException("Unrecognized attribute type tag parsed: " + tag); } }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public String constantToString( Constant c ) throws ClassFormatException { String str; int i; byte tag = c.getTag(); switch (tag) { case Constants.CONSTANT_Class: i = ((ConstantClass) c).getNameIndex(); c = getConstant(i, Constants.CONSTANT_Utf8); str = Utility.compactClassName(((ConstantUtf8) c).getBytes(), false); break; case Constants.CONSTANT_String: i = ((ConstantString) c).getStringIndex(); c = getConstant(i, Constants.CONSTANT_Utf8); str = "\"" + escape(((ConstantUtf8) c).getBytes()) + "\""; break; case Constants.CONSTANT_Utf8: str = ((ConstantUtf8) c).getBytes(); break; case Constants.CONSTANT_Double: str = String.valueOf(((ConstantDouble) c).getBytes()); break; case Constants.CONSTANT_Float: str = String.valueOf(((ConstantFloat) c).getBytes()); break; case Constants.CONSTANT_Long: str = String.valueOf(((ConstantLong) c).getBytes()); break; case Constants.CONSTANT_Integer: str = String.valueOf(((ConstantInteger) c).getBytes()); break; case Constants.CONSTANT_NameAndType: str = (constantToString(((ConstantNameAndType) c).getNameIndex(), Constants.CONSTANT_Utf8) + " " + constantToString(((ConstantNameAndType) c).getSignatureIndex(), Constants.CONSTANT_Utf8)); break; case Constants.CONSTANT_InterfaceMethodref: case Constants.CONSTANT_Methodref: case Constants.CONSTANT_Fieldref: str = (constantToString(((ConstantCP) c).getClassIndex(), Constants.CONSTANT_Class) + "." + constantToString(((ConstantCP) c).getNameAndTypeIndex(), Constants.CONSTANT_NameAndType)); break; default: // Never reached throw new RuntimeException("Unknown constant type " + tag); } return str; }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public String constantToString( int index, byte tag ) throws ClassFormatException { Constant c = getConstant(index, tag); return constantToString(c); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public Constant getConstant( int index, byte tag ) throws ClassFormatException { Constant c; c = getConstant(index); if (c == null) { throw new ClassFormatException("Constant pool at index " + index + " is null."); } if (c.getTag() != tag) { throw new ClassFormatException("Expected class `" + Constants.CONSTANT_NAMES[tag] + "' at index " + index + " and got " + c); } return c; }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public String getConstantString( int index, byte tag ) throws ClassFormatException { Constant c; int i; c = getConstant(index, tag); /* This switch() is not that elegant, since the two classes have the * same contents, they just differ in the name of the index * field variable. * But we want to stick to the JVM naming conventions closely though * we could have solved these more elegantly by using the same * variable name or by subclassing. */ switch (tag) { case Constants.CONSTANT_Class: i = ((ConstantClass) c).getNameIndex(); break; case Constants.CONSTANT_String: i = ((ConstantString) c).getStringIndex(); break; default: throw new RuntimeException("getConstantString called with illegal tag " + tag); } // Finally get the string from the constant pool c = getConstant(i, Constants.CONSTANT_Utf8); return ((ConstantUtf8) c).getBytes(); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
public JavaClass parse() throws IOException, ClassFormatException { /****************** Read headers ********************************/ // Check magic tag of class file readID(); // Get compiler version readVersion(); /****************** Read constant pool and related **************/ // Read constant pool entries readConstantPool(); // Get class information readClassInfo(); // Get interface information, i.e., implemented interfaces readInterfaces(); /****************** Read class fields and methods ***************/ // Read class fields, i.e., the variables of the class readFields(); // Read class methods, i.e., the functions in the class readMethods(); // Read class attributes readAttributes(); // Check for unknown variables //Unknown[] u = Unknown.getUnknownAttributes(); //for(int i=0; i < u.length; i++) // System.err.println("WARNING: " + u[i]); // Everything should have been read now // if(file.available() > 0) { // int bytes = file.available(); // byte[] buf = new byte[bytes]; // file.read(buf); // if(!(is_zip && (buf.length == 1))) { // System.err.println("WARNING: Trailing garbage at end of " + file_name); // System.err.println(bytes + " extra bytes: " + Utility.toHexString(buf)); // } // } // Return the information we have gathered in a new object return new JavaClass(class_name_index, superclass_name_index, file_name, major, minor, access_flags, constant_pool, interfaces, fields, methods, attributes); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readAttributes() throws IOException, ClassFormatException { int attributes_count; attributes_count = file.readUnsignedShort(); attributes = new Attribute[attributes_count]; for (int i = 0; i < attributes_count; i++) { attributes[i] = Attribute.readAttribute(file, constant_pool); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readClassInfo() throws IOException, ClassFormatException { access_flags = file.readUnsignedShort(); /* Interfaces are implicitely abstract, the flag should be set * according to the JVM specification. */ if ((access_flags & Constants.ACC_INTERFACE) != 0) { access_flags |= Constants.ACC_ABSTRACT; } if (((access_flags & Constants.ACC_ABSTRACT) != 0) && ((access_flags & Constants.ACC_FINAL) != 0)) { throw new ClassFormatException("Class " + file_name + " can't be both final and abstract"); } class_name_index = file.readUnsignedShort(); superclass_name_index = file.readUnsignedShort(); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readConstantPool() throws IOException, ClassFormatException { constant_pool = new ConstantPool(file); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readFields() throws IOException, ClassFormatException { int fields_count; fields_count = file.readUnsignedShort(); fields = new Field[fields_count]; for (int i = 0; i < fields_count; i++) { fields[i] = new Field(file, constant_pool); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readID() throws IOException, ClassFormatException { int magic = 0xCAFEBABE; if (file.readInt() != magic) { throw new ClassFormatException(file_name + " is not a Java .class file"); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readInterfaces() throws IOException, ClassFormatException { int interfaces_count; interfaces_count = file.readUnsignedShort(); interfaces = new int[interfaces_count]; for (int i = 0; i < interfaces_count; i++) { interfaces[i] = file.readUnsignedShort(); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readMethods() throws IOException, ClassFormatException { int methods_count; methods_count = file.readUnsignedShort(); methods = new Method[methods_count]; for (int i = 0; i < methods_count; i++) { methods[i] = new Method(file, constant_pool); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readVersion() throws IOException, ClassFormatException { minor = file.readUnsignedShort(); major = file.readUnsignedShort(); }
// in java/org/apache/catalina/startup/ContextConfig.java
protected void processAnnotationsStream(InputStream is, WebXml fragment) throws ClassFormatException, IOException { ClassParser parser = new ClassParser(is, null); JavaClass clazz = parser.parse(); checkHandlesTypes(clazz); String className = clazz.getClassName(); AnnotationEntry[] annotationsEntries = clazz.getAnnotationEntries(); for (AnnotationEntry ae : annotationsEntries) { String type = ae.getAnnotationType(); if ("Ljavax/servlet/annotation/WebServlet;".equals(type)) { processAnnotationWebServlet(className, ae, fragment); }else if ("Ljavax/servlet/annotation/WebFilter;".equals(type)) { processAnnotationWebFilter(className, ae, fragment); }else if ("Ljavax/servlet/annotation/WebListener;".equals(type)) { fragment.addListener(className); } else { // Unknown annotation - ignore } } }
2
            
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) { log.error("Compilation error", exc); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassFormatException e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); }
0 0
unknown (Lib) ClassNotFoundException 17
            
// in java/org/apache/jasper/servlet/JasperLoader.java
Override public synchronized Class<?> loadClass(final String name, boolean resolve) throws ClassNotFoundException { Class<?> clazz = null; // (0) Check our previously loaded class cache clazz = findLoadedClass(name); if (clazz != null) { if (resolve) resolveClass(clazz); return (clazz); } // (.5) Permission to access this class when using a SecurityManager if (securityManager != null) { int dot = name.lastIndexOf('.'); if (dot >= 0) { try { // Do not call the security manager since by default, we grant that package. if (!"org.apache.jasper.runtime".equalsIgnoreCase(name.substring(0,dot))){ securityManager.checkPackageAccess(name.substring(0,dot)); } } catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; se.printStackTrace(); throw new ClassNotFoundException(error); } } } if( !name.startsWith(Constants.JSP_PACKAGE_NAME + '.') ) { // Class is not in org.apache.jsp, therefore, have our // parent load it clazz = parent.loadClass(name); if( resolve ) resolveClass(clazz); return clazz; } return findClass(name); }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
public static SSLImplementation getInstance() throws ClassNotFoundException { for (int i = 0; i < implementations.length; i++) { try { SSLImplementation impl = getInstance(implementations[i]); return impl; } catch (Exception e) { if (logger.isTraceEnabled()) logger.trace("Error creating " + implementations[i], e); } } // If we can't instantiate any of these throw new ClassNotFoundException("Can't find any SSL implementation"); }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
public static SSLImplementation getInstance(String className) throws ClassNotFoundException { if (className == null) return getInstance(); try { // Workaround for the J2SE 1.4.x classloading problem (under // Solaris). // Class.forName(..) fails without creating class using new. // This is an ugly workaround. if (JSSEImplementationClass.equals(className)) { return new org.apache.tomcat.util.net.jsse.JSSEImplementation(); } Class<?> clazz = Class.forName(className); return (SSLImplementation) clazz.newInstance(); } catch (Exception e) { if (logger.isDebugEnabled()) logger .debug("Error loading SSL Implementation " + className, e); throw new ClassNotFoundException( "Error loading SSL Implementation " + className + " :" + e.toString()); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public Class<?> findClass(String name) throws ClassNotFoundException { if (log.isDebugEnabled()) log.debug(" findClass(" + name + ")"); // Cannot load anything from local repositories if class loader is stopped if (!started) { throw new ClassNotFoundException(name); } // (1) Permission to define this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { if (log.isTraceEnabled()) log.trace(" securityManager.checkPackageDefinition"); securityManager.checkPackageDefinition(name.substring(0,i)); } catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); } } } // Ask our superclass to locate this class, if possible // (throws ClassNotFoundException if it is not found) Class<?> clazz = null; try { if (log.isTraceEnabled()) log.trace(" findClassInternal(" + name + ")"); if (hasExternalRepositories && searchExternalFirst) { try { clazz = super.findClass(name); } catch(ClassNotFoundException cnfe) { // Ignore - will search internal repositories next } catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if ((clazz == null)) { try { clazz = findClassInternal(name); } catch(ClassNotFoundException cnfe) { if (!hasExternalRepositories || searchExternalFirst) { throw cnfe; } } catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if ((clazz == null) && hasExternalRepositories && !searchExternalFirst) { try { clazz = super.findClass(name); } catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if (clazz == null) { if (log.isDebugEnabled()) log.debug(" --> Returning ClassNotFoundException"); throw new ClassNotFoundException(name); } } catch (ClassNotFoundException e) { if (log.isTraceEnabled()) log.trace(" --> Passing on ClassNotFoundException"); throw e; } // Return the class we have located if (log.isTraceEnabled()) log.debug(" Returning class " + clazz); if (log.isTraceEnabled()) { ClassLoader cl; if (Globals.IS_SECURITY_ENABLED){ cl = AccessController.doPrivileged( new PrivilegedGetClassLoader(clazz)); } else { cl = clazz.getClassLoader(); } log.debug(" Loaded by " + cl.toString()); } return (clazz); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (log.isDebugEnabled()) log.debug("loadClass(" + name + ", " + resolve + ")"); Class<?> clazz = null; // Log access to stopped classloader if (!started) { try { throw new IllegalStateException(); } catch (IllegalStateException e) { log.info(sm.getString("webappClassLoader.stopped", name), e); } } // (0) Check our previously loaded local class cache clazz = findLoadedClass0(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.1) Check our previously loaded class cache clazz = findLoadedClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.2) Try loading the class with the system class loader, to prevent // the webapp from overriding J2SE classes try { clazz = system.loadClass(name); if (clazz != null) { if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (0.5) Permission to access this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { securityManager.checkPackageAccess(name.substring(0,i)); } catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); } } } boolean delegateLoad = delegate || filter(name); // (1) Delegate to our parent if requested if (delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader1 " + parent); ClassLoader loader = parent; if (loader == null) loader = system; try { clazz = Class.forName(name, false, loader); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } // (2) Search local repositories if (log.isDebugEnabled()) log.debug(" Searching local repositories"); try { clazz = findClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from local repository"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (3) Delegate to parent unconditionally if (!delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader at end: " + parent); ClassLoader loader = parent; if (loader == null) loader = system; try { clazz = Class.forName(name, false, loader); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } throw new ClassNotFoundException(name); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
protected Class<?> findClassInternal(String name) throws ClassNotFoundException { if (!validate(name)) throw new ClassNotFoundException(name); String tempPath = name.replace('.', '/'); String classPath = tempPath + ".class"; ResourceEntry entry = null; if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, classPath); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, classPath); } if (entry == null) throw new ClassNotFoundException(name); Class<?> clazz = entry.loadedClass; if (clazz != null) return clazz; synchronized (this) { clazz = entry.loadedClass; if (clazz != null) return clazz; if (entry.binaryContent == null) throw new ClassNotFoundException(name); // Looking up the package String packageName = null; int pos = name.lastIndexOf('.'); if (pos != -1) packageName = name.substring(0, pos); Package pkg = null; if (packageName != null) { pkg = getPackage(packageName); // Define the package (if null) if (pkg == null) { try { if (entry.manifest == null) { definePackage(packageName, null, null, null, null, null, null, null); } else { definePackage(packageName, entry.manifest, entry.codeBase); } } catch (IllegalArgumentException e) { // Ignore: normal error due to dual definition of package } pkg = getPackage(packageName); } } if (securityManager != null) { // Checking sealing if (pkg != null) { boolean sealCheck = true; if (pkg.isSealed()) { sealCheck = pkg.isSealed(entry.codeBase); } else { sealCheck = (entry.manifest == null) || !isPackageSealed(packageName, entry.manifest); } if (!sealCheck) throw new SecurityException ("Sealing violation loading " + name + " : Package " + packageName + " is sealed."); } } try { clazz = defineClass(name, entry.binaryContent, 0, entry.binaryContent.length, new CodeSource(entry.codeBase, entry.certificates)); } catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); } entry.loadedClass = clazz; entry.binaryContent = null; entry.source = null; entry.codeBase = null; entry.manifest = null; entry.certificates = null; } return clazz; }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
Override protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { ClassLoader latestLoader = (classLoaders!=null && classLoaders.length==0)?null:classLoaders[0]; ClassLoader nonPublicLoader = null; boolean hasNonPublicInterface = false; // define proxy in class loader of non-public interface(s), if any Class<?>[] classObjs = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { Class<?> cl = this.resolveClass(interfaces[i]); if (latestLoader==null) latestLoader = cl.getClassLoader(); if ((cl.getModifiers() & Modifier.PUBLIC) == 0) { if (hasNonPublicInterface) { if (nonPublicLoader != cl.getClassLoader()) { throw new IllegalAccessError( "conflicting non-public interface class loaders"); } } else { nonPublicLoader = cl.getClassLoader(); hasNonPublicInterface = true; } } classObjs[i] = cl; } try { return Proxy.getProxyClass(hasNonPublicInterface ? nonPublicLoader : latestLoader, classObjs); } catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); } }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
public Class<?> findExternalClass(String name) throws ClassNotFoundException { ClassNotFoundException cnfe = null; for (int i=0; i<classLoaders.length; i++ ) { try { Class<?> clazz = Class.forName(name, false, classLoaders[i]); return clazz; } catch ( ClassNotFoundException x ) { cnfe = x; } } if ( cnfe != null ) throw cnfe; else throw new ClassNotFoundException(name); }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
Override protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { Class<?>[] cinterfaces = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) cinterfaces[i] = classLoader.loadClass(interfaces[i]); try { return Proxy.getProxyClass(classLoader, cinterfaces); } catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); } }
9
            
// in java/org/apache/jasper/servlet/JasperLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; se.printStackTrace(); throw new ClassNotFoundException(error); }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
catch (Exception e) { if (logger.isDebugEnabled()) logger .debug("Error loading SSL Implementation " + className, e); throw new ClassNotFoundException( "Error loading SSL Implementation " + className + " :" + e.toString()); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); }
63
            
// in java/org/apache/jasper/compiler/JspUtil.java
public static Class<?> toClass(String type, ClassLoader loader) throws ClassNotFoundException { Class<?> c = null; int i0 = type.indexOf('['); int dims = 0; if (i0 > 0) { // This is an array. Count the dimensions for (int i = 0; i < type.length(); i++) { if (type.charAt(i) == '[') { dims++; } } type = type.substring(0, i0); } if ("boolean".equals(type)) { c = boolean.class; } else if ("char".equals(type)) { c = char.class; } else if ("byte".equals(type)) { c = byte.class; } else if ("short".equals(type)) { c = short.class; } else if ("int".equals(type)) { c = int.class; } else if ("long".equals(type)) { c = long.class; } else if ("float".equals(type)) { c = float.class; } else if ("double".equals(type)) { c = double.class; } else if ("void".equals(type)) { c = void.class; } else if (type.indexOf('[') < 0) { c = loader.loadClass(type); } if (dims == 0) { return c; } if (dims == 1) { return java.lang.reflect.Array.newInstance(c, 1).getClass(); } // Array of more than i dimension return java.lang.reflect.Array.newInstance(c, new int[dims]).getClass(); }
// in java/org/apache/jasper/servlet/JasperLoader.java
Override public Class<?> loadClass(String name) throws ClassNotFoundException { return (loadClass(name, false)); }
// in java/org/apache/jasper/servlet/JasperLoader.java
Override public synchronized Class<?> loadClass(final String name, boolean resolve) throws ClassNotFoundException { Class<?> clazz = null; // (0) Check our previously loaded class cache clazz = findLoadedClass(name); if (clazz != null) { if (resolve) resolveClass(clazz); return (clazz); } // (.5) Permission to access this class when using a SecurityManager if (securityManager != null) { int dot = name.lastIndexOf('.'); if (dot >= 0) { try { // Do not call the security manager since by default, we grant that package. if (!"org.apache.jasper.runtime".equalsIgnoreCase(name.substring(0,dot))){ securityManager.checkPackageAccess(name.substring(0,dot)); } } catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; se.printStackTrace(); throw new ClassNotFoundException(error); } } } if( !name.startsWith(Constants.JSP_PACKAGE_NAME + '.') ) { // Class is not in org.apache.jsp, therefore, have our // parent load it clazz = parent.loadClass(name); if( resolve ) resolveClass(clazz); return clazz; } return findClass(name); }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.mark = in.readUTF(); this.target = (MethodExpression) in.readObject(); }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.mark = in.readUTF(); this.target = (ValueExpression) in.readObject(); }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
public static SSLImplementation getInstance() throws ClassNotFoundException { for (int i = 0; i < implementations.length; i++) { try { SSLImplementation impl = getInstance(implementations[i]); return impl; } catch (Exception e) { if (logger.isTraceEnabled()) logger.trace("Error creating " + implementations[i], e); } } // If we can't instantiate any of these throw new ClassNotFoundException("Can't find any SSL implementation"); }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
public static SSLImplementation getInstance(String className) throws ClassNotFoundException { if (className == null) return getInstance(); try { // Workaround for the J2SE 1.4.x classloading problem (under // Solaris). // Class.forName(..) fails without creating class using new. // This is an ugly workaround. if (JSSEImplementationClass.equals(className)) { return new org.apache.tomcat.util.net.jsse.JSSEImplementation(); } Class<?> clazz = Class.forName(className); return (SSLImplementation) clazz.newInstance(); } catch (Exception e) { if (logger.isDebugEnabled()) logger .debug("Error loading SSL Implementation " + className, e); throw new ClassNotFoundException( "Error loading SSL Implementation " + className + " :" + e.toString()); } }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // read values in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; }
// in java/org/apache/el/lang/FunctionMapperImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.prefix = in.readUTF(); if ("".equals(this.prefix)) this.prefix = null; this.localName = in.readUTF(); this.owner = in.readUTF(); this.name = in.readUTF(); this.types = (String[]) in.readObject(); }
// in java/org/apache/el/MethodExpressionImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.expr = in.readUTF(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } this.paramTypes = ReflectionUtil.toTypeArray(((String[]) in .readObject())); this.fnMapper = (FunctionMapper) in.readObject(); this.varMapper = (VariableMapper) in.readObject(); }
// in java/org/apache/el/MethodExpressionLiteral.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.expr = in.readUTF(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } this.paramTypes = ReflectionUtil.toTypeArray(((String[]) in .readObject())); }
// in java/org/apache/el/ValueExpressionLiteral.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.value = in.readObject(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } }
// in java/org/apache/el/ValueExpressionImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.expr = in.readUTF(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } this.fnMapper = (FunctionMapper) in.readObject(); this.varMapper = (VariableMapper) in.readObject(); }
// in java/org/apache/el/util/ReflectionUtil.java
public static Class<?> forName(String name) throws ClassNotFoundException { if (null == name || "".equals(name)) { return null; } Class<?> c = forNamePrimitive(name); if (c == null) { if (name.endsWith("[]")) { String nc = name.substring(0, name.length() - 2); c = Class.forName(nc, true, Thread.currentThread().getContextClassLoader()); c = Array.newInstance(c, 0).getClass(); } else { c = Class.forName(name, true, Thread.currentThread().getContextClassLoader()); } } return c; }
// in java/org/apache/el/util/ReflectionUtil.java
public static Class<?>[] toTypeArray(String[] s) throws ClassNotFoundException { if (s == null) return null; Class<?>[] c = new Class[s.length]; for (int i = 0; i < s.length; i++) { c[i] = forName(s[i]); } return c; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public Class<?> findClass(String name) throws ClassNotFoundException { if (log.isDebugEnabled()) log.debug(" findClass(" + name + ")"); // Cannot load anything from local repositories if class loader is stopped if (!started) { throw new ClassNotFoundException(name); } // (1) Permission to define this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { if (log.isTraceEnabled()) log.trace(" securityManager.checkPackageDefinition"); securityManager.checkPackageDefinition(name.substring(0,i)); } catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); } } } // Ask our superclass to locate this class, if possible // (throws ClassNotFoundException if it is not found) Class<?> clazz = null; try { if (log.isTraceEnabled()) log.trace(" findClassInternal(" + name + ")"); if (hasExternalRepositories && searchExternalFirst) { try { clazz = super.findClass(name); } catch(ClassNotFoundException cnfe) { // Ignore - will search internal repositories next } catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if ((clazz == null)) { try { clazz = findClassInternal(name); } catch(ClassNotFoundException cnfe) { if (!hasExternalRepositories || searchExternalFirst) { throw cnfe; } } catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if ((clazz == null) && hasExternalRepositories && !searchExternalFirst) { try { clazz = super.findClass(name); } catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if (clazz == null) { if (log.isDebugEnabled()) log.debug(" --> Returning ClassNotFoundException"); throw new ClassNotFoundException(name); } } catch (ClassNotFoundException e) { if (log.isTraceEnabled()) log.trace(" --> Passing on ClassNotFoundException"); throw e; } // Return the class we have located if (log.isTraceEnabled()) log.debug(" Returning class " + clazz); if (log.isTraceEnabled()) { ClassLoader cl; if (Globals.IS_SECURITY_ENABLED){ cl = AccessController.doPrivileged( new PrivilegedGetClassLoader(clazz)); } else { cl = clazz.getClassLoader(); } log.debug(" Loaded by " + cl.toString()); } return (clazz); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public Class<?> loadClass(String name) throws ClassNotFoundException { return (loadClass(name, false)); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (log.isDebugEnabled()) log.debug("loadClass(" + name + ", " + resolve + ")"); Class<?> clazz = null; // Log access to stopped classloader if (!started) { try { throw new IllegalStateException(); } catch (IllegalStateException e) { log.info(sm.getString("webappClassLoader.stopped", name), e); } } // (0) Check our previously loaded local class cache clazz = findLoadedClass0(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.1) Check our previously loaded class cache clazz = findLoadedClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.2) Try loading the class with the system class loader, to prevent // the webapp from overriding J2SE classes try { clazz = system.loadClass(name); if (clazz != null) { if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (0.5) Permission to access this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { securityManager.checkPackageAccess(name.substring(0,i)); } catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); } } } boolean delegateLoad = delegate || filter(name); // (1) Delegate to our parent if requested if (delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader1 " + parent); ClassLoader loader = parent; if (loader == null) loader = system; try { clazz = Class.forName(name, false, loader); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } // (2) Search local repositories if (log.isDebugEnabled()) log.debug(" Searching local repositories"); try { clazz = findClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from local repository"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (3) Delegate to parent unconditionally if (!delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader at end: " + parent); ClassLoader loader = parent; if (loader == null) loader = system; try { clazz = Class.forName(name, false, loader); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } throw new ClassNotFoundException(name); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
protected Class<?> findClassInternal(String name) throws ClassNotFoundException { if (!validate(name)) throw new ClassNotFoundException(name); String tempPath = name.replace('.', '/'); String classPath = tempPath + ".class"; ResourceEntry entry = null; if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, classPath); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, classPath); } if (entry == null) throw new ClassNotFoundException(name); Class<?> clazz = entry.loadedClass; if (clazz != null) return clazz; synchronized (this) { clazz = entry.loadedClass; if (clazz != null) return clazz; if (entry.binaryContent == null) throw new ClassNotFoundException(name); // Looking up the package String packageName = null; int pos = name.lastIndexOf('.'); if (pos != -1) packageName = name.substring(0, pos); Package pkg = null; if (packageName != null) { pkg = getPackage(packageName); // Define the package (if null) if (pkg == null) { try { if (entry.manifest == null) { definePackage(packageName, null, null, null, null, null, null, null); } else { definePackage(packageName, entry.manifest, entry.codeBase); } } catch (IllegalArgumentException e) { // Ignore: normal error due to dual definition of package } pkg = getPackage(packageName); } } if (securityManager != null) { // Checking sealing if (pkg != null) { boolean sealCheck = true; if (pkg.isSealed()) { sealCheck = pkg.isSealed(entry.codeBase); } else { sealCheck = (entry.manifest == null) || !isPackageSealed(packageName, entry.manifest); } if (!sealCheck) throw new SecurityException ("Sealing violation loading " + name + " : Package " + packageName + " is sealed."); } } try { clazz = defineClass(name, entry.binaryContent, 0, entry.binaryContent.length, new CodeSource(entry.codeBase, entry.certificates)); } catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); } entry.loadedClass = clazz; entry.binaryContent = null; entry.source = null; entry.codeBase = null; entry.manifest = null; entry.certificates = null; } return clazz; }
// in java/org/apache/catalina/tribes/group/RpcMessage.java
Override public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException { reply = in.readBoolean(); int length = in.readInt(); uuid = new byte[length]; in.readFully(uuid); length = in.readInt(); rpcId = new byte[length]; in.readFully(rpcId); message = (Serializable)in.readObject(); }
// in java/org/apache/catalina/tribes/group/RpcMessage.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { reply = true; int length = in.readInt(); uuid = new byte[length]; in.readFully(uuid); length = in.readInt(); rpcId = new byte[length]; in.readFully(rpcId); }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data) throws IOException, ClassNotFoundException, ClassCastException { return deserialize(data,0,data.length); }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data, int offset, int length) throws IOException, ClassNotFoundException, ClassCastException { return deserialize(data,offset,length,null); }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data, int offset, int length, ClassLoader[] cls) throws IOException, ClassNotFoundException, ClassCastException { invokecount.addAndGet(1); Object message = null; if ( cls == null ) cls = new ClassLoader[0]; if (data != null && length > 0) { InputStream instream = new ByteArrayInputStream(data,offset,length); ObjectInputStream stream = null; stream = (cls.length>0)? new ReplicationStream(instream,cls):new ObjectInputStream(instream); message = stream.readObject(); instream.close(); stream.close(); } if ( message == null ) { return null; } else if (message instanceof Serializable) return (Serializable) message; else { throw new ClassCastException("Message has the wrong class. It should implement Serializable, instead it is:"+message.getClass().getName()); } }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
Override public Class<?> resolveClass(ObjectStreamClass classDesc) throws ClassNotFoundException, IOException { String name = classDesc.getName(); try { return resolveClass(name); } catch (ClassNotFoundException e) { return super.resolveClass(classDesc); } }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
public Class<?> resolveClass(String name) throws ClassNotFoundException { boolean tryRepFirst = name.startsWith("org.apache.catalina.tribes"); try { if (tryRepFirst) return findReplicationClass(name); else return findExternalClass(name); } catch (Exception x) { if (tryRepFirst) return findExternalClass(name); else return findReplicationClass(name); } }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
Override protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { ClassLoader latestLoader = (classLoaders!=null && classLoaders.length==0)?null:classLoaders[0]; ClassLoader nonPublicLoader = null; boolean hasNonPublicInterface = false; // define proxy in class loader of non-public interface(s), if any Class<?>[] classObjs = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { Class<?> cl = this.resolveClass(interfaces[i]); if (latestLoader==null) latestLoader = cl.getClassLoader(); if ((cl.getModifiers() & Modifier.PUBLIC) == 0) { if (hasNonPublicInterface) { if (nonPublicLoader != cl.getClassLoader()) { throw new IllegalAccessError( "conflicting non-public interface class loaders"); } } else { nonPublicLoader = cl.getClassLoader(); hasNonPublicInterface = true; } } classObjs[i] = cl; } try { return Proxy.getProxyClass(hasNonPublicInterface ? nonPublicLoader : latestLoader, classObjs); } catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); } }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
public Class<?> findReplicationClass(String name) throws ClassNotFoundException { Class<?> clazz = Class.forName(name, false, getClass().getClassLoader()); return clazz; }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
public Class<?> findExternalClass(String name) throws ClassNotFoundException { ClassNotFoundException cnfe = null; for (int i=0; i<classLoaders.length; i++ ) { try { Class<?> clazz = Class.forName(name, false, classLoaders[i]); return clazz; } catch ( ClassNotFoundException x ) { cnfe = x; } } if ( cnfe != null ) throw cnfe; else throw new ClassNotFoundException(name); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public void deserialize(ClassLoader[] cls) throws IOException, ClassNotFoundException { key(cls); value(cls); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public Serializable key(ClassLoader[] cls) throws IOException, ClassNotFoundException { if ( key!=null ) return key; if ( keydata == null || keydata.length == 0 ) return null; key = XByteBuffer.deserialize(keydata,0,keydata.length,cls); keydata = null; return key; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public Serializable value(ClassLoader[] cls) throws IOException, ClassNotFoundException { if ( value!=null ) return value; if ( valuedata == null || valuedata.length == 0 ) return null; value = XByteBuffer.deserialize(valuedata,0,valuedata.length,cls); valuedata = null; return value; }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { int length = in.readInt(); byte[] message = new byte[length]; in.readFully(message); getMember(message,this); }
// in java/org/apache/catalina/session/StandardManager.java
Override public void load() throws ClassNotFoundException, IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ AccessController.doPrivileged( new PrivilegedDoLoad() ); } catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof ClassNotFoundException){ throw (ClassNotFoundException)exception; } else if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in load() " + exception); } } else { doLoad(); } }
// in java/org/apache/catalina/session/StandardManager.java
protected void doLoad() throws ClassNotFoundException, IOException { if (log.isDebugEnabled()) log.debug("Start: Loading persisted sessions"); // Initialize our internal data structures sessions.clear(); // Open an input stream to the specified pathname, if any File file = file(); if (file == null) return; if (log.isDebugEnabled()) log.debug(sm.getString("standardManager.loading", pathname)); FileInputStream fis = null; BufferedInputStream bis = null; ObjectInputStream ois = null; Loader loader = null; ClassLoader classLoader = null; try { fis = new FileInputStream(file.getAbsolutePath()); bis = new BufferedInputStream(fis); if (container != null) loader = container.getLoader(); if (loader != null) classLoader = loader.getClassLoader(); if (classLoader != null) { if (log.isDebugEnabled()) log.debug("Creating custom object input stream for class loader "); ois = new CustomObjectInputStream(bis, classLoader); } else { if (log.isDebugEnabled()) log.debug("Creating standard object input stream"); ois = new ObjectInputStream(bis); } } catch (FileNotFoundException e) { if (log.isDebugEnabled()) log.debug("No persisted data file found"); return; } catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } throw e; } // Load the previously unloaded active sessions synchronized (sessions) { try { Integer count = (Integer) ois.readObject(); int n = count.intValue(); if (log.isDebugEnabled()) log.debug("Loading " + n + " persisted sessions"); for (int i = 0; i < n; i++) { StandardSession session = getNewSession(); session.readObjectData(ois); session.setManager(this); sessions.put(session.getIdInternal(), session); session.activate(); if (!session.isValidInternal()) { // If session is already invalid, // expire session to prevent memory leak. session.setValid(true); session.expire(); } sessionCounter++; } } catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; } catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; } finally { // Close the input stream try { ois.close(); } catch (IOException f) { // ignored } // Delete the persistent storage file if (file.exists() ) file.delete(); } } if (log.isDebugEnabled()) log.debug("Finish: Loading persisted sessions"); }
// in java/org/apache/catalina/session/JDBCStore.java
Override public Session load(String id) throws ClassNotFoundException, IOException { ResultSet rst = null; StandardSession _session = null; Loader loader = null; ClassLoader classLoader = null; ObjectInputStream ois = null; BufferedInputStream bis = null; Container container = manager.getContainer(); synchronized (this) { int numberOfTries = 2; while (numberOfTries > 0) { Connection _conn = getConnection(); if (_conn == null) { return (null); } try { if (preparedLoadSql == null) { String loadSql = "SELECT " + sessionIdCol + ", " + sessionDataCol + " FROM " + sessionTable + " WHERE " + sessionIdCol + " = ? AND " + sessionAppCol + " = ?"; preparedLoadSql = _conn.prepareStatement(loadSql); } preparedLoadSql.setString(1, id); preparedLoadSql.setString(2, getName()); rst = preparedLoadSql.executeQuery(); if (rst.next()) { bis = new BufferedInputStream(rst.getBinaryStream(2)); if (container != null) { loader = container.getLoader(); } if (loader != null) { classLoader = loader.getClassLoader(); } if (classLoader != null) { ois = new CustomObjectInputStream(bis, classLoader); } else { ois = new ObjectInputStream(bis); } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName() + ".loading", id, sessionTable)); } _session = (StandardSession) manager.createEmptySession(); _session.readObjectData(ois); _session.setManager(manager); } else if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(getStoreName() + ": No persisted data object found"); } // Break out after the finally block numberOfTries = 0; } catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); } finally { try { if (rst != null) { rst.close(); } } catch (SQLException e) { // Ignore } if (ois != null) { try { ois.close(); } catch (IOException e) { // Ignore } } release(_conn); } numberOfTries--; } } return (_session); }
// in java/org/apache/catalina/session/FileStore.java
Override public Session load(String id) throws ClassNotFoundException, IOException { // Open an input stream to the specified pathname, if any File file = file(id); if (file == null) { return (null); } if (! file.exists()) { return (null); } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName()+".loading", id, file.getAbsolutePath())); } FileInputStream fis = null; BufferedInputStream bis = null; ObjectInputStream ois = null; Loader loader = null; ClassLoader classLoader = null; try { fis = new FileInputStream(file.getAbsolutePath()); bis = new BufferedInputStream(fis); Container container = manager.getContainer(); if (container != null) loader = container.getLoader(); if (loader != null) classLoader = loader.getClassLoader(); if (classLoader != null) ois = new CustomObjectInputStream(bis, classLoader); else ois = new ObjectInputStream(bis); } catch (FileNotFoundException e) { if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug("No persisted data file found"); return (null); } catch (IOException e) { if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } throw e; } try { StandardSession session = (StandardSession) manager.createEmptySession(); session.readObjectData(ois); session.setManager(manager); return (session); } finally { // Close the input stream try { ois.close(); } catch (IOException f) { // Ignore } } }
// in java/org/apache/catalina/session/StandardSession.java
public void readObjectData(ObjectInputStream stream) throws ClassNotFoundException, IOException { readObject(stream); }
// in java/org/apache/catalina/session/StandardSession.java
protected void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException { // Deserialize the scalar instance variables (except Manager) authType = null; // Transient only creationTime = ((Long) stream.readObject()).longValue(); lastAccessedTime = ((Long) stream.readObject()).longValue(); maxInactiveInterval = ((Integer) stream.readObject()).intValue(); isNew = ((Boolean) stream.readObject()).booleanValue(); isValid = ((Boolean) stream.readObject()).booleanValue(); thisAccessedTime = ((Long) stream.readObject()).longValue(); principal = null; // Transient only // setId((String) stream.readObject()); id = (String) stream.readObject(); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug ("readObject() loading session " + id); // Deserialize the attribute count and attribute values if (attributes == null) attributes = new ConcurrentHashMap<String, Object>(); int n = ((Integer) stream.readObject()).intValue(); boolean isValidSave = isValid; isValid = true; for (int i = 0; i < n; i++) { String name = (String) stream.readObject(); Object value = stream.readObject(); if ((value instanceof String) && (value.equals(NOT_SERIALIZED))) continue; if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug(" loading attribute '" + name + "' with value '" + value + "'"); attributes.put(name, value); } isValid = isValidSave; if (listeners == null) { listeners = new ArrayList<SessionListener>(); } if (notes == null) { notes = new Hashtable<String, Object>(); } }
// in java/org/apache/catalina/ha/session/SerializablePrincipal.java
public static GenericPrincipal readPrincipal(ObjectInput in) throws IOException, ClassNotFoundException { String name = in.readUTF(); boolean hasPwd = in.readBoolean(); String pwd = null; if ( hasPwd ) pwd = in.readUTF(); int size = in.readInt(); String[] roles = new String[size]; for ( int i=0; i<size; i++ ) roles[i] = in.readUTF(); Principal userPrincipal = null; boolean hasUserPrincipal = in.readBoolean(); if (hasUserPrincipal) { try { userPrincipal = (Principal) in.readObject(); } catch (ClassNotFoundException e) { log.error(sm.getString( "serializablePrincipal.readPrincipal.cnfe"), e); throw e; } } return new GenericPrincipal(name,pwd,Arrays.asList(roles), userPrincipal); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void applyDiff(byte[] diff, int offset, int length) throws IOException, ClassNotFoundException { try { lock(); ReplicationStream stream = ( (ClusterManager) getManager()).getReplicationStream(diff, offset, length); ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); try { ClassLoader[] loaders = getClassLoaders(); if (loaders != null && loaders.length > 0) Thread.currentThread().setContextClassLoader(loaders[0]); getDeltaRequest().readExternal(stream); getDeltaRequest().execute(this, ((ClusterManager)getManager()).isNotifyListenersOnReplication()); } finally { Thread.currentThread().setContextClassLoader(contextLoader); } }finally { unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException { try { lock(); readObjectData(in); }finally{ unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void readObjectData(ObjectInputStream stream) throws ClassNotFoundException, IOException { readObject((ObjectInput)stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
public void readObjectData(ObjectInput stream) throws ClassNotFoundException, IOException { readObject(stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override protected void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException { readObject((ObjectInput)stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
private void readObject(ObjectInput stream) throws ClassNotFoundException, IOException { // Deserialize the scalar instance variables (except Manager) authType = null; // Transient only creationTime = ( (Long) stream.readObject()).longValue(); lastAccessedTime = ( (Long) stream.readObject()).longValue(); maxInactiveInterval = ( (Integer) stream.readObject()).intValue(); isNew = ( (Boolean) stream.readObject()).booleanValue(); isValid = ( (Boolean) stream.readObject()).booleanValue(); thisAccessedTime = ( (Long) stream.readObject()).longValue(); version = ( (Long) stream.readObject()).longValue(); boolean hasPrincipal = stream.readBoolean(); principal = null; if (hasPrincipal) { principal = SerializablePrincipal.readPrincipal(stream); } // setId((String) stream.readObject()); id = (String) stream.readObject(); if (log.isDebugEnabled()) log.debug(sm.getString("deltaSession.readSession", id)); // Deserialize the attribute count and attribute values if (attributes == null) attributes = new ConcurrentHashMap<String, Object>(); int n = ( (Integer) stream.readObject()).intValue(); boolean isValidSave = isValid; isValid = true; for (int i = 0; i < n; i++) { String name = (String) stream.readObject(); Object value = stream.readObject(); if ( (value instanceof String) && (value.equals(NOT_SERIALIZED))) continue; attributes.put(name, value); } isValid = isValidSave; if (listeners == null) { ArrayList<SessionListener> arrayList = new ArrayList<SessionListener>(); listeners = arrayList; } if (notes == null) { notes = new Hashtable<String,Object>(); } activate(); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
Override public void readExternal(java.io.ObjectInput in) throws IOException,ClassNotFoundException { //sessionId - String //recordAll - boolean //size - int //AttributeInfo - in an array reset(); sessionId = in.readUTF(); recordAllActions = in.readBoolean(); int cnt = in.readInt(); if (actions == null) actions = new LinkedList<AttributeInfo>(); else actions.clear(); for (int i = 0; i < cnt; i++) { AttributeInfo info = null; if (this.actionPool.size() > 0) { try { info = actionPool.removeFirst(); } catch ( Exception x ) { log.error("Unable to remove element",x); info = new AttributeInfo(); } } else { info = new AttributeInfo(); } info.readExternal(in); actions.addLast(info); }//for }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
Override public void readExternal(java.io.ObjectInput in ) throws IOException,ClassNotFoundException { //type - int //action - int //name - String //hasvalue - boolean //value - object type = in.readInt(); action = in.readInt(); name = in.readUTF(); boolean hasValue = in.readBoolean(); if ( hasValue ) value = in.readObject(); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected DeltaRequest deserializeDeltaRequest(DeltaSession session, byte[] data) throws ClassNotFoundException, IOException { try { session.lock(); ReplicationStream ois = getReplicationStream(data); session.getDeltaRequest().readExternal(ois); ois.close(); return session.getDeltaRequest(); }finally { session.unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void deserializeSessions(byte[] data) throws ClassNotFoundException,IOException { // Initialize our internal data structures //sessions.clear(); //should not do this // Open an input stream to the specified pathname, if any ClassLoader originalLoader = Thread.currentThread().getContextClassLoader(); ObjectInputStream ois = null; // Load the previously unloaded active sessions try { ois = getReplicationStream(data); Integer count = (Integer) ois.readObject(); int n = count.intValue(); for (int i = 0; i < n; i++) { DeltaSession session = (DeltaSession) createEmptySession(); session.readObjectData(ois); session.setManager(this); session.setValid(true); session.setPrimarySession(false); //in case the nodes in the cluster are out of //time synch, this will make sure that we have the //correct timestamp, isValid returns true, cause // accessCount=1 session.access(); //make sure that the session gets ready to expire if // needed session.setAccessCount(0); session.resetDeltaRequest(); // FIXME How inform other session id cache like SingleSignOn // increment sessionCounter to correct stats report if (findSession(session.getIdInternal()) == null ) { sessionCounter++; } else { sessionReplaceCounter++; // FIXME better is to grap this sessions again ! if (log.isWarnEnabled()) log.warn(sm.getString("deltaManager.loading.existing.session",session.getIdInternal())); } add(session); if (notifySessionListenersOnReplication) { session.tellNew(); } } } catch (ClassNotFoundException e) { log.error(sm.getString("deltaManager.loading.cnfe", e), e); throw e; } catch (IOException e) { log.error(sm.getString("deltaManager.loading.ioe", e), e); throw e; } finally { // Close the input stream try { if (ois != null) ois.close(); } catch (IOException f) { // ignored } ois = null; if (originalLoader != null) Thread.currentThread().setContextClassLoader(originalLoader); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleSESSION_DELTA(SessionMessage msg, Member sender) throws IOException, ClassNotFoundException { counterReceive_EVT_SESSION_DELTA++; byte[] delta = msg.getSession(); DeltaSession session = (DeltaSession) findSession(msg.getSessionID()); if (session != null) { if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.delta",getName(), msg.getSessionID())); try { session.lock(); DeltaRequest dreq = deserializeDeltaRequest(session, delta); dreq.execute(session, isNotifyListenersOnReplication()); session.setPrimarySession(false); }finally { session.unlock(); } } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleALL_SESSION_DATA(SessionMessage msg,Member sender) throws ClassNotFoundException, IOException { counterReceive_EVT_ALL_SESSION_DATA++; if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataBegin",getName())); byte[] data = msg.getSession(); deserializeSessions(data); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataAfter",getName())); //stateTransferred = true; }
// in java/org/apache/catalina/core/AprLifecycleListener.java
private static void terminateAPR() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { String methodName = "terminate"; Method method = Class.forName("org.apache.tomcat.jni.Library") .getMethod(methodName, (Class [])null); method.invoke(null, (Object []) null); aprAvailable = false; aprInitialized = false; sslInitialized = false; // Well we cleaned the pool in terminate. sslAvailable = false; // Well we cleaned the pool in terminate. fipsModeActive = false; }
// in java/org/apache/catalina/core/AprLifecycleListener.java
private static void initializeSSL() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { if ("off".equalsIgnoreCase(SSLEngine)) { return; } if (sslInitialized) { //only once per VM return; } sslInitialized = true; String methodName = "randSet"; Class<?> paramTypes[] = new Class[1]; paramTypes[0] = String.class; Object paramValues[] = new Object[1]; paramValues[0] = SSLRandomSeed; Class<?> clazz = Class.forName("org.apache.tomcat.jni.SSL"); Method method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); methodName = "initialize"; paramValues[0] = "on".equalsIgnoreCase(SSLEngine)?null:SSLEngine; method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); if("on".equalsIgnoreCase(FIPSMode)) { log.info(sm.getString("aprListener.initializingFIPS")); int result = SSL.fipsModeSet(1); // success is defined as return value = 1 if(1 == result) { fipsModeActive = true; log.info(sm.getString("aprListener.initializeFIPSSuccess")); } else { // This case should be handled by the native method, // but we'll make absolutely sure, here. String message = sm.getString("aprListener.initializeFIPSFailed"); log.error(message); throw new IllegalStateException(message); } } log.info(sm.getString("aprListener.initializedOpenSSL", SSL.versionString())); sslAvailable = true; }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
Filter getFilter() throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { // Return the existing filter instance, if any if (this.filter != null) return (this.filter); // Identify the class loader we will be using String filterClass = filterDef.getFilterClass(); this.filter = (Filter) getInstanceManager().newInstance(filterClass); initFilter(); return (this.filter); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
void setFilterDef(FilterDef filterDef) throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { this.filterDef = filterDef; if (filterDef == null) { // Release any previously allocated filter instance if (this.filter != null){ if (Globals.IS_SECURITY_ENABLED) { try{ SecurityUtil.doAsPrivilege("destroy", filter); } catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); } SecurityUtil.remove(filter); } else { filter.destroy(); } if (!context.getIgnoreAnnotations()) { try { ((StandardContext) context).getInstanceManager().destroyInstance(this.filter); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); } } } this.filter = null; } else { // Allocate a new filter instance if necessary if (filterDef.getFilter() == null) { getFilter(); } } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { Class<?> clazz = loadClassMaybePrivileged(className, classLoader); return newInstance(clazz.newInstance(), clazz); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(final String className, final ClassLoader classLoader) throws IllegalAccessException, NamingException, InvocationTargetException, InstantiationException, ClassNotFoundException { Class<?> clazz = classLoader.loadClass(className); return newInstance(clazz.newInstance(), clazz); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected Class<?> loadClassMaybePrivileged(final String className, final ClassLoader classLoader) throws ClassNotFoundException { Class<?> clazz; if (SecurityUtil.isPackageProtectionEnabled()) { try { clazz = AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() { @Override public Class<?> run() throws Exception { return loadClass(className, classLoader); } }); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected Class<?> loadClass(String className, ClassLoader classLoader) throws ClassNotFoundException { if (className.startsWith("org.apache.catalina")) { return containerClassLoader.loadClass(className); } try { Class<?> clazz = containerClassLoader.loadClass(className); if (ContainerServlet.class.isAssignableFrom(clazz)) { return clazz; } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } return classLoader.loadClass(className); }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
Override public Class<?> resolveClass(ObjectStreamClass classDesc) throws ClassNotFoundException, IOException { try { return Class.forName(classDesc.getName(), false, classLoader); } catch (ClassNotFoundException e) { try { // Try also the superclass because of primitive types return super.resolveClass(classDesc); } catch (ClassNotFoundException e2) { // Rethrow original exception, as it can have more information // about why the class was not found. BZ 48007 throw e; } } }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
Override protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { Class<?>[] cinterfaces = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) cinterfaces[i] = classLoader.loadClass(interfaces[i]); try { return Proxy.getProxyClass(classLoader, cinterfaces); } catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); } }
70
            
// in java/org/apache/jasper/compiler/BeanRepository.java
catch (ClassNotFoundException ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
catch (ClassNotFoundException e) { throw new JasperException(e); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError (n, "jsp.error.unknown_attribute_type", tldAttr.getName(), expectedType); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError("jsp.error.function.classnotfound", n .getFunctionInfo().getFunctionClass(), n .getPrefix() + ':' + n.getName(), e.getMessage()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ClassNotFoundException e) { err.jspError("jsp.error.signature.classnotfound", paramTypes[i], n.getPrefix() + ':' + n.getName(), e.getMessage()); }
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch (ClassNotFoundException ex) { throw new IllegalStateException(ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (ClassNotFoundException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.error.compiler"), e); } }
// in java/org/apache/jasper/JspCompilationContext.java
catch (ClassNotFoundException cex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.load"), cex); }
// in java/org/apache/jasper/security/SecurityClassLoad.java
catch (ClassNotFoundException ex) { log.error("SecurityClassLoad", ex); }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/BeanFactory.java
catch(ClassNotFoundException e) { }
// in java/org/apache/naming/factory/BeanFactory.java
catch(ClassNotFoundException e) { e.printStackTrace(); }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load service Interface"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch(ClassNotFoundException e) { break; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch( ClassNotFoundException e ) { }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (ClassNotFoundException e) { throw new ReflectionException (e, "Cannot find Class for " + signature); }
// in java/org/apache/tomcat/util/digester/CallMethodRule.java
catch (ClassNotFoundException e) { // use the digester log digester.getLogger().error("(CallMethodRule) Cannot load class " + this.paramClassNames[i], e); this.paramTypes[i] = null; // Will cause NPE later }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassNotFoundException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassNotFoundException e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); return null; }
// in java/org/apache/catalina/startup/WebAnnotationSet.java
catch (ClassNotFoundException e) { // We do nothing }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(ClassNotFoundException cnfe) { // Ignore - will search internal repositories next }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(ClassNotFoundException cnfe) { if (!hasExternalRepositories || searchExternalFirst) { throw cnfe; } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { if (log.isTraceEnabled()) log.trace(" --> Passing on ClassNotFoundException"); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { log.info(sm.getString("webappClassLoader.clearRmiInfo", contextName), e); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (ClassNotFoundException e) { log.error("Class "+classNames[i]+" not found! Class not added."); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassNotFoundException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassNotFoundException", className), e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (ClassNotFoundException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch (ClassNotFoundException e) { return super.resolveClass(classDesc); }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch ( ClassNotFoundException x ) { cnfe = x; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ClassNotFoundException x) { log.error("Unable to transfer LazyReplicatedMap state.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ClassNotFoundException x ) { log.error("Unable to deserialize MapMessage.",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ClassNotFoundException x) { log.error("Unable to deserialize MapMessage.", x); return; }
// in java/org/apache/catalina/session/StandardManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/JDBCStore.java
catch (ClassNotFoundException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (ClassNotFoundException e) { String msg = sm.getString( "persistentManager.deserializeError", id); log.error(msg, e); throw new IllegalStateException(msg, e); }
// in java/org/apache/catalina/ha/session/SerializablePrincipal.java
catch (ClassNotFoundException e) { log.error(sm.getString( "serializablePrincipal.readPrincipal.cnfe"), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("deltaManager.loading.cnfe", e), e); throw e; }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (ClassNotFoundException e) { ServletException se = new ServletException(e); throw se; }
// in java/org/apache/catalina/core/StandardContext.java
catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException(cnfe.getMessage()); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ClassNotFoundException e) { // Safe to ignore. No class means no annotations to process }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException cnfe) { // Ignore this case: we must be running on a // non-Sun-based JRE. }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { if (System.getProperty("java.vendor").startsWith( "Sun")) { log.error(sm.getString( "jreLeakListener.gcDaemonFail"), e); } else { log.debug(sm.getString( "jreLeakListener.gcDaemonFail"), e); } }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch(ClassNotFoundException e) { // Ignore. The class is deprecated. }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch(ClassNotFoundException e) { // Ignore }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { if (System.getProperty("java.vendor").startsWith( "Sun")) { log.error(sm.getString( "jreLeakListener.ldapPoolManagerFail"), e); } else { log.debug(sm.getString( "jreLeakListener.ldapPoolManagerFail"), e); } }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ClassNotFoundException e) { log.error( sm.getString("jreLeakListener.classToInitializeFail", classNameToLoad), e); // continue with next class to load }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (ClassNotFoundException e) { try { // Try also the superclass because of primitive types return super.resolveClass(classDesc); } catch (ClassNotFoundException e2) { // Rethrow original exception, as it can have more information // about why the class was not found. BZ 48007 throw e; } }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (ClassNotFoundException e2) { // Rethrow original exception, as it can have more information // about why the class was not found. BZ 48007 throw e; }
// in java/javax/el/ExpressionFactory.java
catch (ClassNotFoundException e) { throw new ELException( "Unable to find ExpressionFactory of type: " + className, e); }
// in java/javax/el/CompositeELResolver.java
catch (ClassNotFoundException e) { // Ignore. This is expected if using the EL stand-alone }
35
            
// in java/org/apache/jasper/compiler/BeanRepository.java
catch (ClassNotFoundException ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
catch (ClassNotFoundException e) { throw new JasperException(e); }
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch (ClassNotFoundException ex) { throw new IllegalStateException(ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (ClassNotFoundException cex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.load"), cex); }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load service Interface"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (ClassNotFoundException e) { throw new ReflectionException (e, "Cannot find Class for " + signature); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassNotFoundException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(ClassNotFoundException cnfe) { if (!hasExternalRepositories || searchExternalFirst) { throw cnfe; } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (ClassNotFoundException e) { if (log.isTraceEnabled()) log.trace(" --> Passing on ClassNotFoundException"); throw e; }
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassNotFoundException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassNotFoundException", className), e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (ClassNotFoundException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/session/StandardManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (ClassNotFoundException e) { String msg = sm.getString( "persistentManager.deserializeError", id); log.error(msg, e); throw new IllegalStateException(msg, e); }
// in java/org/apache/catalina/ha/session/SerializablePrincipal.java
catch (ClassNotFoundException e) { log.error(sm.getString( "serializablePrincipal.readPrincipal.cnfe"), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("deltaManager.loading.cnfe", e), e); throw e; }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (ClassNotFoundException e) { ServletException se = new ServletException(e); throw se; }
// in java/org/apache/catalina/core/StandardContext.java
catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException(cnfe.getMessage()); }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (ClassNotFoundException e) { try { // Try also the superclass because of primitive types return super.resolveClass(classDesc); } catch (ClassNotFoundException e2) { // Rethrow original exception, as it can have more information // about why the class was not found. BZ 48007 throw e; } }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (ClassNotFoundException e2) { // Rethrow original exception, as it can have more information // about why the class was not found. BZ 48007 throw e; }
// in java/javax/el/ExpressionFactory.java
catch (ClassNotFoundException e) { throw new ELException( "Unable to find ExpressionFactory of type: " + className, e); }
5
checked (Domain) ClientAbortException
public final class ClientAbortException extends IOException {

    private static final long serialVersionUID = 1L;


    //------------------------------------------------------------ Constructors

    /**
     * Construct a new ClientAbortException with no other information.
     */
    public ClientAbortException() {

        this(null, null);

    }


    /**
     * Construct a new ClientAbortException for the specified message.
     *
     * @param message Message describing this exception
     */
    public ClientAbortException(String message) {

        this(message, null);

    }


    /**
     * Construct a new ClientAbortException for the specified throwable.
     *
     * @param throwable Throwable that caused this exception
     */
    public ClientAbortException(Throwable throwable) {

        this(null, throwable);

    }


    /**
     * Construct a new ClientAbortException for the specified message
     * and throwable.
     *
     * @param message Message describing this exception
     * @param throwable Throwable that caused this exception
     */
    public ClientAbortException(String message, Throwable throwable) {

        super();
        this.message = message;
        this.throwable = throwable;

    }


    //------------------------------------------------------ Instance Variables


    /**
     * The error message passed to our constructor (if any)
     */
    protected String message = null;


    /**
     * The underlying exception or error passed to our constructor (if any)
     */
    protected Throwable throwable = null;


    //---------------------------------------------------------- Public Methods


    /**
     * Returns the message associated with this exception, if any.
     */
    @Override
    public String getMessage() {

        return (message);

    }


    /**
     * Returns the cause that caused this exception, if any.
     */
    @Override
    public Throwable getCause() {

        return (throwable);

    }


    /**
     * Return a formatted string that describes this exception.
     */
    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder("ClientAbortException:  ");
        if (message != null) {
            sb.append(message);
            if (throwable != null) {
                sb.append(":  ");
            }
        }
        if (throwable != null) {
            sb.append(throwable.toString());
        }
        return (sb.toString());

    }


}
2
            
// in java/org/apache/catalina/connector/OutputBuffer.java
protected void doFlush(boolean realFlush) throws IOException { if (suspended) { return; } // Flush the convertor if one is in use if (gotEnc && conv != null) { conv.flushBuffer(); } try { doFlush = true; if (initial) { coyoteResponse.sendHeaders(); initial = false; } if (bb.getLength() > 0) { bb.flushBuffer(); } } finally { doFlush = false; } if (realFlush) { coyoteResponse.action(ActionCode.CLIENT_FLUSH, coyoteResponse); // If some exception occurred earlier, or if some IOE occurred // here, notify the servlet with an IOE if (coyoteResponse.isExceptionPresent()) { throw new ClientAbortException (coyoteResponse.getErrorException()); } } }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void realWriteBytes(byte buf[], int off, int cnt) throws IOException { if (closed) { return; } if (coyoteResponse == null) { return; } // If we really have something to write if (cnt > 0) { // real write to the adapter outputChunk.setBytes(buf, off, cnt); try { coyoteResponse.doWrite(outputChunk); } catch (IOException e) { // An IOException on a write is almost always due to // the remote client aborting the request. Wrap this // so that it can be handled better by the error dispatcher. throw new ClientAbortException(e); } } }
1
            
// in java/org/apache/catalina/connector/OutputBuffer.java
catch (IOException e) { // An IOException on a write is almost always due to // the remote client aborting the request. Wrap this // so that it can be handled better by the error dispatcher. throw new ClientAbortException(e); }
0 4
            
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ClientAbortException e) { throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ClientAbortException e) { throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (ClientAbortException e) { // Ignore }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ClientAbortException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); ioException = e; }
0 0
unknown (Lib) CloneNotSupportedException 6
            
// in java/org/apache/catalina/connector/CoyoteOutputStream.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/CoyoteWriter.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
0 7
            
// in java/org/apache/tomcat/util/bcel/classfile/Constant.java
Override public Object clone() throws CloneNotSupportedException { return super.clone(); }
// in java/org/apache/catalina/connector/CoyoteOutputStream.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/CoyoteWriter.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
9
            
// in java/org/apache/tomcat/util/buf/CharChunk.java
catch (CloneNotSupportedException e) { // Cannot happen return null; }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapEntry.java
catch (CloneNotSupportedException e) { }
// in java/org/apache/tomcat/util/bcel/classfile/Attribute.java
catch (CloneNotSupportedException e) { e.printStackTrace(); // Never occurs }
// in java/org/apache/tomcat/util/bcel/classfile/LocalVariable.java
catch (CloneNotSupportedException e) { }
// in java/org/apache/tomcat/util/bcel/classfile/InnerClass.java
catch (CloneNotSupportedException e) { }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapTableEntry.java
catch (CloneNotSupportedException e) { }
// in java/org/apache/tomcat/util/bcel/classfile/CodeException.java
catch (CloneNotSupportedException e) { }
// in java/org/apache/tomcat/util/bcel/classfile/LineNumber.java
catch (CloneNotSupportedException e) { }
// in java/javax/servlet/http/Cookie.java
catch (CloneNotSupportedException e) { throw new RuntimeException(e.getMessage()); }
1
            
// in java/javax/servlet/http/Cookie.java
catch (CloneNotSupportedException e) { throw new RuntimeException(e.getMessage()); }
1
unknown (Lib) ClosedChannelException 0 0 0 1
            
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (ClosedChannelException cx) { cancel(sk,key,ops); }
0 0
unknown (Lib) ClosedSelectorException 0 0 0 2
            
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (java.nio.channels.ClosedSelectorException cse) { // ignore is normal at shutdown or stop listen socket }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch ( ClosedSelectorException ignore){}
0 0
unknown (Lib) CommunicationException 0 0 0 2
            
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (CommunicationException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (CommunicationException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); }
0 0
unknown (Lib) ConnectException 0 0 0 1
            
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( ConnectException cx) { //do nothing, we couldn't connect }
0 0
unknown (Lib) CredentialExpiredException 0 0 0 1
            
// in java/org/apache/catalina/realm/JAASRealm.java
catch (CredentialExpiredException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.credentialExpired", username)); return (null); }
0 0
unknown (Lib) DOMException 0 0 0 4
            
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
4
            
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
0
unknown (Lib) DataFormatException 0 0 0 1
            
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
catch (DataFormatException e) { throw new IOException(e); }
1
            
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
catch (DataFormatException e) { throw new IOException(e); }
0
checked (Domain) DebugException
private static class DebugException extends Exception {
        private static final long serialVersionUID = 1L;
    }
0 0 0 0 0 0
unknown (Domain) DecodeException
private static class DecodeException extends CharConversionException {
        private static final long serialVersionUID = 1L;
        public DecodeException(String s) {
            super(s);
        }

        @Override
        public synchronized Throwable fillInStackTrace() {
            // This class does not provide a stack trace
            return this;
        }
    }
1
            
// in java/org/apache/tomcat/util/buf/UDecoder.java
public void convert(MessageBytes mb, boolean query) throws IOException { switch (mb.getType()) { case MessageBytes.T_STR: String strValue=mb.toString(); if( strValue==null ) { return; } try { mb.setString( convert( strValue, query )); } catch (RuntimeException ex) { throw new DecodeException(ex.getMessage()); } break; case MessageBytes.T_CHARS: CharChunk charC=mb.getCharChunk(); convert( charC, query ); break; case MessageBytes.T_BYTES: ByteChunk bytesC=mb.getByteChunk(); convert( bytesC, query ); break; } }
1
            
// in java/org/apache/tomcat/util/buf/UDecoder.java
catch (RuntimeException ex) { throw new DecodeException(ex.getMessage()); }
0 0 0 0
runtime (Domain) ELException
public class ELException extends RuntimeException {

    private static final long serialVersionUID = -6228042809457459161L;

    /**
     * Creates an ELException with no detail message
     */
    public ELException() {
        super();
    }

    /**
     * Creates an ELException with the provided detail message.
     *
     * @param message
     *            the detail message
     */
    public ELException(String message) {
        super(message);
    }

    /**
     * Creates an ELException with the given detail message and root cause.
     *
     * @param message
     *            the detail message
     * @param cause
     *            the originating cause of this exception
     */
    public ELException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Creates an ELException with the given cause
     *
     * @param cause
     *            the originating cause of this exception
     */
    public ELException(Throwable cause) {
        super(cause);
    }
}
59
            
// in java/org/apache/jasper/runtime/PageContextImpl.java
public static Object proprietaryEvaluate(final String expression, final Class<?> expectedType, final PageContext pageContext, final ProtectedFunctionMapper functionMap, final boolean escape) throws ELException { Object retValue; final ExpressionFactory exprFactory = jspf.getJspApplicationContext(pageContext.getServletContext()).getExpressionFactory(); if (SecurityUtil.isPackageProtectionEnabled()) { try { retValue = AccessController .doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { ELContextImpl ctx = (ELContextImpl) pageContext.getELContext(); ctx.setFunctionMapper(new FunctionMapperImpl(functionMap)); ValueExpression ve = exprFactory.createValueExpression(ctx, expression, expectedType); return ve.getValue(ctx); } }); } catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } } }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { return this.variableResolver.resolveVariable(property .toString()); } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getValue(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { Object obj = this.variableResolver.resolveVariable(property .toString()); return (obj != null) ? obj.getClass() : null; } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getType(context, base, property); } return null; }
// in java/org/apache/el/lang/ELSupport.java
public static final int compare(final Object obj0, final Object obj1) throws ELException { if (obj0 == obj1 || equals(obj0, obj1)) { return 0; } if (isBigDecimalOp(obj0, obj1)) { BigDecimal bd0 = (BigDecimal) coerceToNumber(obj0, BigDecimal.class); BigDecimal bd1 = (BigDecimal) coerceToNumber(obj1, BigDecimal.class); return bd0.compareTo(bd1); } if (isDoubleOp(obj0, obj1)) { Double d0 = (Double) coerceToNumber(obj0, Double.class); Double d1 = (Double) coerceToNumber(obj1, Double.class); return d0.compareTo(d1); } if (isBigIntegerOp(obj0, obj1)) { BigInteger bi0 = (BigInteger) coerceToNumber(obj0, BigInteger.class); BigInteger bi1 = (BigInteger) coerceToNumber(obj1, BigInteger.class); return bi0.compareTo(bi1); } if (isLongOp(obj0, obj1)) { Long l0 = (Long) coerceToNumber(obj0, Long.class); Long l1 = (Long) coerceToNumber(obj1, Long.class); return l0.compareTo(l1); } if (obj0 instanceof String || obj1 instanceof String) { return coerceToString(obj0).compareTo(coerceToString(obj1)); } if (obj0 instanceof Comparable<?>) { @SuppressWarnings("unchecked") // checked above final Comparable<Object> comparable = (Comparable<Object>) obj0; return (obj1 != null) ? comparable.compareTo(obj1) : 1; } if (obj1 instanceof Comparable<?>) { @SuppressWarnings("unchecked") // checked above final Comparable<Object> comparable = (Comparable<Object>) obj1; return (obj0 != null) ? -comparable.compareTo(obj0) : -1; } throw new ELException(MessageFactory.get("error.compare", obj0, obj1)); }
// in java/org/apache/el/lang/ELSupport.java
public static final Boolean coerceToBoolean(final Object obj) throws ELException { if (obj == null || "".equals(obj)) { return Boolean.FALSE; } if (obj instanceof Boolean) { return (Boolean) obj; } if (obj instanceof String) { return Boolean.valueOf((String) obj); } throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), Boolean.class)); }
// in java/org/apache/el/lang/ELSupport.java
public static final Character coerceToCharacter(final Object obj) throws ELException { if (obj == null || "".equals(obj)) { return Character.valueOf((char) 0); } if (obj instanceof String) { return Character.valueOf(((String) obj).charAt(0)); } if (ELArithmetic.isNumber(obj)) { return Character.valueOf((char) ((Number) obj).shortValue()); } Class<?> objType = obj.getClass(); if (obj instanceof Character) { return (Character) obj; } throw new ELException(MessageFactory.get("error.convert", obj, objType, Character.class)); }
// in java/org/apache/el/lang/ELSupport.java
protected static final Number coerceToNumber(final Number number, final Class<?> type) throws ELException { if (Long.TYPE == type || Long.class.equals(type)) { return Long.valueOf(number.longValue()); } if (Double.TYPE == type || Double.class.equals(type)) { return new Double(number.doubleValue()); } if (Integer.TYPE == type || Integer.class.equals(type)) { return Integer.valueOf(number.intValue()); } if (BigInteger.class.equals(type)) { if (number instanceof BigDecimal) { return ((BigDecimal) number).toBigInteger(); } if (number instanceof BigInteger) { return number; } return BigInteger.valueOf(number.longValue()); } if (BigDecimal.class.equals(type)) { if (number instanceof BigDecimal) { return number; } if (number instanceof BigInteger) { return new BigDecimal((BigInteger) number); } return new BigDecimal(number.doubleValue()); } if (Byte.TYPE == type || Byte.class.equals(type)) { return Byte.valueOf(number.byteValue()); } if (Short.TYPE == type || Short.class.equals(type)) { return Short.valueOf(number.shortValue()); } if (Float.TYPE == type || Float.class.equals(type)) { return new Float(number.floatValue()); } if (Number.class.equals(type)) { return number; } throw new ELException(MessageFactory.get("error.convert", number, number.getClass(), type)); }
// in java/org/apache/el/lang/ELSupport.java
public static final Number coerceToNumber(final Object obj, final Class<?> type) throws ELException { if (obj == null || "".equals(obj)) { return coerceToNumber(ZERO, type); } if (obj instanceof String) { return coerceToNumber((String) obj, type); } if (ELArithmetic.isNumber(obj)) { return coerceToNumber((Number) obj, type); } if (obj instanceof Character) { return coerceToNumber(Short.valueOf((short) ((Character) obj) .charValue()), type); } throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/lang/ELSupport.java
protected static final Number coerceToNumber(final String val, final Class<?> type) throws ELException { if (Long.TYPE == type || Long.class.equals(type)) { try { return Long.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Integer.TYPE == type || Integer.class.equals(type)) { try { return Integer.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Double.TYPE == type || Double.class.equals(type)) { try { return Double.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (BigInteger.class.equals(type)) { try { return new BigInteger(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (BigDecimal.class.equals(type)) { try { return new BigDecimal(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Byte.TYPE == type || Byte.class.equals(type)) { try { return Byte.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Short.TYPE == type || Short.class.equals(type)) { try { return Short.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Float.TYPE == type || Float.class.equals(type)) { try { return Float.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
public static final Object coerceToType(final Object obj, final Class<?> type) throws ELException { if (type == null || Object.class.equals(type) || (obj != null && type.isAssignableFrom(obj.getClass()))) { return obj; } if (String.class.equals(type)) { return coerceToString(obj); } if (ELArithmetic.isNumberType(type)) { return coerceToNumber(obj, type); } if (Character.class.equals(type) || Character.TYPE == type) { return coerceToCharacter(obj); } if (Boolean.class.equals(type) || Boolean.TYPE == type) { return coerceToBoolean(obj); } if (type.isEnum()) { return coerceToEnum(obj, type); } // new to spec if (obj == null) return null; if (obj instanceof String) { if ("".equals(obj)) return null; PropertyEditor editor = PropertyEditorManager.findEditor(type); if (editor != null) { editor.setAsText((String) obj); return editor.getValue(); } } throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/lang/ExpressionBuilder.java
private static final Node createNodeInternal(String expr) throws ELException { if (expr == null) { throw new ELException(MessageFactory.get("error.null")); } Node n = cache.get(expr); if (n == null) { try { n = (new ELParser(new StringReader(expr))) .CompositeExpression(); // validate composite expression int numChildren = n.jjtGetNumChildren(); if (numChildren == 1) { n = n.jjtGetChild(0); } else { Class<?> type = null; Node child = null; for (int i = 0; i < numChildren; i++) { child = n.jjtGetChild(i); if (child instanceof AstLiteralExpression) continue; if (type == null) type = child.getClass(); else { if (!type.equals(child.getClass())) { throw new ELException(MessageFactory.get( "error.mixed", expr)); } } } } if (n instanceof AstDeferredExpression || n instanceof AstDynamicExpression) { n = n.jjtGetChild(0); } cache.put(expr, n); } catch (Exception e) { throw new ELException( MessageFactory.get("error.parseFail", expr), e); } } return n; }
// in java/org/apache/el/lang/ExpressionBuilder.java
Override public void visit(Node node) throws ELException { if (node instanceof AstFunction) { AstFunction funcNode = (AstFunction) node; if (this.fnMapper == null) { throw new ELException(MessageFactory.get("error.fnMapper.null")); } Method m = fnMapper.resolveFunction(funcNode.getPrefix(), funcNode .getLocalName()); if (m == null) { throw new ELException(MessageFactory.get( "error.fnMapper.method", funcNode.getOutputName())); } int pcnt = m.getParameterTypes().length; if (node.jjtGetNumChildren() != pcnt) { throw new ELException(MessageFactory.get( "error.fnMapper.paramcount", funcNode.getOutputName(), "" + pcnt, "" + node.jjtGetNumChildren())); } } else if (node instanceof AstIdentifier && this.varMapper != null) { String variable = ((AstIdentifier) node).getImage(); // simply capture it this.varMapper.resolveVariable(variable); } }
// in java/org/apache/el/lang/ExpressionBuilder.java
public MethodExpression createMethodExpression(Class<?> expectedReturnType, Class<?>[] expectedParamTypes) throws ELException { Node n = this.build(); if (!n.isParametersProvided() && expectedParamTypes == null) { throw new NullPointerException(MessageFactory .get("error.method.nullParms")); } if (n instanceof AstValue || n instanceof AstIdentifier) { return new MethodExpressionImpl(expression, n, this.fnMapper, this.varMapper, expectedReturnType, expectedParamTypes); } else if (n instanceof AstLiteralExpression) { return new MethodExpressionLiteral(expression, expectedReturnType, expectedParamTypes); } else { throw new ELException("Not a Valid Method Expression: " + expression); } }
// in java/org/apache/el/parser/AstFunction.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { FunctionMapper fnMapper = ctx.getFunctionMapper(); // quickly validate again for this request if (fnMapper == null) { throw new ELException(MessageFactory.get("error.fnMapper.null")); } Method m = fnMapper.resolveFunction(this.prefix, this.localName); if (m == null) { throw new ELException(MessageFactory.get("error.fnMapper.method", this.getOutputName())); } return m.getReturnType(); }
// in java/org/apache/el/parser/AstFunction.java
Override public Object getValue(EvaluationContext ctx) throws ELException { FunctionMapper fnMapper = ctx.getFunctionMapper(); // quickly validate again for this request if (fnMapper == null) { throw new ELException(MessageFactory.get("error.fnMapper.null")); } Method m = fnMapper.resolveFunction(this.prefix, this.localName); if (m == null) { throw new ELException(MessageFactory.get("error.fnMapper.method", this.getOutputName())); } Class<?>[] paramTypes = m.getParameterTypes(); Object[] params = null; Object result = null; int numParams = this.jjtGetNumChildren(); if (numParams > 0) { params = new Object[numParams]; try { for (int i = 0; i < numParams; i++) { params[i] = this.children[i].getValue(ctx); params[i] = coerceToType(params[i], paramTypes[i]); } } catch (ELException ele) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), ele); } } try { result = m.invoke(null, params); } catch (IllegalAccessException iae) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), iae); } catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(MessageFactory.get("error.function", this .getOutputName()), cause); } return result; }
// in java/org/apache/el/parser/AstIdentifier.java
Override public void setImage(String image) { if (!Validation.isIdentifier(image)) { throw new ELException(MessageFactory.get("error.identifier.notjava", image)); } this.image = image; }
// in java/org/apache/el/parser/AstIdentifier.java
private final MethodExpression getMethodExpression(EvaluationContext ctx) throws ELException { Object obj = null; // case A: ValueExpression exists, getValue which must // be a MethodExpression VariableMapper varMapper = ctx.getVariableMapper(); ValueExpression ve = null; if (varMapper != null) { ve = varMapper.resolveVariable(this.image); if (ve != null) { obj = ve.getValue(ctx); } } // case B: evaluate the identity against the ELResolver, again, must be // a MethodExpression to be able to invoke if (ve == null) { ctx.setPropertyResolved(false); obj = ctx.getELResolver().getValue(ctx, null, this.image); } // finally provide helpful hints if (obj instanceof MethodExpression) { return (MethodExpression) obj; } else if (obj == null) { throw new MethodNotFoundException("Identity '" + this.image + "' was null and was unable to invoke"); } else { throw new ELException( "Identity '" + this.image + "' does not reference a MethodExpression instance, returned type: " + obj.getClass().getName()); } }
// in java/org/apache/el/parser/AstDotSuffix.java
Override public void setImage(String image) { if (!Validation.isIdentifier(image)) { throw new ELException(MessageFactory.get("error.identifier.notjava", image)); } this.image = image; }
// in java/javax/el/ExpressionFactory.java
public static ExpressionFactory newInstance(Properties properties) { ExpressionFactory result = null; ClassLoader tccl = Thread.currentThread().getContextClassLoader(); CacheValue cacheValue; Class<?> clazz; if (tccl == null) { cacheValue = nullTcclFactory; } else { CacheKey key = new CacheKey(tccl); cacheValue = factoryCache.get(key); if (cacheValue == null) { CacheValue newCacheValue = new CacheValue(); cacheValue = factoryCache.putIfAbsent(key, newCacheValue); if (cacheValue == null) { cacheValue = newCacheValue; } } } final Lock readLock = cacheValue.getLock().readLock(); readLock.lock(); try { clazz = cacheValue.getFactoryClass(); } finally { readLock.unlock(); } if (clazz == null) { String className = null; try { final Lock writeLock = cacheValue.getLock().writeLock(); writeLock.lock(); try { className = cacheValue.getFactoryClassName(); if (className == null) { className = discoverClassName(tccl); cacheValue.setFactoryClassName(className); } if (tccl == null) { clazz = Class.forName(className); } else { clazz = tccl.loadClass(className); } cacheValue.setFactoryClass(clazz); } finally { writeLock.unlock(); } } catch (ClassNotFoundException e) { throw new ELException( "Unable to find ExpressionFactory of type: " + className, e); } } try { Constructor<?> constructor = null; // Do we need to look for a constructor that will take properties? if (properties != null) { try { constructor = clazz.getConstructor(Properties.class); } catch (SecurityException se) { throw new ELException(se); } catch (NoSuchMethodException nsme) { // This can be ignored // This is OK for this constructor not to exist } } if (constructor == null) { result = (ExpressionFactory) clazz.newInstance(); } else { result = (ExpressionFactory) constructor.newInstance(properties); } } catch (InstantiationException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); } catch (IllegalAccessException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); } catch (IllegalArgumentException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); } return result; }
// in java/javax/el/ExpressionFactory.java
private static String getClassNameServices(ClassLoader tccl) { InputStream is = null; if (tccl == null) { is = ClassLoader.getSystemResourceAsStream(SERVICE_RESOURCE_NAME); } else { is = tccl.getResourceAsStream(SERVICE_RESOURCE_NAME); } if (is != null) { String line = null; BufferedReader br = null; InputStreamReader isr = null; try { isr = new InputStreamReader(is, "UTF-8"); br = new BufferedReader(isr); line = br.readLine(); if (line != null && line.trim().length() > 0) { return line.trim(); } } catch (UnsupportedEncodingException e) { // Should never happen with UTF-8 // If it does - ignore & return null } catch (IOException e) { throw new ELException("Failed to read " + SERVICE_RESOURCE_NAME, e); } finally { try { if (br != null) { br.close(); } } catch (IOException ioe) {/*Ignore*/} try { if (isr != null) { isr.close(); } } catch (IOException ioe) {/*Ignore*/} try { is.close(); } catch (IOException ioe) {/*Ignore*/} } } return null; }
// in java/javax/el/ExpressionFactory.java
private static String getClassNameJreDir() { File file = new File(PROPERTY_FILE); if (file.canRead()) { InputStream is = null; try { is = new FileInputStream(file); Properties props = new Properties(); props.load(is); String value = props.getProperty(PROPERTY_NAME); if (value != null && value.trim().length() > 0) { return value.trim(); } } catch (FileNotFoundException e) { // Should not happen - ignore it if it does } catch (IOException e) { throw new ELException("Failed to read " + PROPERTY_FILE, e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { // Ignore } } } } return null; }
// in java/javax/el/BeanELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); Method m = this.property(context, base, property).read(context); try { return m.invoke(base, (Object[]) null); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return; } context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } Method m = this.property(context, base, property).write(context); try { m.invoke(base, value); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
39
            
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } }
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/el/lang/ELSupport.java
catch (IllegalArgumentException iae) { throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ExpressionBuilder.java
catch (Exception e) { throw new ELException( MessageFactory.get("error.parseFail", expr), e); }
// in java/org/apache/el/lang/ExpressionBuilder.java
catch (Exception e) { if (e instanceof ELException) { throw (ELException) e; } else { throw (new ELException(e)); } }
// in java/org/apache/el/parser/AstFunction.java
catch (ELException ele) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), ele); }
// in java/org/apache/el/parser/AstFunction.java
catch (IllegalAccessException iae) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), iae); }
// in java/org/apache/el/parser/AstFunction.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(MessageFactory.get("error.function", this .getOutputName()), cause); }
// in java/org/apache/el/parser/ELParser.java
catch (ParseException pe) { throw new ELException(pe.getMessage());
// in java/org/apache/el/parser/AstValue.java
catch (IllegalAccessException iae) { throw new ELException(iae); }
// in java/org/apache/el/parser/AstValue.java
catch (IllegalArgumentException iae) { throw new ELException(iae); }
// in java/org/apache/el/parser/AstValue.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
// in java/javax/el/ExpressionFactory.java
catch (ClassNotFoundException e) { throw new ELException( "Unable to find ExpressionFactory of type: " + className, e); }
// in java/javax/el/ExpressionFactory.java
catch (SecurityException se) { throw new ELException(se); }
// in java/javax/el/ExpressionFactory.java
catch (InstantiationException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/ExpressionFactory.java
catch (IllegalAccessException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/ExpressionFactory.java
catch (IllegalArgumentException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/ExpressionFactory.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { throw new ELException("Failed to read " + SERVICE_RESOURCE_NAME, e); }
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { throw new ELException("Failed to read " + PROPERTY_FILE, e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (Exception e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (Exception e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IntrospectionException ie) { throw new ELException(ie); }
// in java/javax/el/BeanELResolver.java
catch (IllegalArgumentException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
140
            
// in java/org/apache/jasper/runtime/PageContextImpl.java
public static Object proprietaryEvaluate(final String expression, final Class<?> expectedType, final PageContext pageContext, final ProtectedFunctionMapper functionMap, final boolean escape) throws ELException { Object retValue; final ExpressionFactory exprFactory = jspf.getJspApplicationContext(pageContext.getServletContext()).getExpressionFactory(); if (SecurityUtil.isPackageProtectionEnabled()) { try { retValue = AccessController .doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { ELContextImpl ctx = (ELContextImpl) pageContext.getELContext(); ctx.setFunctionMapper(new FunctionMapperImpl(functionMap)); ValueExpression ve = exprFactory.createValueExpression(ctx, expression, expectedType); return ve.getValue(ctx); } }); } catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } } }
// in java/org/apache/jasper/compiler/Node.java
public void validateEL(ExpressionFactory ef, ELContext ctx) throws ELException { if (this.el != null) { // determine exact type ef.createValueExpression(ctx, this.value, String.class); } }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { return this.variableResolver.resolveVariable(property .toString()); } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getValue(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { Object obj = this.variableResolver.resolveVariable(property .toString()); return (obj != null) ? obj.getClass() : null; } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getType(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); throw new PropertyNotWritableException( "Legacy VariableResolver wrapped, not writable"); } if (!context.isPropertyResolved()) { elResolver.setValue(context, base, property, value); } }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return true; } return elResolver.isReadOnly(context, base, property); }
// in java/org/apache/jasper/el/ExpressionImpl.java
Override public Object evaluate(VariableResolver vResolver) throws ELException { ELContext ctx = new ELContextImpl(new ELResolverImpl(vResolver)); return ve.getValue(ctx); }
// in java/org/apache/jasper/el/VariableResolverImpl.java
Override public Object resolveVariable(String pName) throws ELException { return this.ctx.getELResolver().getValue(this.ctx, null, pName); }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public MethodInfo getMethodInfo(ELContext context) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.getMethodInfo(context); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public Object invoke(ELContext context, Object[] params) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.invoke(context, params); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Class<?> getType(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getType(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public boolean isReadOnly(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.isReadOnly(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void setValue(ELContext context, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { try { this.target.setValue(context, value); } catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Object getValue(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getValue(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/el/lang/ELSupport.java
public static final int compare(final Object obj0, final Object obj1) throws ELException { if (obj0 == obj1 || equals(obj0, obj1)) { return 0; } if (isBigDecimalOp(obj0, obj1)) { BigDecimal bd0 = (BigDecimal) coerceToNumber(obj0, BigDecimal.class); BigDecimal bd1 = (BigDecimal) coerceToNumber(obj1, BigDecimal.class); return bd0.compareTo(bd1); } if (isDoubleOp(obj0, obj1)) { Double d0 = (Double) coerceToNumber(obj0, Double.class); Double d1 = (Double) coerceToNumber(obj1, Double.class); return d0.compareTo(d1); } if (isBigIntegerOp(obj0, obj1)) { BigInteger bi0 = (BigInteger) coerceToNumber(obj0, BigInteger.class); BigInteger bi1 = (BigInteger) coerceToNumber(obj1, BigInteger.class); return bi0.compareTo(bi1); } if (isLongOp(obj0, obj1)) { Long l0 = (Long) coerceToNumber(obj0, Long.class); Long l1 = (Long) coerceToNumber(obj1, Long.class); return l0.compareTo(l1); } if (obj0 instanceof String || obj1 instanceof String) { return coerceToString(obj0).compareTo(coerceToString(obj1)); } if (obj0 instanceof Comparable<?>) { @SuppressWarnings("unchecked") // checked above final Comparable<Object> comparable = (Comparable<Object>) obj0; return (obj1 != null) ? comparable.compareTo(obj1) : 1; } if (obj1 instanceof Comparable<?>) { @SuppressWarnings("unchecked") // checked above final Comparable<Object> comparable = (Comparable<Object>) obj1; return (obj0 != null) ? -comparable.compareTo(obj0) : -1; } throw new ELException(MessageFactory.get("error.compare", obj0, obj1)); }
// in java/org/apache/el/lang/ELSupport.java
public static final boolean equals(final Object obj0, final Object obj1) throws ELException { if (obj0 == obj1) { return true; } else if (obj0 == null || obj1 == null) { return false; } else if (isBigDecimalOp(obj0, obj1)) { BigDecimal bd0 = (BigDecimal) coerceToNumber(obj0, BigDecimal.class); BigDecimal bd1 = (BigDecimal) coerceToNumber(obj1, BigDecimal.class); return bd0.equals(bd1); } else if (isDoubleOp(obj0, obj1)) { Double d0 = (Double) coerceToNumber(obj0, Double.class); Double d1 = (Double) coerceToNumber(obj1, Double.class); return d0.equals(d1); } else if (isBigIntegerOp(obj0, obj1)) { BigInteger bi0 = (BigInteger) coerceToNumber(obj0, BigInteger.class); BigInteger bi1 = (BigInteger) coerceToNumber(obj1, BigInteger.class); return bi0.equals(bi1); } else if (isLongOp(obj0, obj1)) { Long l0 = (Long) coerceToNumber(obj0, Long.class); Long l1 = (Long) coerceToNumber(obj1, Long.class); return l0.equals(l1); } else if (obj0 instanceof Boolean || obj1 instanceof Boolean) { return coerceToBoolean(obj0).equals(coerceToBoolean(obj1)); } else if (obj0.getClass().isEnum()) { return obj0.equals(coerceToEnum(obj1, obj0.getClass())); } else if (obj1.getClass().isEnum()) { return obj1.equals(coerceToEnum(obj0, obj1.getClass())); } else if (obj0 instanceof String || obj1 instanceof String) { int lexCompare = coerceToString(obj0).compareTo(coerceToString(obj1)); return (lexCompare == 0) ? true : false; } else { return obj0.equals(obj1); } }
// in java/org/apache/el/lang/ELSupport.java
public static final Boolean coerceToBoolean(final Object obj) throws ELException { if (obj == null || "".equals(obj)) { return Boolean.FALSE; } if (obj instanceof Boolean) { return (Boolean) obj; } if (obj instanceof String) { return Boolean.valueOf((String) obj); } throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), Boolean.class)); }
// in java/org/apache/el/lang/ELSupport.java
public static final Character coerceToCharacter(final Object obj) throws ELException { if (obj == null || "".equals(obj)) { return Character.valueOf((char) 0); } if (obj instanceof String) { return Character.valueOf(((String) obj).charAt(0)); } if (ELArithmetic.isNumber(obj)) { return Character.valueOf((char) ((Number) obj).shortValue()); } Class<?> objType = obj.getClass(); if (obj instanceof Character) { return (Character) obj; } throw new ELException(MessageFactory.get("error.convert", obj, objType, Character.class)); }
// in java/org/apache/el/lang/ELSupport.java
protected static final Number coerceToNumber(final Number number, final Class<?> type) throws ELException { if (Long.TYPE == type || Long.class.equals(type)) { return Long.valueOf(number.longValue()); } if (Double.TYPE == type || Double.class.equals(type)) { return new Double(number.doubleValue()); } if (Integer.TYPE == type || Integer.class.equals(type)) { return Integer.valueOf(number.intValue()); } if (BigInteger.class.equals(type)) { if (number instanceof BigDecimal) { return ((BigDecimal) number).toBigInteger(); } if (number instanceof BigInteger) { return number; } return BigInteger.valueOf(number.longValue()); } if (BigDecimal.class.equals(type)) { if (number instanceof BigDecimal) { return number; } if (number instanceof BigInteger) { return new BigDecimal((BigInteger) number); } return new BigDecimal(number.doubleValue()); } if (Byte.TYPE == type || Byte.class.equals(type)) { return Byte.valueOf(number.byteValue()); } if (Short.TYPE == type || Short.class.equals(type)) { return Short.valueOf(number.shortValue()); } if (Float.TYPE == type || Float.class.equals(type)) { return new Float(number.floatValue()); } if (Number.class.equals(type)) { return number; } throw new ELException(MessageFactory.get("error.convert", number, number.getClass(), type)); }
// in java/org/apache/el/lang/ELSupport.java
public static final Number coerceToNumber(final Object obj, final Class<?> type) throws ELException { if (obj == null || "".equals(obj)) { return coerceToNumber(ZERO, type); } if (obj instanceof String) { return coerceToNumber((String) obj, type); } if (ELArithmetic.isNumber(obj)) { return coerceToNumber((Number) obj, type); } if (obj instanceof Character) { return coerceToNumber(Short.valueOf((short) ((Character) obj) .charValue()), type); } throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/lang/ELSupport.java
protected static final Number coerceToNumber(final String val, final Class<?> type) throws ELException { if (Long.TYPE == type || Long.class.equals(type)) { try { return Long.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Integer.TYPE == type || Integer.class.equals(type)) { try { return Integer.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Double.TYPE == type || Double.class.equals(type)) { try { return Double.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (BigInteger.class.equals(type)) { try { return new BigInteger(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (BigDecimal.class.equals(type)) { try { return new BigDecimal(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Byte.TYPE == type || Byte.class.equals(type)) { try { return Byte.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Short.TYPE == type || Short.class.equals(type)) { try { return Short.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } if (Float.TYPE == type || Float.class.equals(type)) { try { return Float.valueOf(val); } catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); } } throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
public static final Object coerceToType(final Object obj, final Class<?> type) throws ELException { if (type == null || Object.class.equals(type) || (obj != null && type.isAssignableFrom(obj.getClass()))) { return obj; } if (String.class.equals(type)) { return coerceToString(obj); } if (ELArithmetic.isNumberType(type)) { return coerceToNumber(obj, type); } if (Character.class.equals(type) || Character.TYPE == type) { return coerceToCharacter(obj); } if (Boolean.class.equals(type) || Boolean.TYPE == type) { return coerceToBoolean(obj); } if (type.isEnum()) { return coerceToEnum(obj, type); } // new to spec if (obj == null) return null; if (obj instanceof String) { if ("".equals(obj)) return null; PropertyEditor editor = PropertyEditorManager.findEditor(type); if (editor != null) { editor.setAsText((String) obj); return editor.getValue(); } } throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/lang/ExpressionBuilder.java
public static final Node createNode(String expr) throws ELException { Node n = createNodeInternal(expr); return n; }
// in java/org/apache/el/lang/ExpressionBuilder.java
private static final Node createNodeInternal(String expr) throws ELException { if (expr == null) { throw new ELException(MessageFactory.get("error.null")); } Node n = cache.get(expr); if (n == null) { try { n = (new ELParser(new StringReader(expr))) .CompositeExpression(); // validate composite expression int numChildren = n.jjtGetNumChildren(); if (numChildren == 1) { n = n.jjtGetChild(0); } else { Class<?> type = null; Node child = null; for (int i = 0; i < numChildren; i++) { child = n.jjtGetChild(i); if (child instanceof AstLiteralExpression) continue; if (type == null) type = child.getClass(); else { if (!type.equals(child.getClass())) { throw new ELException(MessageFactory.get( "error.mixed", expr)); } } } } if (n instanceof AstDeferredExpression || n instanceof AstDynamicExpression) { n = n.jjtGetChild(0); } cache.put(expr, n); } catch (Exception e) { throw new ELException( MessageFactory.get("error.parseFail", expr), e); } } return n; }
// in java/org/apache/el/lang/ExpressionBuilder.java
private void prepare(Node node) throws ELException { try { node.accept(this); } catch (Exception e) { if (e instanceof ELException) { throw (ELException) e; } else { throw (new ELException(e)); } } if (this.fnMapper instanceof FunctionMapperFactory) { this.fnMapper = ((FunctionMapperFactory) this.fnMapper).create(); } if (this.varMapper instanceof VariableMapperFactory) { this.varMapper = ((VariableMapperFactory) this.varMapper).create(); } }
// in java/org/apache/el/lang/ExpressionBuilder.java
private Node build() throws ELException { Node n = createNodeInternal(this.expression); this.prepare(n); if (n instanceof AstDeferredExpression || n instanceof AstDynamicExpression) { n = n.jjtGetChild(0); } return n; }
// in java/org/apache/el/lang/ExpressionBuilder.java
Override public void visit(Node node) throws ELException { if (node instanceof AstFunction) { AstFunction funcNode = (AstFunction) node; if (this.fnMapper == null) { throw new ELException(MessageFactory.get("error.fnMapper.null")); } Method m = fnMapper.resolveFunction(funcNode.getPrefix(), funcNode .getLocalName()); if (m == null) { throw new ELException(MessageFactory.get( "error.fnMapper.method", funcNode.getOutputName())); } int pcnt = m.getParameterTypes().length; if (node.jjtGetNumChildren() != pcnt) { throw new ELException(MessageFactory.get( "error.fnMapper.paramcount", funcNode.getOutputName(), "" + pcnt, "" + node.jjtGetNumChildren())); } } else if (node instanceof AstIdentifier && this.varMapper != null) { String variable = ((AstIdentifier) node).getImage(); // simply capture it this.varMapper.resolveVariable(variable); } }
// in java/org/apache/el/lang/ExpressionBuilder.java
public ValueExpression createValueExpression(Class<?> expectedType) throws ELException { Node n = this.build(); return new ValueExpressionImpl(this.expression, n, this.fnMapper, this.varMapper, expectedType); }
// in java/org/apache/el/lang/ExpressionBuilder.java
public MethodExpression createMethodExpression(Class<?> expectedReturnType, Class<?>[] expectedParamTypes) throws ELException { Node n = this.build(); if (!n.isParametersProvided() && expectedParamTypes == null) { throw new NullPointerException(MessageFactory .get("error.method.nullParms")); } if (n instanceof AstValue || n instanceof AstIdentifier) { return new MethodExpressionImpl(expression, n, this.fnMapper, this.varMapper, expectedReturnType, expectedParamTypes); } else if (n instanceof AstLiteralExpression) { return new MethodExpressionLiteral(expression, expectedReturnType, expectedParamTypes); } else { throw new ELException("Not a Valid Method Expression: " + expression); } }
// in java/org/apache/el/MethodExpressionImpl.java
Override public MethodInfo getMethodInfo(ELContext context) throws PropertyNotFoundException, MethodNotFoundException, ELException { Node n = this.getNode(); EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return n.getMethodInfo(ctx, this.paramTypes); }
// in java/org/apache/el/MethodExpressionImpl.java
private Node getNode() throws ELException { if (this.node == null) { this.node = ExpressionBuilder.createNode(this.expr); } return this.node; }
// in java/org/apache/el/MethodExpressionImpl.java
Override public Object invoke(ELContext context, Object[] params) throws PropertyNotFoundException, MethodNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return this.getNode().invoke(ctx, this.paramTypes, params); }
// in java/org/apache/el/MethodExpressionLiteral.java
Override public MethodInfo getMethodInfo(ELContext context) throws ELException { return new MethodInfo(this.expr, this.expectedType, this.paramTypes); }
// in java/org/apache/el/MethodExpressionLiteral.java
Override public Object invoke(ELContext context, Object[] params) throws ELException { if (this.expectedType != null) { return ELSupport.coerceToType(this.expr, this.expectedType); } else { return this.expr; } }
// in java/org/apache/el/parser/AstMult.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); return ELArithmetic.multiply(obj0, obj1); }
// in java/org/apache/el/parser/AstFunction.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { FunctionMapper fnMapper = ctx.getFunctionMapper(); // quickly validate again for this request if (fnMapper == null) { throw new ELException(MessageFactory.get("error.fnMapper.null")); } Method m = fnMapper.resolveFunction(this.prefix, this.localName); if (m == null) { throw new ELException(MessageFactory.get("error.fnMapper.method", this.getOutputName())); } return m.getReturnType(); }
// in java/org/apache/el/parser/AstFunction.java
Override public Object getValue(EvaluationContext ctx) throws ELException { FunctionMapper fnMapper = ctx.getFunctionMapper(); // quickly validate again for this request if (fnMapper == null) { throw new ELException(MessageFactory.get("error.fnMapper.null")); } Method m = fnMapper.resolveFunction(this.prefix, this.localName); if (m == null) { throw new ELException(MessageFactory.get("error.fnMapper.method", this.getOutputName())); } Class<?>[] paramTypes = m.getParameterTypes(); Object[] params = null; Object result = null; int numParams = this.jjtGetNumChildren(); if (numParams > 0) { params = new Object[numParams]; try { for (int i = 0; i < numParams; i++) { params[i] = this.children[i].getValue(ctx); params[i] = coerceToType(params[i], paramTypes[i]); } } catch (ELException ele) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), ele); } } try { result = m.invoke(null, params); } catch (IllegalAccessException iae) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), iae); } catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(MessageFactory.get("error.function", this .getOutputName()), cause); } return result; }
// in java/org/apache/el/parser/SimpleNode.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/el/parser/SimpleNode.java
Override public Object getValue(EvaluationContext ctx) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/el/parser/SimpleNode.java
Override public boolean isReadOnly(EvaluationContext ctx) throws ELException { return true; }
// in java/org/apache/el/parser/SimpleNode.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { throw new PropertyNotWritableException(MessageFactory.get("error.syntax.set")); }
// in java/org/apache/el/parser/SimpleNode.java
Override public Object invoke(EvaluationContext ctx, Class<?>[] paramTypes, Object[] paramValues) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/el/parser/SimpleNode.java
Override public MethodInfo getMethodInfo(EvaluationContext ctx, Class<?>[] paramTypes) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/el/parser/AstIdentifier.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { return expr.getType(ctx.getELContext()); } } ctx.setPropertyResolved(false); Class<?> result = ctx.getELResolver().getType(ctx, null, this.image); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } return result; }
// in java/org/apache/el/parser/AstIdentifier.java
Override public Object getValue(EvaluationContext ctx) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { return expr.getValue(ctx.getELContext()); } } ctx.setPropertyResolved(false); Object result = ctx.getELResolver().getValue(ctx, null, this.image); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } return result; }
// in java/org/apache/el/parser/AstIdentifier.java
Override public boolean isReadOnly(EvaluationContext ctx) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { return expr.isReadOnly(ctx.getELContext()); } } ctx.setPropertyResolved(false); boolean result = ctx.getELResolver().isReadOnly(ctx, null, this.image); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } return result; }
// in java/org/apache/el/parser/AstIdentifier.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { expr.setValue(ctx.getELContext(), value); return; } } ctx.setPropertyResolved(false); ctx.getELResolver().setValue(ctx, null, this.image, value); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } }
// in java/org/apache/el/parser/AstIdentifier.java
Override public Object invoke(EvaluationContext ctx, Class<?>[] paramTypes, Object[] paramValues) throws ELException { return this.getMethodExpression(ctx).invoke(ctx.getELContext(), paramValues); }
// in java/org/apache/el/parser/AstIdentifier.java
Override public MethodInfo getMethodInfo(EvaluationContext ctx, Class<?>[] paramTypes) throws ELException { return this.getMethodExpression(ctx).getMethodInfo(ctx.getELContext()); }
// in java/org/apache/el/parser/AstIdentifier.java
private final MethodExpression getMethodExpression(EvaluationContext ctx) throws ELException { Object obj = null; // case A: ValueExpression exists, getValue which must // be a MethodExpression VariableMapper varMapper = ctx.getVariableMapper(); ValueExpression ve = null; if (varMapper != null) { ve = varMapper.resolveVariable(this.image); if (ve != null) { obj = ve.getValue(ctx); } } // case B: evaluate the identity against the ELResolver, again, must be // a MethodExpression to be able to invoke if (ve == null) { ctx.setPropertyResolved(false); obj = ctx.getELResolver().getValue(ctx, null, this.image); } // finally provide helpful hints if (obj instanceof MethodExpression) { return (MethodExpression) obj; } else if (obj == null) { throw new MethodNotFoundException("Identity '" + this.image + "' was null and was unable to invoke"); } else { throw new ELException( "Identity '" + this.image + "' does not reference a MethodExpression instance, returned type: " + obj.getClass().getName()); } }
// in java/org/apache/el/parser/AstDeferredExpression.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return this.children[0].getType(ctx); }
// in java/org/apache/el/parser/AstDeferredExpression.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.children[0].getValue(ctx); }
// in java/org/apache/el/parser/AstDeferredExpression.java
Override public boolean isReadOnly(EvaluationContext ctx) throws ELException { return this.children[0].isReadOnly(ctx); }
// in java/org/apache/el/parser/AstDeferredExpression.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { this.children[0].setValue(ctx, value); }
// in java/org/apache/el/parser/AstString.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return String.class; }
// in java/org/apache/el/parser/AstString.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.getString(); }
// in java/org/apache/el/parser/AstEmpty.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return Boolean.class; }
// in java/org/apache/el/parser/AstEmpty.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj = this.children[0].getValue(ctx); if (obj == null) { return Boolean.TRUE; } else if (obj instanceof String) { return Boolean.valueOf(((String) obj).length() == 0); } else if (obj instanceof Object[]) { return Boolean.valueOf(((Object[]) obj).length == 0); } else if (obj instanceof Collection<?>) { return Boolean.valueOf(((Collection<?>) obj).isEmpty()); } else if (obj instanceof Map<?,?>) { return Boolean.valueOf(((Map<?,?>) obj).isEmpty()); } return Boolean.FALSE; }
// in java/org/apache/el/parser/ArithmeticNode.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return Number.class; }
// in java/org/apache/el/parser/AstNot.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return Boolean.class; }
// in java/org/apache/el/parser/AstNot.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj = this.children[0].getValue(ctx); Boolean b = coerceToBoolean(obj); return Boolean.valueOf(!b.booleanValue()); }
// in java/org/apache/el/parser/AstAnd.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj = children[0].getValue(ctx); Boolean b = coerceToBoolean(obj); if (!b.booleanValue()) { return b; } obj = children[1].getValue(ctx); b = coerceToBoolean(obj); return b; }
// in java/org/apache/el/parser/AstDotSuffix.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.image; }
// in java/org/apache/el/parser/AstGreaterThanEqual.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); if (obj0 == obj1) { return Boolean.TRUE; } if (obj0 == null || obj1 == null) { return Boolean.FALSE; } return (compare(obj0, obj1) >= 0) ? Boolean.TRUE : Boolean.FALSE; }
// in java/org/apache/el/parser/AstInteger.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return this.getInteger().getClass(); }
// in java/org/apache/el/parser/AstInteger.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.getInteger(); }
// in java/org/apache/el/parser/AstGreaterThan.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); if (obj0 == null) { return Boolean.FALSE; } Object obj1 = this.children[1].getValue(ctx); if (obj1 == null) { return Boolean.FALSE; } return (compare(obj0, obj1) > 0) ? Boolean.TRUE : Boolean.FALSE; }
// in java/org/apache/el/parser/AstBracketSuffix.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.children[0].getValue(ctx); }
// in java/org/apache/el/parser/AstLiteralExpression.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return String.class; }
// in java/org/apache/el/parser/AstLiteralExpression.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.image; }
// in java/org/apache/el/parser/AstFalse.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return Boolean.FALSE; }
// in java/org/apache/el/parser/AstPlus.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); return ELArithmetic.add(obj0, obj1); }
// in java/org/apache/el/parser/AstDiv.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); return ELArithmetic.divide(obj0, obj1); }
// in java/org/apache/el/parser/AstLessThan.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); if (obj0 == null) { return Boolean.FALSE; } Object obj1 = this.children[1].getValue(ctx); if (obj1 == null) { return Boolean.FALSE; } return (compare(obj0, obj1) < 0) ? Boolean.TRUE : Boolean.FALSE; }
// in java/org/apache/el/parser/AstNull.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return null; }
// in java/org/apache/el/parser/AstNull.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return null; }
// in java/org/apache/el/parser/AstMod.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); return ELArithmetic.mod(obj0, obj1); }
// in java/org/apache/el/parser/AstChoice.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { Object val = this.getValue(ctx); return (val != null) ? val.getClass() : null; }
// in java/org/apache/el/parser/AstChoice.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Boolean b0 = coerceToBoolean(obj0); return this.children[((b0.booleanValue() ? 1 : 2))].getValue(ctx); }
// in java/org/apache/el/parser/AstDynamicExpression.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return this.children[0].getType(ctx); }
// in java/org/apache/el/parser/AstDynamicExpression.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.children[0].getValue(ctx); }
// in java/org/apache/el/parser/AstDynamicExpression.java
Override public boolean isReadOnly(EvaluationContext ctx) throws ELException { return this.children[0].isReadOnly(ctx); }
// in java/org/apache/el/parser/AstDynamicExpression.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { this.children[0].setValue(ctx, value); }
// in java/org/apache/el/parser/AstNotEqual.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); return Boolean.valueOf(!equals(obj0, obj1)); }
// in java/org/apache/el/parser/AstCompositeExpression.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return String.class; }
// in java/org/apache/el/parser/AstCompositeExpression.java
Override public Object getValue(EvaluationContext ctx) throws ELException { StringBuilder sb = new StringBuilder(16); Object obj = null; if (this.children != null) { for (int i = 0; i < this.children.length; i++) { obj = this.children[i].getValue(ctx); if (obj != null) { sb.append(ELSupport.coerceToString(obj)); } } } return sb.toString(); }
// in java/org/apache/el/parser/AstOr.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj = this.children[0].getValue(ctx); Boolean b = coerceToBoolean(obj); if (b.booleanValue()) { return b; } obj = this.children[1].getValue(ctx); b = coerceToBoolean(obj); return b; }
// in java/org/apache/el/parser/AstMinus.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); return ELArithmetic.subtract(obj0, obj1); }
// in java/org/apache/el/parser/AstFloatingPoint.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return this.getFloatingPoint(); }
// in java/org/apache/el/parser/AstFloatingPoint.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return this.getFloatingPoint().getClass(); }
// in java/org/apache/el/parser/AstNegative.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return Number.class; }
// in java/org/apache/el/parser/AstNegative.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj = this.children[0].getValue(ctx); if (obj == null) { return Long.valueOf(0); } if (obj instanceof BigDecimal) { return ((BigDecimal) obj).negate(); } if (obj instanceof BigInteger) { return ((BigInteger) obj).negate(); } if (obj instanceof String) { if (isStringFloat((String) obj)) { return new Double(-Double.parseDouble((String) obj)); } return Long.valueOf(-Long.parseLong((String) obj)); } if (obj instanceof Long) { return Long.valueOf(-((Long) obj).longValue()); } if (obj instanceof Double) { return new Double(-((Double) obj).doubleValue()); } if (obj instanceof Integer) { return Integer.valueOf(-((Integer) obj).intValue()); } if (obj instanceof Float) { return new Float(-((Float) obj).floatValue()); } if (obj instanceof Short) { return Short.valueOf((short) -((Short) obj).shortValue()); } if (obj instanceof Byte) { return Byte.valueOf((byte) -((Byte) obj).byteValue()); } Long num = (Long) coerceToNumber(obj, Long.class); return Long.valueOf(-num.longValue()); }
// in java/org/apache/el/parser/AstLessThanEqual.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); if (obj0 == obj1) { return Boolean.TRUE; } if (obj0 == null || obj1 == null) { return Boolean.FALSE; } return (compare(obj0, obj1) <= 0) ? Boolean.TRUE : Boolean.FALSE; }
// in java/org/apache/el/parser/AstTrue.java
Override public Object getValue(EvaluationContext ctx) throws ELException { return Boolean.TRUE; }
// in java/org/apache/el/parser/AstEqual.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object obj0 = this.children[0].getValue(ctx); Object obj1 = this.children[1].getValue(ctx); return Boolean.valueOf(equals(obj0, obj1)); }
// in java/org/apache/el/parser/AstValue.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { Target t = getTarget(ctx); ctx.setPropertyResolved(false); Class<?> result = ctx.getELResolver().getType(ctx, t.base, t.property); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", t.base, t.property)); } return result; }
// in java/org/apache/el/parser/AstValue.java
private final Target getTarget(EvaluationContext ctx) throws ELException { // evaluate expr-a to value-a Object base = this.children[0].getValue(ctx); // if our base is null (we know there are more properties to evaluate) if (base == null) { throw new PropertyNotFoundException(MessageFactory.get( "error.unreachable.base", this.children[0].getImage())); } // set up our start/end Object property = null; int propCount = this.jjtGetNumChildren(); if (propCount > 2 && this.jjtGetChild(propCount - 1) instanceof AstMethodParameters) { // Method call with paramaters. propCount-=2; } else { propCount--; } int i = 1; // evaluate any properties before our target ELResolver resolver = ctx.getELResolver(); if (propCount > 1) { while (base != null && i < propCount) { property = this.children[i].getValue(ctx); ctx.setPropertyResolved(false); base = resolver.getValue(ctx, base, property); i++; } // if we are in this block, we have more properties to resolve, // but our base was null if (base == null || property == null) { throw new PropertyNotFoundException(MessageFactory.get( "error.unreachable.property", property)); } } property = this.children[i].getValue(ctx); if (property == null) { throw new PropertyNotFoundException(MessageFactory.get( "error.unreachable.property", this.children[i])); } Target t = new Target(); t.base = base; t.property = property; return t; }
// in java/org/apache/el/parser/AstValue.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object base = this.children[0].getValue(ctx); int propCount = this.jjtGetNumChildren(); int i = 1; Object suffix = null; ELResolver resolver = ctx.getELResolver(); while (base != null && i < propCount) { suffix = this.children[i].getValue(ctx); if (i + 1 < propCount && (this.children[i+1] instanceof AstMethodParameters)) { AstMethodParameters mps = (AstMethodParameters) this.children[i+1]; // This is a method base = resolver.invoke(ctx, base, suffix, null, mps.getParameters(ctx)); i+=2; } else { // This is a property if (suffix == null) { return null; } ctx.setPropertyResolved(false); base = resolver.getValue(ctx, base, suffix); i++; } } if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", base, suffix)); } return base; }
// in java/org/apache/el/parser/AstValue.java
Override public boolean isReadOnly(EvaluationContext ctx) throws ELException { Target t = getTarget(ctx); ctx.setPropertyResolved(false); boolean result = ctx.getELResolver().isReadOnly(ctx, t.base, t.property); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", t.base, t.property)); } return result; }
// in java/org/apache/el/parser/AstValue.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { Target t = getTarget(ctx); ctx.setPropertyResolved(false); ELResolver resolver = ctx.getELResolver(); // coerce to the expected type Class<?> targetClass = resolver.getType(ctx, t.base, t.property); if (COERCE_TO_ZERO == true || !isAssignable(value, targetClass)) { resolver.setValue(ctx, t.base, t.property, ELSupport.coerceToType(value, targetClass)); } else { resolver.setValue(ctx, t.base, t.property, value); } if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", t.base, t.property)); } }
// in java/org/apache/el/parser/BooleanNode.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { return Boolean.class; }
// in java/org/apache/el/ValueExpressionImpl.java
private Node getNode() throws ELException { if (this.node == null) { this.node = ExpressionBuilder.createNode(this.expr); } return this.node; }
// in java/org/apache/el/ValueExpressionImpl.java
Override public Class<?> getType(ELContext context) throws PropertyNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return this.getNode().getType(ctx); }
// in java/org/apache/el/ValueExpressionImpl.java
Override public Object getValue(ELContext context) throws PropertyNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); Object value = this.getNode().getValue(ctx); if (this.expectedType != null) { return ELSupport.coerceToType(value, this.expectedType); } return value; }
// in java/org/apache/el/ValueExpressionImpl.java
Override public boolean isReadOnly(ELContext context) throws PropertyNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return this.getNode().isReadOnly(ctx); }
// in java/org/apache/el/ValueExpressionImpl.java
Override public void setValue(ELContext context, Object value) throws PropertyNotFoundException, PropertyNotWritableException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); this.getNode().setValue(ctx, value); }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { PageContext page = (PageContext) context .getContext(JspContext.class); context.setPropertyResolved(true); switch (idx) { case APPLICATIONSCOPE: return ScopeManager.get(page).getApplicationScope(); case COOKIE: return ScopeManager.get(page).getCookie(); case HEADER: return ScopeManager.get(page).getHeader(); case HEADERVALUES: return ScopeManager.get(page).getHeaderValues(); case INITPARAM: return ScopeManager.get(page).getInitParam(); case PAGECONTEXT: return ScopeManager.get(page).getPageContext(); case PAGESCOPE: return ScopeManager.get(page).getPageScope(); case PARAM: return ScopeManager.get(page).getParam(); case PARAM_VALUES: return ScopeManager.get(page).getParamValues(); case REQUEST_SCOPE: return ScopeManager.get(page).getRequestScope(); case SESSION_SCOPE: return ScopeManager.get(page).getSessionScope(); } } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
public Class getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); throw new PropertyNotWritableException(); } } }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); return true; } } return false; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); return page.findAttribute(key); } } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Class<Object> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); int scope = page.getAttributesScope(key); if (scope != 0) { page.setAttribute(key, value, scope); } else { page.setAttribute(key, value); } } } }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); } return false; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); if (property != null) { try { return ((ResourceBundle) base).getObject(property .toString()); } catch (MissingResourceException mre) { return "???" + property.toString() + "???"; } } } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } }
// in java/javax/el/ResourceBundleELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return true; }
// in java/javax/el/CompositeELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; Object result = null; for (int i = 0; i < sz; i++) { result = this.resolvers[i].getValue(context, base, property); if (context.isPropertyResolved()) { return result; } } return null; }
// in java/javax/el/CompositeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { context.setPropertyResolved(false); int sz = this.size; for (int i = 0; i < sz; i++) { this.resolvers[i].setValue(context, base, property, value); if (context.isPropertyResolved()) { return; } } }
// in java/javax/el/CompositeELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; boolean readOnly = false; for (int i = 0; i < sz; i++) { readOnly = this.resolvers[i].isReadOnly(context, base, property); if (context.isPropertyResolved()) { return readOnly; } } return false; }
// in java/javax/el/CompositeELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; Class<?> type; for (int i = 0; i < sz; i++) { type = this.resolvers[i].getType(context, base, property); if (context.isPropertyResolved()) { if (SCOPED_ATTRIBUTE_EL_RESOLVER != null && SCOPED_ATTRIBUTE_EL_RESOLVER.isAssignableFrom( resolvers[i].getClass())) { // Special case since // javax.servlet.jsp.el.ScopedAttributeELResolver will // always return Object.class for type Object value = resolvers[i].getValue(context, base, property); if (value != null) { return value.getClass(); } } return type; } } return null; }
// in java/javax/el/ArrayELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); if (idx < 0 || idx >= Array.getLength(base)) { return null; } return Array.get(base, idx); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); return base.getClass().getComponentType(); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); checkBounds(base, idx); if (value != null && !base.getClass().getComponentType().isAssignableFrom( value.getClass())) { throw new ClassCastException(message(context, "objectNotAssignable", new Object[] {value.getClass().getName(), base.getClass().getComponentType().getName()})); } Array.set(base, idx, value); } }
// in java/javax/el/ArrayELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); } return this.readOnly; }
// in java/javax/el/MapELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return ((Map<?,?>) base).get(property); } return null; }
// in java/javax/el/MapELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/el/MapELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } try { @SuppressWarnings("unchecked") // Must be OK Map<Object, Object> map = ((Map<Object, Object>) base); map.put(property, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } } }
// in java/javax/el/MapELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); return this.readOnly || UNMODIFIABLE.equals(base.getClass()); } return this.readOnly; }
// in java/javax/el/BeanELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); Method m = this.property(context, base, property).read(context); try { return m.invoke(base, (Object[]) null); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); return this.property(context, base, property).getPropertyType(); }
// in java/javax/el/BeanELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return; } context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } Method m = this.property(context, base, property).write(context); try { m.invoke(base, value); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return false; } context.setPropertyResolved(true); return this.readOnly || this.property(context, base, property).isReadOnly(); }
// in java/javax/el/ListELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { return null; } return list.get(idx); } return null; }
// in java/javax/el/ListELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return Object.class; } return null; }
// in java/javax/el/ListELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); @SuppressWarnings("unchecked") // Must be OK to cast to Object List<Object> list = (List<Object>) base; if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); try { list.set(idx, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); } } }
// in java/javax/el/ListELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return this.readOnly || UNMODIFIABLE.equals(list.getClass()); } return this.readOnly; }
15
            
// in java/org/apache/jasper/compiler/Validator.java
catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", attrs.getValue(i), e.toString()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", value, e .toString()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (ELException e) { }
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/jasper/el/ExpressionEvaluatorImpl.java
catch (javax.el.ELException e) { throw new ELParseException(e.getMessage()); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/el/parser/AstFunction.java
catch (ELException ele) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), ele); }
// in java/org/apache/el/ValueExpressionImpl.java
catch (ELException ele) { return false; }
// in java/org/apache/el/util/ReflectionUtil.java
catch (ELException e) { return false; }
16
            
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/jasper/el/ELResolverImpl.java
catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); }
// in java/org/apache/jasper/el/ExpressionEvaluatorImpl.java
catch (javax.el.ELException e) { throw new ELParseException(e.getMessage()); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/el/parser/AstFunction.java
catch (ELException ele) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), ele); }
9
unknown (Lib) ELParseException 1 1
            
// in java/org/apache/jasper/el/ExpressionEvaluatorImpl.java
catch (javax.el.ELException e) { throw new ELParseException(e.getMessage()); }
0 0 0 0
unknown (Lib) EOFException 44
            
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
final boolean load(int offset, boolean changeEntity) throws IOException { // read characters int length = fCurrentEntity.mayReadChunks? (fCurrentEntity.ch.length - offset): (DEFAULT_XMLDECL_BUFFER_SIZE); int count = fCurrentEntity.reader.read(fCurrentEntity.ch, offset, length); // reset count and position boolean entityChanged = false; if (count != -1) { if (count != 0) { fCurrentEntity.count = count + offset; fCurrentEntity.position = offset; } } // end of this entity else { fCurrentEntity.count = offset; fCurrentEntity.position = offset; entityChanged = true; if (changeEntity) { endEntity(); if (fCurrentEntity == null) { throw new EOFException(); } // handle the trailing edges if (fCurrentEntity.position == fCurrentEntity.count) { load(0, false); } } } return entityChanged; }
// in java/org/apache/jasper/JspC.java
protected void mergeIntoWebXml() throws IOException { File webappBase = new File(uriRoot); File webXml = new File(webappBase, "WEB-INF/web.xml"); File webXml2 = new File(webappBase, "WEB-INF/web2.xml"); String insertStartMarker = Localizer.getMessage("jspc.webinc.insertStart"); String insertEndMarker = Localizer.getMessage("jspc.webinc.insertEnd"); BufferedReader reader = new BufferedReader(openWebxmlReader(webXml)); BufferedReader fragmentReader = new BufferedReader( openWebxmlReader(new File(webxmlFile))); PrintWriter writer = new PrintWriter(openWebxmlWriter(webXml2)); // Insert the <servlet> and <servlet-mapping> declarations boolean inserted = false; int current = reader.read(); while (current > -1) { if (current == '<') { String element = getElement(reader); if (!inserted && insertBefore.contains(element)) { // Insert generated content here writer.println(insertStartMarker); while (true) { String line = fragmentReader.readLine(); if (line == null) { writer.println(); break; } writer.println(line); } writer.println(insertEndMarker); writer.println(); writer.write(element); inserted = true; } else if (element.equals(insertStartMarker)) { // Skip the previous auto-generated content while (true) { current = reader.read(); if (current < 0) { throw new EOFException(); } if (current == '<') { element = getElement(reader); if (element.equals(insertEndMarker)) { break; } } } current = reader.read(); while (current == '\n' || current == '\r') { current = reader.read(); } continue; } else { writer.write(element); } } else { writer.write(current); } current = reader.read(); } writer.close(); reader.close(); fragmentReader.close(); FileInputStream fis = new FileInputStream(webXml2); FileOutputStream fos = new FileOutputStream(webXml); byte buf[] = new byte[512]; while (true) { int n = fis.read(buf); if (n < 0) { break; } fos.write(buf, 0, n); } fis.close(); fos.close(); if(!webXml2.delete() && log.isDebugEnabled()) log.debug(Localizer.getMessage("jspc.delete.fail", webXml2.toString())); if (!(new File(webxmlFile)).delete() && log.isDebugEnabled()) log.debug(Localizer.getMessage("jspc.delete.fail", webxmlFile)); }
// in java/org/apache/jasper/JspC.java
private String getElement(Reader reader) throws IOException { StringBuilder result = new StringBuilder(); result.append('<'); boolean done = false; while (!done) { int current = reader.read(); while (current != '>') { if (current < 0) { throw new EOFException(); } result.append((char) current); current = reader.read(); } result.append((char) current); int len = result.length(); if (len > 4 && result.substring(0, 4).equals("<!--")) { // This is a comment - make sure we are at the end if (len >= 7 && result.substring(len - 3, len).equals("-->")) { done = true; } } else { done = true; } } return result.toString(); }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
private int readSocket(byte[] buf, int pos, int n, boolean block) throws IOException { int nRead = 0; socket.getBufHandler().getReadBuffer().clear(); socket.getBufHandler().getReadBuffer().limit(n); if ( block ) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled."); nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout()); } catch ( EOFException eof ) { nRead = -1; } finally { if ( selector != null ) pool.put(selector); } } else { nRead = socket.read(socket.getBufHandler().getReadBuffer()); } if (nRead > 0) { socket.getBufHandler().getReadBuffer().flip(); socket.getBufHandler().getReadBuffer().limit(nRead); socket.getBufHandler().getReadBuffer().get(buf, pos, nRead); return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("iib.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
private int readSocket(boolean timeout, boolean block) throws IOException { int nRead = 0; socket.getBufHandler().getReadBuffer().clear(); if ( block ) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled."); nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout()); } catch ( EOFException eof ) { nRead = -1; } finally { if ( selector != null ) pool.put(selector); } } else { nRead = socket.read(socket.getBufHandler().getReadBuffer()); } if (nRead > 0) { socket.getBufHandler().getReadBuffer().flip(); socket.getBufHandler().getReadBuffer().limit(nRead); expand(nRead + pos); socket.getBufHandler().getReadBuffer().get(buf, pos, nRead); lastValid = pos + nRead; return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("iib.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
private int readSocket(boolean block, byte[] bytes, int offset, int len) throws IOException { int nRead = 0; nioChannel.getBufHandler().getReadBuffer().clear(); nioChannel.getBufHandler().getReadBuffer().limit(len); if (block) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) nioChannel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled."); } nRead = pool.read(nioChannel.getBufHandler().getReadBuffer(), nioChannel, selector, att.getTimeout()); } catch (EOFException eof) { nRead = -1; } finally { if (selector != null) { pool.put(selector); } } } else { nRead = nioChannel.read(nioChannel.getBufHandler().getReadBuffer()); } if (nRead > 0) { nioChannel.getBufHandler().getReadBuffer().flip(); nioChannel.getBufHandler().getReadBuffer().limit(nRead); nioChannel.getBufHandler().getReadBuffer().get(bytes, offset, nRead); return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("nio.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
private boolean parseHeader() throws IOException { MimeHeaders headers = request.getMimeHeaders(); byte chr = 0; while (true) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr == Constants.CR) || (chr == Constants.LF)) { if (chr == Constants.LF) { pos++; return false; } } else { break; } pos++; } // Mark the current buffer position int start = trailingHeaders.getEnd(); // // Reading the header name // Header name is always US-ASCII // boolean colon = false; while (!colon) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr >= Constants.A) && (chr <= Constants.Z)) { chr = (byte) (chr - Constants.LC_OFFSET); } if (chr == Constants.COLON) { colon = true; } else { trailingHeaders.append(chr); } pos++; } MessageBytes headerValue = headers.addValue(trailingHeaders.getBytes(), start, trailingHeaders.getEnd() - start); // Mark the current buffer position start = trailingHeaders.getEnd(); // // Reading the header value (which can be spanned over multiple lines) // boolean eol = false; boolean validLine = true; int lastSignificantChar = 0; while (validLine) { boolean space = true; // Skipping spaces while (space) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr == Constants.SP) || (chr == Constants.HT)) { pos++; } else { space = false; } } // Reading bytes until the end of the line while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if (chr == Constants.CR) { // Skip } else if (chr == Constants.LF) { eol = true; } else if (chr == Constants.SP) { trailingHeaders.append(chr); } else { trailingHeaders.append(chr); lastSignificantChar = trailingHeaders.getEnd(); } pos++; } // Checking the first character of the new line. If the character // is a LWS, then it's a multiline header // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr != Constants.SP) && (chr != Constants.HT)) { validLine = false; } else { eol = false; // Copying one extra space in the buffer (since there must // be at least one space inserted between the lines) trailingHeaders.append(chr); } } // Set the header value headerValue.setBytes(trailingHeaders.getBytes(), start, lastSignificantChar - start); return true; }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableDataOnly) throws IOException { int start = 0; // // Skipping blank lines // byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; // Mark the current buffer position start = pos; // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, start, pos - start); } pos++; } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; int end = 0; int questionPos = -1; // // Reading the URI // boolean eol = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request eol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (questionPos == -1)) { questionPos = pos; } pos++; } request.unparsedURI().setBytes(buf, start, end - start); if (questionPos >= 0) { request.queryString().setBytes(buf, questionPos + 1, end - questionPos - 1); request.requestURI().setBytes(buf, start, questionPos - start); } else { request.requestURI().setBytes(buf, start, end - start); } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; eol = true; } pos++; } if ((end - start) > 0) { request.protocol().setBytes(buf, start, end - start); } else { request.protocol().setString(""); } return true; }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
private void skipLine(int start) throws IOException { boolean eol = false; int lastRealByte = start; if (pos - 1 > start) { lastRealByte = pos - 1; } while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { // Skip } else if (buf[pos] == Constants.LF) { eol = true; } else { lastRealByte = pos; } pos++; } if (log.isDebugEnabled()) { log.debug(sm.getString("iib.invalidheader", new String(buf, start, lastRealByte - start + 1, Charset.forName("ISO-8859-1")))); } }
// in java/org/apache/coyote/http11/Http11Processor.java
Override protected void setRequestLineReadTimeout() throws IOException { /* * When there is no data in the buffer and this is not the first * request on this connection and timeouts are being used the * first read for this request may need a different timeout to * take account of time spent waiting for a processing thread. * * This is a little hacky but better than exposing the socket * and the timeout info to the InputBuffer */ if (inputBuffer.lastValid == 0 && socket.getLastAccess() > -1) { int firstReadTimeout; if (keepAliveTimeout == -1) { firstReadTimeout = 0; } else { long queueTime = System.currentTimeMillis() - socket.getLastAccess(); if (queueTime >= keepAliveTimeout) { // Queued for longer than timeout but there might be // data so use shortest possible timeout firstReadTimeout = 1; } else { // Cast is safe since queueTime must be less than // keepAliveTimeout which is an int firstReadTimeout = keepAliveTimeout - (int) queueTime; } } socket.getSocket().setSoTimeout(firstReadTimeout); if (!inputBuffer.fill()) { throw new EOFException(sm.getString("iib.eof.error")); } // Once the first byte has been read, the standard timeout should be // used so restore it here. socket.getSocket().setSoTimeout(endpoint.getSoTimeout()); } }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableData) throws IOException { int start = 0; // // Skipping blank lines // byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (useAvailableData) { return false; } if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; // Mark the current buffer position start = pos; if (pos >= lastValid) { if (useAvailableData) { return false; } if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, start, pos - start); } pos++; } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; int end = 0; int questionPos = -1; // // Reading the URI // boolean eol = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request eol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (questionPos == -1)) { questionPos = pos; } pos++; } request.unparsedURI().setBytes(buf, start, end - start); if (questionPos >= 0) { request.queryString().setBytes(buf, questionPos + 1, end - questionPos - 1); request.requestURI().setBytes(buf, start, questionPos - start); } else { request.requestURI().setBytes(buf, start, end - start); } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; eol = true; } pos++; } if ((end - start) > 0) { request.protocol().setBytes(buf, start, end - start); } else { request.protocol().setString(""); } return true; }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
private void skipLine(int start) throws IOException { boolean eol = false; int lastRealByte = start; if (pos - 1 > start) { lastRealByte = pos - 1; } while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { // Skip } else if (buf[pos] == Constants.LF) { eol = true; } else { lastRealByte = pos; } pos++; } if (log.isDebugEnabled()) { log.debug(sm.getString("iib.invalidheader", new String(buf, start, lastRealByte - start + 1, Charset.forName("ISO-8859-1")))); } }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int write(ByteBuffer buf, NioChannel socket, long writeTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int written = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) && buf.hasRemaining()) { if (keycount > 0) { //only write if we were registered for a write int cnt = socket.write(buf); //write the data if (cnt == -1) throw new EOFException(); written += cnt; if (cnt > 0) { time = System.currentTimeMillis(); //reset our timeout timer continue; //we successfully wrote, try again without a selector } } try { if ( att.getWriteLatch()==null || att.getWriteLatch().getCount()==0) att.startWriteLatch(1); poller.add(att,SelectionKey.OP_WRITE,reference); if (writeTimeout < 0) { att.awaitWriteLatch(Long.MAX_VALUE,TimeUnit.MILLISECONDS); } else { att.awaitWriteLatch(writeTimeout,TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getWriteLatch()!=null && att.getWriteLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetWriteLatch(); } if (writeTimeout > 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= writeTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_WRITE); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return written; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int read(ByteBuffer buf, NioChannel socket, long readTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int read = 0; boolean timedout = false; int keycount = 1; //assume we can read long time = System.currentTimeMillis(); //start the timeout timer try { while(!timedout) { if (keycount > 0) { //only read if we were registered for a read read = socket.read(buf); if (read == -1) throw new EOFException(); if (read > 0) break; } try { if ( att.getReadLatch()==null || att.getReadLatch().getCount()==0) att.startReadLatch(1); poller.add(att,SelectionKey.OP_READ, reference); if (readTimeout < 0) { att.awaitReadLatch(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } else { att.awaitReadLatch(readTimeout, TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getReadLatch()!=null && att.getReadLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetReadLatch(); } if (readTimeout >= 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= readTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_READ); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return read; }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int write(ByteBuffer buf, NioChannel socket, Selector selector, long writeTimeout, boolean block) throws IOException { if ( SHARED && block ) { return blockingSelector.write(buf,socket,writeTimeout); } SelectionKey key = null; int written = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) && buf.hasRemaining() ) { int cnt = 0; if ( keycount > 0 ) { //only write if we were registered for a write cnt = socket.write(buf); //write the data if (cnt == -1) throw new EOFException(); written += cnt; if (cnt > 0) { time = System.currentTimeMillis(); //reset our timeout timer continue; //we successfully wrote, try again without a selector } if (cnt==0 && (!block)) break; //don't block } if ( selector != null ) { //register OP_WRITE to the selector if (key==null) key = socket.getIOChannel().register(selector, SelectionKey.OP_WRITE); else key.interestOps(SelectionKey.OP_WRITE); keycount = selector.select(writeTimeout); } if (writeTimeout > 0 && (selector == null || keycount == 0) ) timedout = (System.currentTimeMillis()-time)>=writeTimeout; }//while if ( timedout ) throw new SocketTimeoutException(); } finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } } return written; }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int read(ByteBuffer buf, NioChannel socket, Selector selector, long readTimeout, boolean block) throws IOException { if ( SHARED && block ) { return blockingSelector.read(buf,socket,readTimeout); } SelectionKey key = null; int read = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) ) { int cnt = 0; if ( keycount > 0 ) { //only read if we were registered for a read cnt = socket.read(buf); if (cnt == -1) throw new EOFException(); read += cnt; if (cnt > 0) continue; //read some more if (cnt==0 && (read>0 || (!block) ) ) break; //we are done reading } if ( selector != null ) {//perform a blocking read //register OP_WRITE to the selector if (key==null) key = socket.getIOChannel().register(selector, SelectionKey.OP_READ); else key.interestOps(SelectionKey.OP_READ); keycount = selector.select(readTimeout); } if (readTimeout > 0 && (selector == null || keycount == 0) ) timedout = (System.currentTimeMillis()-time)>=readTimeout; }//while if ( timedout ) throw new SocketTimeoutException(); } finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } } return read; }
// in java/org/apache/catalina/websocket/WsFrame.java
public static WsFrame nextFrame(UpgradeProcessor<?> processor, boolean block) throws IOException { byte[] first = new byte[1]; int read = processor.read(block, first, 0, 1); if (read == 1) { return new WsFrame(first[0], processor); } else if (read == 0) { return null; } else if (read == -1) { throw new EOFException(sm.getString("frame.readEos")); } else { throw new IOException( sm.getString("frame.readFailed", Integer.valueOf(read))); } }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
protected boolean write() throws IOException { if ( (!isConnected()) || (this.socketChannel==null && this.dataChannel==null)) { throw new IOException("NioSender is not connected, this should not occur."); } if ( current != null ) { if ( remaining > 0 ) { //we have written everything, or we are starting a new package //protect against buffer overwrite int byteswritten = isUdpBased()?dataChannel.write(writebuf) : socketChannel.write(writebuf); if (byteswritten == -1 ) throw new EOFException(); remaining -= byteswritten; //if the entire message was written from the buffer //reset the position counter if ( remaining < 0 ) { remaining = 0; } } return (remaining==0); } //no message to send, we can consider that complete return true; }
0 2
            
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override protected boolean fill(boolean block) throws IOException, EOFException { return fill(true,block); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
protected boolean fill(boolean timeout, boolean block) throws IOException, EOFException { boolean read = false; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } // Do a simple read with a short timeout read = readSocket(timeout,block)>0; } else { lastValid = pos = end; // Do a simple read with a short timeout read = readSocket(timeout, block)>0; } return read; }
3
            
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch ( EOFException eof ) { nRead = -1; }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
catch ( EOFException eof ) { nRead = -1; }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
catch (EOFException eof) { nRead = -1; }
0 0
unknown (Lib) EmptyStackException 5
            
// in java/org/apache/tomcat/util/digester/Digester.java
public Object pop(String stackName) { Object result = null; ArrayStack<Object> namedStack = stacksByName.get(stackName); if (namedStack == null) { if (log.isDebugEnabled()) { log.debug("Stack '" + stackName + "' is empty"); } throw new EmptyStackException(); } else { result = namedStack.pop(); } return result; }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object peek(String stackName) { Object result = null; ArrayStack<Object> namedStack = stacksByName.get(stackName); if (namedStack == null ) { if (log.isDebugEnabled()) { log.debug("Stack '" + stackName + "' is empty"); } throw new EmptyStackException(); } else { result = namedStack.peek(); } return result; }
// in java/org/apache/tomcat/util/digester/ArrayStack.java
public E peek() throws EmptyStackException { int n = size(); if (n <= 0) { throw new EmptyStackException(); } else { return get(n - 1); } }
// in java/org/apache/tomcat/util/digester/ArrayStack.java
public E peek(int n) throws EmptyStackException { int m = (size() - n) - 1; if (m < 0) { throw new EmptyStackException(); } else { return get(m); } }
// in java/org/apache/tomcat/util/digester/ArrayStack.java
public E pop() throws EmptyStackException { int n = size(); if (n <= 0) { throw new EmptyStackException(); } else { return remove(n - 1); } }
0 3
            
// in java/org/apache/tomcat/util/digester/ArrayStack.java
public E peek() throws EmptyStackException { int n = size(); if (n <= 0) { throw new EmptyStackException(); } else { return get(n - 1); } }
// in java/org/apache/tomcat/util/digester/ArrayStack.java
public E peek(int n) throws EmptyStackException { int m = (size() - n) - 1; if (m < 0) { throw new EmptyStackException(); } else { return get(m); } }
// in java/org/apache/tomcat/util/digester/ArrayStack.java
public E pop() throws EmptyStackException { int n = size(); if (n <= 0) { throw new EmptyStackException(); } else { return remove(n - 1); } }
9
            
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { throw createSAXException("endPrefixMapping popped too many times"); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); }
// in java/org/apache/tomcat/util/log/SystemLogHandler.java
catch (EmptyStackException e) { log = new CaptureLog(); }
1
            
// in java/org/apache/tomcat/util/digester/Digester.java
catch (EmptyStackException e) { throw createSAXException("endPrefixMapping popped too many times"); }
0
unknown (Domain) EnableDTDValidationException
private static class EnableDTDValidationException
            extends SAXParseException {

        private static final long serialVersionUID = 1L;

        EnableDTDValidationException(String message, Locator loc) {
            super(message, loc);
        }

        @Override
        public synchronized Throwable fillInStackTrace() {
            // This class does not provide a stack trace
            return this;
        }
    }
0 0 0 1
            
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (EnableDTDValidationException e) { saxParser = getSAXParser(true, jspDocParser); jspDocParser.isValidating = true; if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } inStream = JspUtil.getInputStream(path, jarFile, jspDocParser.ctxt); saxParser.parse(new InputSource(inStream), jspDocParser); }
0 0
runtime (Domain) Error
public class Error extends Exception {

    private static final long serialVersionUID = 1L;

    /**
     * APR error type.
     */
    private int error;

    /**
     * A description of the problem.
     */
    private String description;

    /**
     * Construct an APRException.
     *
     * @param error one of the value in Error
     * @param description error message
     */
    private Error(int error, String description)
    {
        super(error + ": " + description);
        this.error = error;
        this.description = description;
    }

    /**
     * Get the APR error code of the exception.
     *
     * @return error of the Exception
     */
    public int getError()
    {
        return error;
    }

    /**
     * Get the APR description of the exception.
     *
     * @return description of the Exception
     */
    public String getDescription()
    {
        return description;
    }

    /**
     * Get the last platform error.
     * @return apr_status_t the last platform error, folded into apr_status_t, on most platforms
     * This retrieves errno, or calls a GetLastError() style function, and
     *      folds it with APR_FROM_OS_ERROR.  Some platforms (such as OS2) have no
     *      such mechanism, so this call may be unsupported.  Do NOT use this
     *      call for socket errors from socket, send, recv etc!
     */
    public static native int osError();

    /**
     * Get the last platform socket error.
     * @return the last socket error, folded into apr_status_t, on all platforms
     * This retrieves errno or calls a GetLastSocketError() style function,
     *      and folds it with APR_FROM_OS_ERROR.
     */
    public static native int netosError();

    /**
     * Return a human readable string describing the specified error.
     * @param statcode The error code the get a string for.
     * @return The error string.
    */
    public static native String strerror(int statcode);

}
10
            
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Throwable t) { throw new Error(t.getMessage()); } bufsize += 2048; available = bufsize; tokenBegin = 0; }
// in java/org/apache/el/parser/SimpleCharStream.java
protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Throwable t) { throw new Error(t.getMessage()); } bufsize += 2048; available = bufsize; tokenBegin = 0; }
// in java/org/apache/el/parser/ELParser.java
final public AstCompositeExpression CompositeExpression() throws ParseException { /*@bgen(jjtree) CompositeExpression */ AstCompositeExpression jjtn000 = new AstCompositeExpression(JJTCOMPOSITEEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { label_1: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LITERAL_EXPRESSION: case START_DYNAMIC_EXPRESSION: case START_DEFERRED_EXPRESSION: ; break; default: jj_la1[0] = jj_gen; break label_1; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case START_DEFERRED_EXPRESSION: DeferredExpression(); break; case START_DYNAMIC_EXPRESSION: DynamicExpression(); break; case LITERAL_EXPRESSION: LiteralExpression(); break; default: jj_la1[1] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } jj_consume_token(0); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; {if (true) return jjtn000;} } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } throw new Error("Missing return statement in function"); }
// in java/org/apache/catalina/startup/Catalina.java
public void load() { long t1 = System.nanoTime(); initDirs(); // Before digester - it may be needed initNaming(); // Create and execute our Digester Digester digester = createStartDigester(); InputSource inputSource = null; InputStream inputStream = null; File file = null; try { file = configFile(); inputStream = new FileInputStream(file); inputSource = new InputSource(file.toURI().toURL().toString()); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", file), e); } } if (inputStream == null) { try { inputStream = getClass().getClassLoader() .getResourceAsStream(getConfigFile()); inputSource = new InputSource (getClass().getClassLoader() .getResource(getConfigFile()).toString()); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", getConfigFile()), e); } } } // This should be included in catalina.jar // Alternative: don't bother with xml, just create it manually. if( inputStream==null ) { try { inputStream = getClass().getClassLoader() .getResourceAsStream("server-embed.xml"); inputSource = new InputSource (getClass().getClassLoader() .getResource("server-embed.xml").toString()); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", "server-embed.xml"), e); } } } if (inputStream == null || inputSource == null) { if (file == null) { log.warn(sm.getString("catalina.configFail", getConfigFile() + "] or [server-embed.xml]")); } else { log.warn(sm.getString("catalina.configFail", file.getAbsolutePath())); if (file.exists() && !file.canRead()) { log.warn("Permissions incorrect, read permission is not allowed on the file."); } } return; } try { inputSource.setByteStream(inputStream); digester.push(this); digester.parse(inputSource); } catch (SAXParseException spe) { log.warn("Catalina.start using " + getConfigFile() + ": " + spe.getMessage()); return; } catch (Exception e) { log.warn("Catalina.start using " + getConfigFile() + ": " , e); return; } finally { try { inputStream.close(); } catch (IOException e) { // Ignore } } getServer().setCatalina(this); getServer().setCatalinaHome(Bootstrap.getCatalinaHomeFile()); getServer().setCatalinaBase(Bootstrap.getCatalinaBaseFile()); // Stream redirection initStreams(); // Start the new server try { getServer().init(); } catch (LifecycleException e) { if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) { throw new java.lang.Error(e); } else { log.error("Catalina.start", e); } } long t2 = System.nanoTime(); if(log.isInfoEnabled()) { log.info("Initialization processed in " + ((t2 - t1) / 1000000) + " ms"); } }
// in java/org/apache/catalina/security/SecurityListener.java
protected void checkOsUser() { String userName = System.getProperty("user.name"); if (userName != null) { String userNameLC = userName.toLowerCase(); if (checkedOsUsers.contains(userNameLC)) { // Have to throw Error to force start process to be aborted throw new Error(sm.getString( "SecurityListener.checkUserWarning", userName)); } } }
// in java/org/apache/catalina/security/SecurityListener.java
protected void checkUmask() { String prop = System.getProperty(UMASK_PROPERTY_NAME); Integer umask = null; if (prop != null) { try { umask = Integer.valueOf(prop, 8); } catch (NumberFormatException nfe) { log.warn(sm.getString("SecurityListener.checkUmaskParseFail", prop)); } } if (umask == null) { if (Constants.CRLF.equals(Constants.LINE_SEP)) { // Probably running on Windows so no umask if (log.isDebugEnabled()) { log.debug(sm.getString("SecurityListener.checkUmaskSkip")); } return; } else { if (minimumUmask.intValue() > 0) { log.warn(sm.getString( "SecurityListener.checkUmaskNone", UMASK_PROPERTY_NAME, getMinimumUmask())); } return; } } if ((umask.intValue() & minimumUmask.intValue()) != minimumUmask.intValue()) { throw new Error(sm.getString("SecurityListener.checkUmaskFail", String.format(UMASK_FORMAT, umask), getMinimumUmask())); } }
// in java/javax/servlet/jsp/tagext/BodyContent.java
public void clearBody() { try { this.clear(); } catch (IOException ex) { // TODO -- clean this one up. throw new Error("internal error!;"); } }
4
            
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
// in java/org/apache/el/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) { throw new java.lang.Error(e); } else { log.error("Catalina.start", e); } }
// in java/javax/servlet/jsp/tagext/BodyContent.java
catch (IOException ex) { // TODO -- clean this one up. throw new Error("internal error!;"); }
0 6
            
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Error e) { e.printStackTrace(); if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(" endpoint.poll.limitedpollsize " + size); return 0; } else if (Status.APR_STATUS_IS_ENOTIMPL(e.getError())) { // thread safe not supported log.severe("THREAD SAFE NOT SUPPORTED" + e); threadSafe = false; // try again without the flags continue; } else { log.severe("endpoint.poll.initfail" + e); return 0; } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Error e) { if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(sm.getString("endpoint.poll.limitedpollsize", "" + size)); return 0; } else { log.error(sm.getString("endpoint.poll.initfail"), e); return -1; } }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Finish event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Body event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("End event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Begin event threw error", e); throw e; }
4
            
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Finish event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Body event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("End event threw error", e); throw e; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Error e) { log.error("Begin event threw error", e); throw e; }
0
checked (Lib) Exception 13
            
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.UseBean n) throws JasperException { String name = n.getTextAttribute("id"); String scope = n.getTextAttribute("scope"); String klass = n.getTextAttribute("class"); String type = n.getTextAttribute("type"); Node.JspAttribute beanName = n.getBeanName(); // If "class" is specified, try an instantiation at compile time boolean generateNew = false; String canonicalName = null; // Canonical name for klass if (klass != null) { try { Class<?> bean = ctxt.getClassLoader().loadClass(klass); if (klass.indexOf('$') >= 0) { // Obtain the canonical type name canonicalName = bean.getCanonicalName(); } else { canonicalName = klass; } int modifiers = bean.getModifiers(); if (!Modifier.isPublic(modifiers) || Modifier.isInterface(modifiers) || Modifier.isAbstract(modifiers)) { throw new Exception("Invalid bean class modifier"); } // Check that there is a 0 arg constructor bean.getConstructor(new Class[] {}); // At compile time, we have determined that the bean class // exists, with a public zero constructor, new() can be // used for bean instantiation. generateNew = true; } catch (Exception e) { // Cannot instantiate the specified class, either a // compilation error or a runtime error will be raised, // depending on a compiler flag. if (ctxt.getOptions() .getErrorOnUseBeanInvalidClassAttribute()) { err.jspError(n, "jsp.error.invalid.bean", klass); } if (canonicalName == null) { // Doing our best here to get a canonical name // from the binary name, should work 99.99% of time. canonicalName = klass.replace('$', '.'); } } if (type == null) { // if type is unspecified, use "class" as type of bean type = canonicalName; } } // JSP.5.1, Sematics, para 1 - lock not required for request or // page scope String scopename = "javax.servlet.jsp.PageContext.PAGE_SCOPE"; // Default to page String lock = null; if ("request".equals(scope)) { scopename = "javax.servlet.jsp.PageContext.REQUEST_SCOPE"; } else if ("session".equals(scope)) { scopename = "javax.servlet.jsp.PageContext.SESSION_SCOPE"; lock = "session"; } else if ("application".equals(scope)) { scopename = "javax.servlet.jsp.PageContext.APPLICATION_SCOPE"; lock = "application"; } n.setBeginJavaLine(out.getJavaLine()); // Declare bean out.printin(type); out.print(' '); out.print(name); out.println(" = null;"); // Lock (if required) while getting or creating bean if (lock != null) { out.printin("synchronized ("); out.print(lock); out.println(") {"); out.pushIndent(); } // Locate bean from context out.printin(name); out.print(" = ("); out.print(type); out.print(") _jspx_page_context.getAttribute("); out.print(quote(name)); out.print(", "); out.print(scopename); out.println(");"); // Create bean /* * Check if bean is already there */ out.printin("if ("); out.print(name); out.println(" == null){"); out.pushIndent(); if (klass == null && beanName == null) { /* * If both class name and beanName is not specified, the bean * must be found locally, otherwise it's an error */ out.printin("throw new java.lang.InstantiationException(\"bean "); out.print(name); out.println(" not found within scope\");"); } else { /* * Instantiate the bean if it is not in the specified scope. */ if (!generateNew) { String binaryName; if (beanName != null) { if (beanName.isNamedAttribute()) { // If the value for beanName was specified via // jsp:attribute, first generate code to evaluate // that body. binaryName = generateNamedAttributeValue(beanName .getNamedAttributeNode()); } else { binaryName = attributeValue(beanName, false, String.class); } } else { // Implies klass is not null binaryName = quote(klass); } out.printil("try {"); out.pushIndent(); out.printin(name); out.print(" = ("); out.print(type); out.print(") java.beans.Beans.instantiate("); out.print("this.getClass().getClassLoader(), "); out.print(binaryName); out.println(");"); out.popIndent(); /* * Note: Beans.instantiate throws ClassNotFoundException if * the bean class is abstract. */ out.printil("} catch (java.lang.ClassNotFoundException exc) {"); out.pushIndent(); out.printil("throw new InstantiationException(exc.getMessage());"); out.popIndent(); out.printil("} catch (java.lang.Exception exc) {"); out.pushIndent(); out.printin("throw new javax.servlet.ServletException("); out.print("\"Cannot create bean of class \" + "); out.print(binaryName); out.println(", exc);"); out.popIndent(); out.printil("}"); // close of try } else { // Implies klass is not null // Generate codes to instantiate the bean class out.printin(name); out.print(" = new "); out.print(canonicalName); out.println("();"); } /* * Set attribute for bean in the specified scope */ out.printin("_jspx_page_context.setAttribute("); out.print(quote(name)); out.print(", "); out.print(name); out.print(", "); out.print(scopename); out.println(");"); // Only visit the body when bean is instantiated visitBody(n); } out.popIndent(); out.printil("}"); // End of lock block if (lock != null) { out.popIndent(); out.printil("}"); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
Override public void bind() throws Exception { // Create the root APR memory pool try { rootPool = Pool.create(0); } catch (UnsatisfiedLinkError e) { throw new Exception(sm.getString("endpoint.init.notavail")); } // Create the pool for the server socket serverSockPool = Pool.create(rootPool); // Create the APR address that will be bound String addressStr = null; if (getAddress() != null) { addressStr = getAddress().getHostAddress(); } int family = Socket.APR_INET; if (Library.APR_HAVE_IPV6) { if (addressStr == null) { if (!OS.IS_BSD && !OS.IS_WIN32 && !OS.IS_WIN64) family = Socket.APR_UNSPEC; } else if (addressStr.indexOf(':') >= 0) { family = Socket.APR_UNSPEC; } } long inetAddress = Address.info(addressStr, family, getPort(), 0, rootPool); // Create the APR server socket serverSock = Socket.create(Address.getInfo(inetAddress).family, Socket.SOCK_STREAM, Socket.APR_PROTO_TCP, rootPool); if (OS.IS_UNIX) { Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Deal with the firewalls that tend to drop the inactive sockets Socket.optSet(serverSock, Socket.APR_SO_KEEPALIVE, 1); // Bind the server socket int ret = Socket.bind(serverSock, inetAddress); if (ret != 0) { throw new Exception(sm.getString("endpoint.init.bind", "" + ret, Error.strerror(ret))); } // Start listening on the server socket ret = Socket.listen(serverSock, getBacklog()); if (ret != 0) { throw new Exception(sm.getString("endpoint.init.listen", "" + ret, Error.strerror(ret))); } if (OS.IS_WIN32 || OS.IS_WIN64) { // On Windows set the reuseaddr flag after the bind/listen Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Sendfile usage on systems which don't support it cause major problems if (useSendfile && !Library.APR_HAS_SENDFILE) { useSendfile = false; } // Initialize thread count defaults for acceptor, poller and sendfile if (acceptorThreadCount == 0) { // FIXME: Doesn't seem to work that well with multiple accept threads acceptorThreadCount = 1; } if (pollerThreadCount == 0) { if ((OS.IS_WIN32 || OS.IS_WIN64) && (getMaxConnections() > 1024)) { // The maximum per poller to get reasonable performance is 1024 pollerThreadCount = getMaxConnections() / 1024; // Adjust poller size so that it won't reach the limit setMaxConnections( getMaxConnections() - (getMaxConnections() % 1024)); } else { // No explicit poller size limitation pollerThreadCount = 1; } } if (sendfileThreadCount == 0) { if ((OS.IS_WIN32 || OS.IS_WIN64) && (sendfileSize > 1024)) { // The maximum per poller to get reasonable performance is 1024 sendfileThreadCount = sendfileSize / 1024; // Adjust poller size so that it won't reach the limit sendfileSize = sendfileSize - (sendfileSize % 1024); } else { // No explicit poller size limitation // FIXME: Default to one per CPU ? sendfileThreadCount = 1; } } // Delay accepting of new connections until data is available // Only Linux kernels 2.4 + have that implemented // on other platforms this call is noop and will return APR_ENOTIMPL. if (deferAccept) { if (Socket.optSet(serverSock, Socket.APR_TCP_DEFER_ACCEPT, 1) == Status.APR_ENOTIMPL) { deferAccept = false; } } // Initialize SSL if needed if (isSSLEnabled()) { if (SSLCertificateFile == null) { // This is required throw new Exception(sm.getString("endpoint.apr.noSslCertFile")); } // SSL protocol int value; // This branch can be removed, once the required version is at least 1.1.21. int tcnFullVersion = Library.TCN_MAJOR_VERSION * 1000 + Library.TCN_MINOR_VERSION * 100 + Library.TCN_PATCH_VERSION; if (tcnFullVersion <= 1120) { value = SSL.SSL_PROTOCOL_ALL; if ("SSLv2".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_SSLV2; } else if ("SSLv3".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_SSLV3; } else if ("TLSv1".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_TLSV1; } else if ("SSLv2+SSLv3".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_SSLV2 | SSL.SSL_PROTOCOL_SSLV3; } else if ("all".equalsIgnoreCase(SSLProtocol) || SSLProtocol == null || SSLProtocol.length() == 0) { // NOOP, use the default defined above } else { // Protocol not recognized, fail to start as it is safer than // continuing with the default which might enable more than the // is required throw new Exception(sm.getString( "endpoint.apr.invalidSslProtocol", SSLProtocol)); } } else { value = SSL.SSL_PROTOCOL_NONE; if (SSLProtocol == null || SSLProtocol.length() == 0) { value = SSL.SSL_PROTOCOL_ALL; } else { for (String protocol : SSLProtocol.split("\\+")) { protocol = protocol.trim(); if ("SSLv2".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_SSLV2; } else if ("SSLv3".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_SSLV3; } else if ("TLSv1".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_TLSV1; } else if ("all".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_ALL; } else { // Protocol not recognized, fail to start as it is safer than // continuing with the default which might enable more than the // is required throw new Exception(sm.getString( "endpoint.apr.invalidSslProtocol", SSLProtocol)); } } } } // Create SSL Context sslContext = SSLContext.make(rootPool, value, SSL.SSL_MODE_SERVER); if (SSLInsecureRenegotiation) { boolean legacyRenegSupported = false; try { legacyRenegSupported = SSL.hasOp(SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); if (legacyRenegSupported) SSLContext.setOptions(sslContext, SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); } catch (UnsatisfiedLinkError e) { // Ignore } if (!legacyRenegSupported) { // OpenSSL does not support unsafe legacy renegotiation. log.warn(sm.getString("endpoint.warn.noInsecureReneg", SSL.versionString())); } } // List the ciphers that the client is permitted to negotiate SSLContext.setCipherSuite(sslContext, SSLCipherSuite); // Load Server key and certificate SSLContext.setCertificate(sslContext, SSLCertificateFile, SSLCertificateKeyFile, SSLPassword, SSL.SSL_AIDX_RSA); // Set certificate chain file SSLContext.setCertificateChainFile(sslContext, SSLCertificateChainFile, false); // Support Client Certificates SSLContext.setCACertificate(sslContext, SSLCACertificateFile, SSLCACertificatePath); // Set revocation SSLContext.setCARevocation(sslContext, SSLCARevocationFile, SSLCARevocationPath); // Client certificate verification value = SSL.SSL_CVERIFY_NONE; if ("optional".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_OPTIONAL; } else if ("require".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_REQUIRE; } else if ("optionalNoCA".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_OPTIONAL_NO_CA; } SSLContext.setVerify(sslContext, value, SSLVerifyDepth); // For now, sendfile is not supported with SSL useSendfile = false; } }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsSerSource.java
public void execute() throws Exception { if( registry==null ) registry=Registry.getRegistry(null, null); long t1=System.currentTimeMillis(); try { InputStream stream=null; if( source instanceof URL ) { stream=((URL)source).openStream(); } if( source instanceof InputStream ) { stream=(InputStream)source; } if( stream==null ) { throw new Exception( "Can't process "+ source); } ObjectInputStream ois=new ObjectInputStream(stream); Thread.currentThread().setContextClassLoader(ManagedBean.class.getClassLoader()); Object obj=ois.readObject(); //log.info("Reading " + obj); ManagedBean beans[]=(ManagedBean[])obj; // after all are read without error for( int i=0; i<beans.length; i++ ) { registry.addManagedBean(beans[i]); } } catch( Exception ex ) { log.error( "Error reading descriptors " + source + " " + ex.toString(), ex); throw ex; } long t2=System.currentTimeMillis(); log.info( "Reading descriptors ( ser ) " + (t2-t1)); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
private Service getService(ObjectName oname) throws Exception { if (container instanceof Service) { // Don't bother checking the domain - this is the only option return (Service) container; } StandardService service = null; String domain = oname.getDomain(); if (container instanceof Server) { Service[] services = ((Server)container).findServices(); for (int i = 0; i < services.length; i++) { service = (StandardService) services[i]; if (domain.equals(service.getObjectName().getDomain())) { break; } } } if (service == null || !service.getObjectName().getDomain().equals(domain)) { throw new Exception("Service with the domain is not found"); } return service; }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createStandardServiceEngine(String domain, String defaultHost, String baseDir) throws Exception{ if (!(container instanceof Server)) { throw new Exception("Container not Server"); } StandardEngine engine = new StandardEngine(); engine.setDomain(domain); engine.setName(domain); engine.setDefaultHost(defaultHost); Service service = new StandardService(); service.setContainer(engine); service.setName(domain); ((Server) container).addService(service); return engine.getObjectName().toString(); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeService(String name) throws Exception { if (!(container instanceof Server)) { throw new Exception(); } // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(name); Service service = getService(oname); ((Server) container).removeService(service); }
// in java/org/apache/catalina/ha/backend/TcpSender.java
Override public void init(HeartbeatListener config) throws Exception { this.config = config; StringTokenizer tok = new StringTokenizer(config.getProxyList(), ","); proxies = new Proxy[tok.countTokens()]; int i = 0; while (tok.hasMoreTokens()) { String token = tok.nextToken().trim(); int pos = token.indexOf(':'); if (pos <=0) throw new Exception("bad ProxyList"); proxies[i] = new Proxy(); proxies[i].port = Integer.parseInt(token.substring(pos + 1)); try { proxies[i].address = InetAddress.getByName(token.substring(0, pos)); } catch (Exception e) { throw new Exception("bad ProxyList"); } i++; } connections = new Socket[proxies.length]; connectionReaders = new BufferedReader[proxies.length]; connectionWriters = new BufferedWriter[proxies.length]; }
2
            
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (UnsatisfiedLinkError e) { throw new Exception(sm.getString("endpoint.init.notavail")); }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (Exception e) { throw new Exception("bad ProxyList"); }
297
            
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
public void mapFunction(String fnQName, final Class<?> c, final String methodName, final Class<?>[] args) { java.lang.reflect.Method method; if (SecurityUtil.isPackageProtectionEnabled()) { try { method = AccessController.doPrivileged( new PrivilegedExceptionAction<Method>() { @Override public Method run() throws Exception { return c.getDeclaredMethod(methodName, args); } }); } catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); } }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
Override public Method run() throws Exception { return c.getDeclaredMethod(methodName, args); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
public static ProtectedFunctionMapper getMapForFunction(String fnQName, final Class<?> c, final String methodName, final Class<?>[] args) { java.lang.reflect.Method method; ProtectedFunctionMapper funcMapper; if (SecurityUtil.isPackageProtectionEnabled()) { funcMapper = AccessController.doPrivileged( new PrivilegedAction<ProtectedFunctionMapper>() { @Override public ProtectedFunctionMapper run() { return new ProtectedFunctionMapper(); } }); try { method = AccessController.doPrivileged( new PrivilegedExceptionAction<Method>() { @Override public Method run() throws Exception { return c.getDeclaredMethod(methodName, args); } }); } catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); } }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
Override public Method run() throws Exception { return c.getDeclaredMethod(methodName, args); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void include(final String relativeUrlPath, final boolean flush) throws ServletException, IOException { if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doInclude(relativeUrlPath, flush); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public Void run() throws Exception { doInclude(relativeUrlPath, flush); return null; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void forward(final String relativeUrlPath) throws ServletException, IOException { if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doForward(relativeUrlPath); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public Void run() throws Exception { doForward(relativeUrlPath); return null; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void handlePageException(final Throwable t) throws IOException, ServletException { if (t == null) throw new NullPointerException("null Throwable"); if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doHandlePageException(t); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public Void run() throws Exception { doHandlePageException(t); return null; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
public static Object proprietaryEvaluate(final String expression, final Class<?> expectedType, final PageContext pageContext, final ProtectedFunctionMapper functionMap, final boolean escape) throws ELException { Object retValue; final ExpressionFactory exprFactory = jspf.getJspApplicationContext(pageContext.getServletContext()).getExpressionFactory(); if (SecurityUtil.isPackageProtectionEnabled()) { try { retValue = AccessController .doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { ELContextImpl ctx = (ELContextImpl) pageContext.getELContext(); ctx.setFunctionMapper(new FunctionMapperImpl(functionMap)); ValueExpression ve = exprFactory.createValueExpression(ctx, expression, expectedType); return ve.getValue(ctx); } }); } catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public Object run() throws Exception { ELContextImpl ctx = (ELContextImpl) pageContext.getELContext(); ctx.setFunctionMapper(new FunctionMapperImpl(functionMap)); ValueExpression ve = exprFactory.createValueExpression(ctx, expression, expectedType); return ve.getValue(ctx); }
// in java/org/apache/jasper/compiler/Compiler.java
protected String[] generateJava() throws Exception { String[] smapStr = null; long t1, t2, t3, t4; t1 = t2 = t3 = t4 = 0; if (log.isDebugEnabled()) { t1 = System.currentTimeMillis(); } // Setup page info area pageInfo = new PageInfo(new BeanRepository(ctxt.getClassLoader(), errDispatcher), ctxt.getJspFile()); JspConfig jspConfig = options.getJspConfig(); JspConfig.JspProperty jspProperty = jspConfig.findJspProperty(ctxt .getJspFile()); /* * If the current uri is matched by a pattern specified in a * jsp-property-group in web.xml, initialize pageInfo with those * properties. */ if (jspProperty.isELIgnored() != null) { pageInfo.setELIgnored(JspUtil.booleanValue(jspProperty .isELIgnored())); } if (jspProperty.isScriptingInvalid() != null) { pageInfo.setScriptingInvalid(JspUtil.booleanValue(jspProperty .isScriptingInvalid())); } if (jspProperty.getIncludePrelude() != null) { pageInfo.setIncludePrelude(jspProperty.getIncludePrelude()); } if (jspProperty.getIncludeCoda() != null) { pageInfo.setIncludeCoda(jspProperty.getIncludeCoda()); } if (jspProperty.isDeferedSyntaxAllowedAsLiteral() != null) { pageInfo.setDeferredSyntaxAllowedAsLiteral(JspUtil.booleanValue(jspProperty .isDeferedSyntaxAllowedAsLiteral())); } if (jspProperty.isTrimDirectiveWhitespaces() != null) { pageInfo.setTrimDirectiveWhitespaces(JspUtil.booleanValue(jspProperty .isTrimDirectiveWhitespaces())); } // Default ContentType processing is deferred until after the page has // been parsed if (jspProperty.getBuffer() != null) { pageInfo.setBufferValue(jspProperty.getBuffer(), null, errDispatcher); } if (jspProperty.isErrorOnUndeclaredNamespace() != null) { pageInfo.setErrorOnUndeclaredNamespace( JspUtil.booleanValue( jspProperty.isErrorOnUndeclaredNamespace())); } if (ctxt.isTagFile()) { try { double libraryVersion = Double.parseDouble(ctxt.getTagInfo() .getTagLibrary().getRequiredVersion()); if (libraryVersion < 2.0) { pageInfo.setIsELIgnored("true", null, errDispatcher, true); } if (libraryVersion < 2.1) { pageInfo.setDeferredSyntaxAllowedAsLiteral("true", null, errDispatcher, true); } } catch (NumberFormatException ex) { errDispatcher.jspError(ex); } } ctxt.checkOutputDir(); String javaFileName = ctxt.getServletJavaFileName(); ServletWriter writer = null; try { /* * The setting of isELIgnored changes the behaviour of the parser * in subtle ways. To add to the 'fun', isELIgnored can be set in * any file that forms part of the translation unit so setting it * in a file included towards the end of the translation unit can * change how the parser should have behaved when parsing content * up to the point where isELIgnored was set. Arghh! * Previous attempts to hack around this have only provided partial * solutions. We now use two passes to parse the translation unit. * The first just parses the directives and the second parses the * whole translation unit once we know how isELIgnored has been set. * TODO There are some possible optimisations of this process. */ // Parse the file ParserController parserCtl = new ParserController(ctxt, this); // Pass 1 - the directives Node.Nodes directives = parserCtl.parseDirectives(ctxt.getJspFile()); Validator.validateDirectives(this, directives); // Pass 2 - the whole translation unit pageNodes = parserCtl.parse(ctxt.getJspFile()); // Leave this until now since it can only be set once - bug 49726 if (pageInfo.getContentType() == null && jspProperty.getDefaultContentType() != null) { pageInfo.setContentType(jspProperty.getDefaultContentType()); } if (ctxt.isPrototypeMode()) { // generate prototype .java file for the tag file writer = setupContextWriter(javaFileName); Generator.generate(writer, this, pageNodes); writer.close(); writer = null; return null; } // Validate and process attributes - don't re-validate the // directives we validated in pass 1 Validator.validateExDirectives(this, pageNodes); if (log.isDebugEnabled()) { t2 = System.currentTimeMillis(); } // Collect page info Collector.collect(this, pageNodes); // Compile (if necessary) and load the tag files referenced in // this compilation unit. tfp = new TagFileProcessor(); tfp.loadTagFiles(this, pageNodes); if (log.isDebugEnabled()) { t3 = System.currentTimeMillis(); } // Determine which custom tag needs to declare which scripting vars ScriptingVariabler.set(pageNodes, errDispatcher); // Optimizations by Tag Plugins TagPluginManager tagPluginManager = options.getTagPluginManager(); tagPluginManager.apply(pageNodes, errDispatcher, pageInfo); // Optimization: concatenate contiguous template texts. TextOptimizer.concatenate(this, pageNodes); // Generate static function mapper codes. ELFunctionMapper.map(pageNodes); // generate servlet .java file writer = setupContextWriter(javaFileName); Generator.generate(writer, this, pageNodes); writer.close(); writer = null; // The writer is only used during the compile, dereference // it in the JspCompilationContext when done to allow it // to be GC'd and save memory. ctxt.setWriter(null); if (log.isDebugEnabled()) { t4 = System.currentTimeMillis(); log.debug("Generated " + javaFileName + " total=" + (t4 - t1) + " generate=" + (t4 - t3) + " validate=" + (t2 - t1)); } } catch (Exception e) { if (writer != null) { try { writer.close(); writer = null; } catch (Exception e1) { // do nothing } } // Remove the generated .java file File file = new File(javaFileName); if (file.exists()) { if (!file.delete()) { log.warn(Localizer.getMessage( "jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath())); } } throw e; } finally { if (writer != null) { try { writer.close(); } catch (Exception e2) { // do nothing } } } // JSR45 Support if (!options.isSmapSuppressed()) { smapStr = SmapUtil.generateSmap(ctxt, pageNodes); } // If any proto type .java and .class files was generated, // the prototype .java may have been replaced by the current // compilation (if the tag file is self referencing), but the // .class file need to be removed, to make sure that javac would // generate .class again from the new .java file just generated. tfp.removeProtoTypeFiles(ctxt.getClassFileName()); return smapStr; }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile() throws FileNotFoundException, JasperException, Exception { compile(true); }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile(boolean compileClass) throws FileNotFoundException, JasperException, Exception { compile(compileClass, false); }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile(boolean compileClass, boolean jspcMode) throws FileNotFoundException, JasperException, Exception { if (errDispatcher == null) { this.errDispatcher = new ErrorDispatcher(jspcMode); } try { String[] smap = generateJava(); File javaFile = new File(ctxt.getServletJavaFileName()); Long jspLastModified = ctxt.getLastModified(ctxt.getJspFile()); javaFile.setLastModified(jspLastModified.longValue()); if (compileClass) { generateClass(smap); // Fix for bugzilla 41606 // Set JspServletWrapper.servletClassLastModifiedTime after successful compile String targetFileName = ctxt.getClassFileName(); if (targetFileName != null) { File targetFile = new File(targetFileName); if (targetFile.exists()) { targetFile.setLastModified(jspLastModified.longValue()); if (jsw != null) { jsw.setServletClassLastModifiedTime( jspLastModified.longValue()); } } } } } finally { if (tfp != null && ctxt.isPrototypeMode()) { tfp.removeProtoTypeFiles(null); } // Make sure these object which are only used during the // generation and compilation of the JSP page get // dereferenced so that they can be GC'd and reduce the // memory footprint. tfp = null; errDispatcher = null; pageInfo = null; // Only get rid of the pageNodes if in production. // In development mode, they are used for detailed // error messages. // http://issues.apache.org/bugzilla/show_bug.cgi?id=37062 if (!this.options.getDevelopment()) { pageNodes = null; } if (ctxt.getWriter() != null) { ctxt.getWriter().close(); ctxt.setWriter(null); } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private void tldScanWebXml() throws Exception { WebXml webXml = null; try { webXml = new WebXml(ctxt); if (webXml.getInputSource() == null) { return; } // Parse the web application deployment descriptor TreeNode webtld = null; webtld = new ParserUtils().parseXMLDocument(webXml.getSystemId(), webXml.getInputSource()); // Allow taglib to be an element of the root or jsp-config (JSP2.0) TreeNode jspConfig = webtld.findChild("jsp-config"); if (jspConfig != null) { webtld = jspConfig; } Iterator<TreeNode> taglibs = webtld.findChildren("taglib"); while (taglibs.hasNext()) { // Parse the next <taglib> element TreeNode taglib = taglibs.next(); String tagUri = null; String tagLoc = null; TreeNode child = taglib.findChild("taglib-uri"); if (child != null) tagUri = child.getBody(); child = taglib.findChild("taglib-location"); if (child != null) tagLoc = child.getBody(); // Save this location if appropriate if (tagLoc == null) continue; if (uriType(tagLoc) == NOROOT_REL_URI) tagLoc = "/WEB-INF/" + tagLoc; TldLocation location; if (tagLoc.endsWith(JAR_EXT)) { location = new TldLocation("META-INF/taglib.tld", ctxt.getResource(tagLoc).toString()); } else { location = new TldLocation(tagLoc); } mappings.put(tagUri, location); } } finally { if (webXml != null) { webXml.close(); } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private void tldScanResourcePaths(String startPath) throws Exception { Set<String> dirList = ctxt.getResourcePaths(startPath); if (dirList != null) { Iterator<String> it = dirList.iterator(); while (it.hasNext()) { String path = it.next(); if (!path.endsWith(TLD_EXT) && (path.startsWith(WEB_INF_LIB) || path.startsWith("/WEB-INF/classes/"))) { continue; } if (path.endsWith(TLD_EXT)) { if (path.startsWith("/WEB-INF/tags/") && !path.endsWith("implicit.tld")) { continue; } InputStream stream = ctxt.getResourceAsStream(path); try { tldScanStream(path, null, stream); } finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } } else { tldScanResourcePaths(path); } } } }
// in java/org/apache/jasper/compiler/JDTCompiler.java
Override protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception { long t1 = 0; if (log.isDebugEnabled()) { t1 = System.currentTimeMillis(); } final String sourceFile = ctxt.getServletJavaFileName(); final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath(); String packageName = ctxt.getServletPackageName(); final String targetClassName = ((packageName.length() != 0) ? (packageName + ".") : "") + ctxt.getServletClassName(); final ClassLoader classLoader = ctxt.getJspLoader(); String[] fileNames = new String[] {sourceFile}; String[] classNames = new String[] {targetClassName}; final ArrayList<JavacErrorDetail> problemList = new ArrayList<JavacErrorDetail>(); class CompilationUnit implements ICompilationUnit { private final String className; private final String sourceFile; CompilationUnit(String sourceFile, String className) { this.className = className; this.sourceFile = sourceFile; } @Override public char[] getFileName() { return sourceFile.toCharArray(); } @Override public char[] getContents() { char[] result = null; FileInputStream is = null; InputStreamReader isr = null; Reader reader = null; try { is = new FileInputStream(sourceFile); isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding()); reader = new BufferedReader(isr); char[] chars = new char[8192]; StringBuilder buf = new StringBuilder(); int count; while ((count = reader.read(chars, 0, chars.length)) > 0) { buf.append(chars, 0, count); } result = new char[buf.length()]; buf.getChars(0, result.length, result, 0); } catch (IOException e) { log.error("Compilation error", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) {/*Ignore*/} } if (isr != null) { try { isr.close(); } catch (IOException ioe) {/*Ignore*/} } if (is != null) { try { is.close(); } catch (IOException exc) {/*Ignore*/} } } return result; } @Override public char[] getMainTypeName() { int dot = className.lastIndexOf('.'); if (dot > 0) { return className.substring(dot + 1).toCharArray(); } return className.toCharArray(); } @Override public char[][] getPackageName() { StringTokenizer izer = new StringTokenizer(className, "."); char[][] result = new char[izer.countTokens()-1][]; for (int i = 0; i < result.length; i++) { String tok = izer.nextToken(); result[i] = tok.toCharArray(); } return result; } @SuppressWarnings("unused") // New method added to interface in // later JDT versions public boolean ignoreOptionalProblems() { return false; } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private static SAXParser getSAXParser( boolean validating, JspDocumentParser jspDocParser) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); // Preserve xmlns attributes factory.setFeature( "http://xml.org/sax/features/namespace-prefixes", true); factory.setValidating(validating); //factory.setFeature( // "http://xml.org/sax/features/validation", // validating); // Configure the parser SAXParser saxParser = factory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setProperty(LEXICAL_HANDLER_PROPERTY, jspDocParser); xmlReader.setErrorHandler(jspDocParser); return saxParser; }
// in java/org/apache/jasper/compiler/AntCompiler.java
Override protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception { long t1 = 0; if (log.isDebugEnabled()) { t1 = System.currentTimeMillis(); } String javaEncoding = ctxt.getOptions().getJavaEncoding(); String javaFileName = ctxt.getServletJavaFileName(); String classpath = ctxt.getClassPath(); String sep = System.getProperty("path.separator"); StringBuilder errorReport = new StringBuilder(); StringBuilder info=new StringBuilder(); info.append("Compile: javaFileName=" + javaFileName + "\n" ); info.append(" classpath=" + classpath + "\n" ); // Start capturing the System.err output for this thread SystemLogHandler.setThread(); // Initializing javac task getProject(); Javac javac = (Javac) project.createTask("javac"); // Initializing classpath Path path = new Path(project); path.setPath(System.getProperty("java.class.path")); info.append(" cp=" + System.getProperty("java.class.path") + "\n"); StringTokenizer tokenizer = new StringTokenizer(classpath, sep); while (tokenizer.hasMoreElements()) { String pathElement = tokenizer.nextToken(); File repository = new File(pathElement); path.setLocation(repository); info.append(" cp=" + repository + "\n"); } if( log.isDebugEnabled() ) log.debug( "Using classpath: " + System.getProperty("java.class.path") + sep + classpath); // Initializing sourcepath Path srcPath = new Path(project); srcPath.setLocation(options.getScratchDir()); info.append(" work dir=" + options.getScratchDir() + "\n"); // Initialize and set java extensions String exts = System.getProperty("java.ext.dirs"); if (exts != null) { Path extdirs = new Path(project); extdirs.setPath(exts); javac.setExtdirs(extdirs); info.append(" extension dir=" + exts + "\n"); } // Add endorsed directories if any are specified and we're forking // See Bugzilla 31257 if(ctxt.getOptions().getFork()) { String endorsed = System.getProperty("java.endorsed.dirs"); if(endorsed != null) { Javac.ImplementationSpecificArgument endorsedArg = javac.createCompilerArg(); endorsedArg.setLine("-J-Djava.endorsed.dirs=" + quotePathList(endorsed)); info.append(" endorsed dir=" + quotePathList(endorsed) + "\n"); } else { info.append(" no endorsed dirs specified\n"); } } // Configure the compiler object javac.setEncoding(javaEncoding); javac.setClasspath(path); javac.setDebug(ctxt.getOptions().getClassDebugInfo()); javac.setSrcdir(srcPath); javac.setTempdir(options.getScratchDir()); javac.setOptimize(! ctxt.getOptions().getClassDebugInfo() ); javac.setFork(ctxt.getOptions().getFork()); info.append(" srcDir=" + srcPath + "\n" ); // Set the Java compiler to use if (options.getCompiler() != null) { javac.setCompiler(options.getCompiler()); info.append(" compiler=" + options.getCompiler() + "\n"); } if (options.getCompilerTargetVM() != null) { javac.setTarget(options.getCompilerTargetVM()); info.append(" compilerTargetVM=" + options.getCompilerTargetVM() + "\n"); } if (options.getCompilerSourceVM() != null) { javac.setSource(options.getCompilerSourceVM()); info.append(" compilerSourceVM=" + options.getCompilerSourceVM() + "\n"); } // Build includes path PatternSet.NameEntry includes = javac.createInclude(); includes.setName(ctxt.getJavaPath()); info.append(" include="+ ctxt.getJavaPath() + "\n" ); BuildException be = null; try { if (ctxt.getOptions().getFork()) { javac.execute(); } else { synchronized(javacLock) { javac.execute(); } } } catch (BuildException e) { be = e; log.error(Localizer.getMessage("jsp.error.javac"), e); log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString()); } errorReport.append(logger.getReport()); // Stop capturing the System.err output for this thread String errorCapture = SystemLogHandler.unsetThread(); if (errorCapture != null) { errorReport.append(Constants.NEWLINE); errorReport.append(errorCapture); } if (!ctxt.keepGenerated()) { File javaFile = new File(javaFileName); javaFile.delete(); } if (be != null) { String errorReportString = errorReport.toString(); log.error(Localizer.getMessage("jsp.error.compilation", javaFileName, errorReportString)); JavacErrorDetail[] javacErrors = ErrorDispatcher.parseJavacErrors( errorReportString, javaFileName, pageNodes); if (javacErrors != null) { errDispatcher.javacError(javacErrors); } else { errDispatcher.javacError(errorReportString, be); } } if( log.isDebugEnabled() ) { long t2 = System.currentTimeMillis(); log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2-t1) + "ms"); } logger = null; project = null; if (ctxt.isPrototypeMode()) { return; } // JSR45 Support if (! options.isSmapSuppressed()) { SmapUtil.installSmap(smap); } }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof ResourceEnvRef) { Reference ref = (Reference) obj; ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } } // Note: No defaults here if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/factory/OpenEjbFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { Object beanObj = null; if (obj instanceof EjbRef) { Reference ref = (Reference) obj; String factory = DEFAULT_OPENEJB_FACTORY; RefAddr factoryRefAddr = ref.get("openejb.factory"); if (factoryRefAddr != null) { // Retrieving the OpenEJB factory factory = factoryRefAddr.getContent().toString(); } Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, factory); RefAddr linkRefAddr = ref.get("openejb.link"); if (linkRefAddr != null) { String ejbLink = linkRefAddr.getContent().toString(); beanObj = (new InitialContext(env)).lookup(ejbLink); } } return beanObj; }
// in java/org/apache/naming/factory/SendMailFactory.java
Override public Object getObjectInstance(Object refObj, Name name, Context ctx, Hashtable<?,?> env) throws Exception { final Reference ref = (Reference)refObj; // Creation of the DataSource is wrapped inside a doPrivileged // so that javamail can read its default properties without // throwing Security Exceptions if (ref.getClassName().equals(DataSourceClassName)) { return AccessController.doPrivileged( new PrivilegedAction<MimePartDataSource>() { @Override public MimePartDataSource run() { // set up the smtp session that will send the message Properties props = new Properties(); // enumeration of all refaddr Enumeration<RefAddr> list = ref.getAll(); // current refaddr to be set RefAddr refaddr; // set transport to smtp props.put("mail.transport.protocol", "smtp"); while (list.hasMoreElements()) { refaddr = list.nextElement(); // set property props.put(refaddr.getType(), refaddr.getContent()); } MimeMessage message = new MimeMessage( Session.getInstance(props)); try { RefAddr fromAddr = ref.get("mail.from"); String from = null; if (fromAddr != null) { from = (String)ref.get("mail.from").getContent(); } if (from != null) { message.setFrom(new InternetAddress(from)); } message.setSubject(""); } catch (Exception e) {/*Ignore*/} MimePartDataSource mds = new MimePartDataSource(message); return mds; } } ); }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof ServiceRef) { Reference ref = (Reference) obj; // ClassLoader ClassLoader tcl = Thread.currentThread().getContextClassLoader(); if (tcl == null) tcl = this.getClass().getClassLoader(); ServiceFactory factory = ServiceFactory.newInstance(); javax.xml.rpc.Service service = null; // Service Interface RefAddr tmp = ref.get(ServiceRef.SERVICE_INTERFACE); String serviceInterface = null; if (tmp != null) serviceInterface = (String) tmp.getContent(); // WSDL tmp = ref.get(ServiceRef.WSDL); String wsdlRefAddr = null; if (tmp != null) wsdlRefAddr = (String) tmp.getContent(); // PortComponent Hashtable<String,QName> portComponentRef = new Hashtable<String,QName>(); // Create QName object QName serviceQname = null; tmp = ref.get(ServiceRef.SERVICE_LOCAL_PART); if (tmp != null) { String serviceLocalPart = (String) tmp.getContent(); tmp = ref.get(ServiceRef.SERVICE_NAMESPACE); if (tmp == null) { serviceQname = new QName(serviceLocalPart); } else { String serviceNamespace = (String) tmp.getContent(); serviceQname = new QName(serviceNamespace, serviceLocalPart); } } Class<?> serviceInterfaceClass = null; // Create service object if (serviceInterface == null) { if (serviceQname == null) { throw new NamingException ("Could not create service-ref instance"); } try { if (wsdlRefAddr == null) { service = factory.createService( serviceQname ); } else { service = factory.createService( new URL(wsdlRefAddr), serviceQname ); } } catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; } } else { // Loading service Interface try { serviceInterfaceClass = tcl.loadClass(serviceInterface); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load service Interface"); ex.initCause(e); throw ex; } if (serviceInterfaceClass == null) { throw new NamingException ("Could not load service Interface"); } try { if (wsdlRefAddr == null) { if (!Service.class.isAssignableFrom(serviceInterfaceClass)) { throw new NamingException ("service Interface should extend javax.xml.rpc.Service"); } service = factory.loadService( serviceInterfaceClass ); } else { service = factory.loadService( new URL(wsdlRefAddr), serviceInterfaceClass, new Properties() ); } } catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; } } if (service == null) { throw new NamingException ("Cannot create service object"); } serviceQname = service.getServiceName(); serviceInterfaceClass = service.getClass(); if (wsdlRefAddr != null) { try { WSDLFactory wsdlfactory = WSDLFactory.newInstance(); WSDLReader reader = wsdlfactory.newWSDLReader(); reader.setFeature("javax.wsdl.importDocuments", true); Definition def = reader.readWSDL((new URL(wsdlRefAddr)).toExternalForm()); javax.wsdl.Service wsdlservice = def.getService(serviceQname); @SuppressWarnings("unchecked") // Can't change the API Map<String,?> ports = wsdlservice.getPorts(); Method m = serviceInterfaceClass.getMethod("setEndpointAddress", new Class[] { java.lang.String.class, java.lang.String.class }); for (Iterator<String> i = ports.keySet().iterator(); i.hasNext();) { String portName = i.next(); Port port = wsdlservice.getPort(portName); String endpoint = getSOAPLocation(port); m.invoke(service, new Object[] {port.getName(), endpoint }); portComponentRef.put(endpoint, new QName(port.getName())); } } catch (Exception e) { if (e instanceof InvocationTargetException) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } } NamingException ex = new NamingException ("Error while reading Wsdl File"); ex.initCause(e); throw ex; } } ServiceProxy proxy = new ServiceProxy(service); // Use port-component-ref for (int i = 0; i < ref.size(); i++) if (ServiceRef.SERVICEENDPOINTINTERFACE.equals(ref.get(i).getType())) { String serviceendpoint = ""; String portlink = ""; serviceendpoint = (String) ref.get(i).getContent(); if (ServiceRef.PORTCOMPONENTLINK.equals(ref.get(i + 1).getType())) { i++; portlink = (String) ref.get(i).getContent(); } portComponentRef.put(serviceendpoint, new QName(portlink)); } proxy.setPortComponentRef(portComponentRef); // Instantiate service with proxy class Class<?>[] interfaces = null; Class<?>[] serviceInterfaces = serviceInterfaceClass.getInterfaces(); interfaces = new Class[serviceInterfaces.length + 1]; for (int i = 0; i < serviceInterfaces.length; i++) { interfaces[i] = serviceInterfaces[i]; } interfaces[interfaces.length - 1] = javax.xml.rpc.Service.class; Object proxyInstance = null; try { proxyInstance = Proxy.newProxyInstance(tcl, interfaces, proxy); } catch (IllegalArgumentException e) { proxyInstance = Proxy.newProxyInstance(tcl, serviceInterfaces, proxy); } // Use handler if (((ServiceRef) ref).getHandlersSize() > 0) { HandlerRegistry handlerRegistry = service.getHandlerRegistry(); ArrayList<String> soaproles = new ArrayList<String>(); while (((ServiceRef) ref).getHandlersSize() > 0) { HandlerRef handlerRef = ((ServiceRef) ref).getHandler(); HandlerInfo handlerInfo = new HandlerInfo(); // Loading handler Class tmp = handlerRef.get(HandlerRef.HANDLER_CLASS); if ((tmp == null) || (tmp.getContent() == null)) break; Class<?> handlerClass = null; try { handlerClass = tcl.loadClass((String) tmp.getContent()); } catch(ClassNotFoundException e) { break; } // Load all datas relative to the handler : SOAPHeaders, config init element, // portNames to be set on ArrayList<QName> headers = new ArrayList<QName>(); Hashtable<String,String> config = new Hashtable<String,String>(); ArrayList<String> portNames = new ArrayList<String>(); for (int i = 0; i < handlerRef.size(); i++) if (HandlerRef.HANDLER_LOCALPART.equals(handlerRef.get(i).getType())) { String localpart = ""; String namespace = ""; localpart = (String) handlerRef.get(i).getContent(); if (HandlerRef.HANDLER_NAMESPACE.equals(handlerRef.get(i + 1).getType())) { i++; namespace = (String) handlerRef.get(i).getContent(); } QName header = new QName(namespace, localpart); headers.add(header); } else if (HandlerRef.HANDLER_PARAMNAME.equals(handlerRef.get(i).getType())) { String paramName = ""; String paramValue = ""; paramName = (String) handlerRef.get(i).getContent(); if (HandlerRef.HANDLER_PARAMVALUE.equals(handlerRef.get(i + 1).getType())) { i++; paramValue = (String) handlerRef.get(i).getContent(); } config.put(paramName, paramValue); } else if (HandlerRef.HANDLER_SOAPROLE.equals(handlerRef.get(i).getType())) { String soaprole = ""; soaprole = (String) handlerRef.get(i).getContent(); soaproles.add(soaprole); } else if (HandlerRef.HANDLER_PORTNAME.equals(handlerRef.get(i).getType())) { String portName = ""; portName = (String) handlerRef.get(i).getContent(); portNames.add(portName); } // Set the handlers informations handlerInfo.setHandlerClass(handlerClass); handlerInfo.setHeaders(headers.toArray(new QName[headers.size()])); handlerInfo.setHandlerConfig(config); if (!portNames.isEmpty()) { Iterator<String> iter = portNames.iterator(); while (iter.hasNext()) initHandlerChain(new QName(iter.next()), handlerRegistry, handlerInfo, soaproles); } else { Enumeration<QName> e = portComponentRef.elements(); while(e.hasMoreElements()) initHandlerChain(e.nextElement(), handlerRegistry, handlerInfo, soaproles); } } } return proxyInstance; } return null; }
// in java/org/apache/naming/factory/ResourceFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof ResourceRef) { Reference ref = (Reference) obj; ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch (Exception e) { if (e instanceof NamingException) throw (NamingException) e; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; } } } else { if (ref.getClassName().equals("javax.sql.DataSource")) { String javaxSqlDataSourceFactoryClassName = System.getProperty("javax.sql.DataSource.Factory", Constants.DBCP_DATASOURCE_FACTORY); try { factory = (ObjectFactory) Class.forName(javaxSqlDataSourceFactoryClassName) .newInstance(); } catch (Exception e) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; } } else if (ref.getClassName().equals("javax.mail.Session")) { String javaxMailSessionFactoryClassName = System.getProperty("javax.mail.Session.Factory", "org.apache.naming.factory.MailSessionFactory"); try { factory = (ObjectFactory) Class.forName(javaxMailSessionFactoryClassName) .newInstance(); } catch(Throwable t) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } } if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/factory/EjbFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof EjbRef) { Reference ref = (Reference) obj; // If ejb-link has been specified, resolving the link using JNDI RefAddr linkRefAddr = ref.get(EjbRef.LINK); if (linkRefAddr != null) { // Retrieving the EJB link String ejbLink = linkRefAddr.getContent().toString(); Object beanObj = (new InitialContext()).lookup(ejbLink); return beanObj; } ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch(Throwable t) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(t); throw ex; } } } else { String javaxEjbFactoryClassName = System.getProperty("javax.ejb.Factory", Constants.OPENEJB_EJB_FACTORY); try { factory = (ObjectFactory) Class.forName(javaxEjbFactoryClassName).newInstance(); } catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/factory/TransactionFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof TransactionRef) { Reference ref = (Reference) obj; ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } } if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/factory/MailSessionFactory.java
Override public Object getObjectInstance(Object refObj, Name name, Context context, Hashtable<?,?> env) throws Exception { // Return null if we cannot create an object of the requested type final Reference ref = (Reference) refObj; if (!ref.getClassName().equals(factoryType)) return (null); // Create a new Session inside a doPrivileged block, so that JavaMail // can read its default properties without throwing Security // exceptions. // // Bugzilla 31288, 33077: add support for authentication. return AccessController.doPrivileged(new PrivilegedAction<Session>() { @Override public Session run() { // Create the JavaMail properties we will use Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", "localhost"); String password = null; Enumeration<RefAddr> attrs = ref.getAll(); while (attrs.hasMoreElements()) { RefAddr attr = attrs.nextElement(); if ("factory".equals(attr.getType())) { continue; } if ("password".equals(attr.getType())) { password = (String) attr.getContent(); continue; } props.put(attr.getType(), attr.getContent()); } Authenticator auth = null; if (password != null) { String user = props.getProperty("mail.smtp.user"); if(user == null) { user = props.getProperty("mail.user"); } if(user != null) { final PasswordAuthentication pa = new PasswordAuthentication(user, password); auth = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return pa; } }; } } // Create and return the new Session object Session session = Session.getInstance(props, auth); return (session); } } ); }
// in java/org/apache/coyote/AbstractProtocol.java
Override public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { oname = name; mserver = server; domain = name.getDomain(); return name; }
// in java/org/apache/coyote/AbstractProtocol.java
Override public void preDeregister() throws Exception { // NOOP }
// in java/org/apache/coyote/AbstractProtocol.java
Override public void init() throws Exception { if (getLog().isInfoEnabled()) getLog().info(sm.getString("abstractProtocolHandler.init", getName())); if (oname == null) { // Component not pre-registered so register it oname = createObjectName(); if (oname != null) { Registry.getRegistry(null, null).registerComponent(this, oname, null); } } if (this.domain != null) { try { tpOname = new ObjectName(domain + ":" + "type=ThreadPool,name=" + getName()); Registry.getRegistry(null, null).registerComponent(endpoint, tpOname, null); } catch (Exception e) { getLog().error(sm.getString( "abstractProtocolHandler.mbeanRegistrationFailed", tpOname, getName()), e); } rgOname=new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getName()); Registry.getRegistry(null, null).registerComponent( getHandler().getGlobal(), rgOname, null ); } String endpointName = getName(); endpoint.setName(endpointName.substring(1, endpointName.length()-1)); try { endpoint.init(); } catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.initError", getName()), ex); throw ex; } }
// in java/org/apache/coyote/AbstractProtocol.java
Override public void start() throws Exception { if (getLog().isInfoEnabled()) getLog().info(sm.getString("abstractProtocolHandler.start", getName())); try { endpoint.start(); } catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.startError", getName()), ex); throw ex; } }
// in java/org/apache/coyote/AbstractProtocol.java
Override public void pause() throws Exception { if(getLog().isInfoEnabled()) getLog().info(sm.getString("abstractProtocolHandler.pause", getName())); try { endpoint.pause(); } catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.pauseError", getName()), ex); throw ex; } }
// in java/org/apache/coyote/AbstractProtocol.java
Override public void resume() throws Exception { if(getLog().isInfoEnabled()) getLog().info(sm.getString("abstractProtocolHandler.resume", getName())); try { endpoint.resume(); } catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.resumeError", getName()), ex); throw ex; } }
// in java/org/apache/coyote/AbstractProtocol.java
Override public void stop() throws Exception { if(getLog().isInfoEnabled()) getLog().info(sm.getString("abstractProtocolHandler.stop", getName())); try { endpoint.stop(); } catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.stopError", getName()), ex); throw ex; } }
// in java/org/apache/coyote/http11/Http11NioProtocol.java
Override public void start() throws Exception { super.start(); if (npnHandler != null) { npnHandler.init(getEndpoint(), 0, adapter); } }
// in java/org/apache/coyote/http11/Http11Protocol.java
Override public void start() throws Exception { super.start(); if (npnHandler != null) { npnHandler.init(endpoint, 0, adapter); } }
// in java/org/apache/coyote/http11/AbstractHttp11JsseProtocol.java
Override public void init() throws Exception { // SSL implementation needs to be in place before end point is // initialized sslImplementation = SSLImplementation.getInstance(sslImplementationName); super.init(); }
// in java/org/apache/coyote/http11/Http11AprProtocol.java
Override public void start() throws Exception { super.start(); if (npnHandler != null) { long sslCtx = ((AprEndpoint) endpoint).getJniSslContext(); npnHandler.init(endpoint, sslCtx, adapter); } }
// in java/org/apache/coyote/spdy/SpdyProxyProtocol.java
Override public void start() throws Exception { super.start(); spdyContext = new SpdyContext(); spdyContext.setTlsComprression(false, false); spdyContext.setHandler(new SpdyHandler() { @Override public void onStream(SpdyConnection con, SpdyStream ch) throws IOException { SpdyProcessor sp = new SpdyProcessor(con, endpoint); sp.setAdapter(adapter); sp.onSynStream(ch); } }); spdyContext.setNetSupport(new NetSupportSocket()); spdyContext.setExecutor(endpoint.getExecutor()); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
long getSslCtx() throws Exception { if (sslCtx == 0) { synchronized (AprSocketContext.class) { boolean serverMode = acceptor != null; sslCtx = SSLContext.make(getRootPool(), sslProtocol, serverMode ? SSL.SSL_MODE_SERVER : SSL.SSL_MODE_CLIENT); // SSL.SSL_OP_NO_SSLv3 int opts = SSL.SSL_OP_NO_SSLv2 | SSL.SSL_OP_SINGLE_DH_USE; if (!USE_TICKETS || serverMode && ticketKey == null) { opts |= SSL.SSL_OP_NO_TICKET; } SSLContext.setOptions(sslCtx, opts); // Set revocation // SSLContext.setCARevocation(sslContext, SSLCARevocationFile, SSLCARevocationPath); // Client certificate verification - maybe make it option try { SSLContext.setCipherSuite(sslCtx, SSLCipherSuite); if (serverMode) { if (ticketKey != null) { //SSLExt.setTicketKeys(sslCtx, ticketKey, ticketKey.length); } if (certFile != null) { boolean rc = SSLContext.setCertificate(sslCtx, certFile, keyFile, null, SSL.SSL_AIDX_DSA); if (!rc) { throw new IOException("Can't set keys"); } } SSLContext.setVerify(sslCtx, SSL.SSL_CVERIFY_NONE, 10); if (spdyNPN != null) { SSLExt.setNPN(sslCtx, spdyNPN, spdyNPN.length); } } else { if (tlsCertVerifier != null) { // NONE ? SSLContext.setVerify(sslCtx, SSL.SSL_CVERIFY_NONE, 10); } else { SSLContext.setCACertificate(sslCtx, "/etc/ssl/certs/ca-certificates.crt", "/etc/ssl/certs"); SSLContext.setVerify(sslCtx, SSL.SSL_CVERIFY_REQUIRE, 10); } if (spdyNPN != null) { SSLExt.setNPN(sslCtx, spdyNPN, spdyNPN.length); } } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } long mode = SSLExt.sslCtxSetMode(sslCtx, SSLExt.SSL_MODE_ENABLE_PARTIAL_WRITE | SSLExt.SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); // TODO: try release buffers } }
// in java/org/apache/tomcat/jni/Library.java
public static boolean initialize(String libraryName) throws Exception { if (_instance == null) { if (libraryName == null) _instance = new Library(); else _instance = new Library(libraryName); TCN_MAJOR_VERSION = version(0x01); TCN_MINOR_VERSION = version(0x02); TCN_PATCH_VERSION = version(0x03); TCN_IS_DEV_VERSION = version(0x04); APR_MAJOR_VERSION = version(0x11); APR_MINOR_VERSION = version(0x12); APR_PATCH_VERSION = version(0x13); APR_IS_DEV_VERSION = version(0x14); APR_SIZEOF_VOIDP = size(1); APR_PATH_MAX = size(2); APRMAXHOSTLEN = size(3); APR_MAX_IOVEC_SIZE = size(4); APR_MAX_SECS_TO_LINGER = size(5); APR_MMAP_THRESHOLD = size(6); APR_MMAP_LIMIT = size(7); APR_HAVE_IPV6 = has(0); APR_HAS_SHARED_MEMORY = has(1); APR_HAS_THREADS = has(2); APR_HAS_SENDFILE = has(3); APR_HAS_MMAP = has(4); APR_HAS_FORK = has(5); APR_HAS_RANDOM = has(6); APR_HAS_OTHER_CHILD = has(7); APR_HAS_DSO = has(8); APR_HAS_SO_ACCEPTFILTER = has(9); APR_HAS_UNICODE_FS = has(10); APR_HAS_PROC_INVOKED = has(11); APR_HAS_USER = has(12); APR_HAS_LARGE_FILES = has(13); APR_HAS_XTHREAD_FILES = has(14); APR_HAS_OS_UUID = has(15); APR_IS_BIGENDIAN = has(16); APR_FILES_AS_SOCKETS = has(17); APR_CHARSET_EBCDIC = has(18); APR_TCP_NODELAY_INHERITED = has(19); APR_O_NONBLOCK_INHERITED = has(20); if (APR_MAJOR_VERSION < 1) { throw new UnsatisfiedLinkError("Unsupported APR Version (" + aprVersionString() + ")"); } if (!APR_HAS_THREADS) { throw new UnsatisfiedLinkError("Missing APR_HAS_THREADS"); } } return initialize(); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
Override public void bind() throws Exception { serverSock = ServerSocketChannel.open(); socketProperties.setProperties(serverSock.socket()); InetSocketAddress addr = (getAddress()!=null?new InetSocketAddress(getAddress(),getPort()):new InetSocketAddress(getPort())); serverSock.socket().bind(addr,getBacklog()); serverSock.configureBlocking(true); //mimic APR behavior serverSock.socket().setSoTimeout(getSocketProperties().getSoTimeout()); // Initialize thread count defaults for acceptor, poller if (acceptorThreadCount == 0) { // FIXME: Doesn't seem to work that well with multiple accept threads acceptorThreadCount = 1; } if (pollerThreadCount <= 0) { //minimum one poller thread pollerThreadCount = 1; } stopLatch = new CountDownLatch(pollerThreadCount); // Initialize SSL if needed if (isSSLEnabled()) { SSLUtil sslUtil = handler.getSslImplementation().getSSLUtil(this); sslContext = sslUtil.createSSLContext(); sslContext.init(wrap(sslUtil.getKeyManagers()), sslUtil.getTrustManagers(), null); SSLSessionContext sessionContext = sslContext.getServerSessionContext(); if (sessionContext != null) { sslUtil.configureSessionContext(sessionContext); } } if (oomParachute>0) reclaimParachute(true); selectorPool.open(); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
Override public void startInternal() throws Exception { if (!running) { running = true; paused = false; // Create worker collection if ( getExecutor() == null ) { createExecutor(); } initializeConnectionLatch(); // Start poller threads pollers = new Poller[getPollerThreadCount()]; for (int i=0; i<pollers.length; i++) { pollers[i] = new Poller(); Thread pollerThread = new Thread(pollers[i], getName() + "-ClientPoller-"+i); pollerThread.setPriority(threadPriority); pollerThread.setDaemon(true); pollerThread.start(); } startAcceptorThreads(); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
Override public void unbind() throws Exception { if (log.isDebugEnabled()) { log.debug("Destroy initiated for "+new InetSocketAddress(getAddress(),getPort())); } if (running) { stop(); } // Close server socket serverSock.socket().close(); serverSock.close(); serverSock = null; sslContext = null; releaseCaches(); selectorPool.close(); if (log.isDebugEnabled()) { log.debug("Destroy completed for "+new InetSocketAddress(getAddress(),getPort())); } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
Override public void bind() throws Exception { // Create the root APR memory pool try { rootPool = Pool.create(0); } catch (UnsatisfiedLinkError e) { throw new Exception(sm.getString("endpoint.init.notavail")); } // Create the pool for the server socket serverSockPool = Pool.create(rootPool); // Create the APR address that will be bound String addressStr = null; if (getAddress() != null) { addressStr = getAddress().getHostAddress(); } int family = Socket.APR_INET; if (Library.APR_HAVE_IPV6) { if (addressStr == null) { if (!OS.IS_BSD && !OS.IS_WIN32 && !OS.IS_WIN64) family = Socket.APR_UNSPEC; } else if (addressStr.indexOf(':') >= 0) { family = Socket.APR_UNSPEC; } } long inetAddress = Address.info(addressStr, family, getPort(), 0, rootPool); // Create the APR server socket serverSock = Socket.create(Address.getInfo(inetAddress).family, Socket.SOCK_STREAM, Socket.APR_PROTO_TCP, rootPool); if (OS.IS_UNIX) { Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Deal with the firewalls that tend to drop the inactive sockets Socket.optSet(serverSock, Socket.APR_SO_KEEPALIVE, 1); // Bind the server socket int ret = Socket.bind(serverSock, inetAddress); if (ret != 0) { throw new Exception(sm.getString("endpoint.init.bind", "" + ret, Error.strerror(ret))); } // Start listening on the server socket ret = Socket.listen(serverSock, getBacklog()); if (ret != 0) { throw new Exception(sm.getString("endpoint.init.listen", "" + ret, Error.strerror(ret))); } if (OS.IS_WIN32 || OS.IS_WIN64) { // On Windows set the reuseaddr flag after the bind/listen Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Sendfile usage on systems which don't support it cause major problems if (useSendfile && !Library.APR_HAS_SENDFILE) { useSendfile = false; } // Initialize thread count defaults for acceptor, poller and sendfile if (acceptorThreadCount == 0) { // FIXME: Doesn't seem to work that well with multiple accept threads acceptorThreadCount = 1; } if (pollerThreadCount == 0) { if ((OS.IS_WIN32 || OS.IS_WIN64) && (getMaxConnections() > 1024)) { // The maximum per poller to get reasonable performance is 1024 pollerThreadCount = getMaxConnections() / 1024; // Adjust poller size so that it won't reach the limit setMaxConnections( getMaxConnections() - (getMaxConnections() % 1024)); } else { // No explicit poller size limitation pollerThreadCount = 1; } } if (sendfileThreadCount == 0) { if ((OS.IS_WIN32 || OS.IS_WIN64) && (sendfileSize > 1024)) { // The maximum per poller to get reasonable performance is 1024 sendfileThreadCount = sendfileSize / 1024; // Adjust poller size so that it won't reach the limit sendfileSize = sendfileSize - (sendfileSize % 1024); } else { // No explicit poller size limitation // FIXME: Default to one per CPU ? sendfileThreadCount = 1; } } // Delay accepting of new connections until data is available // Only Linux kernels 2.4 + have that implemented // on other platforms this call is noop and will return APR_ENOTIMPL. if (deferAccept) { if (Socket.optSet(serverSock, Socket.APR_TCP_DEFER_ACCEPT, 1) == Status.APR_ENOTIMPL) { deferAccept = false; } } // Initialize SSL if needed if (isSSLEnabled()) { if (SSLCertificateFile == null) { // This is required throw new Exception(sm.getString("endpoint.apr.noSslCertFile")); } // SSL protocol int value; // This branch can be removed, once the required version is at least 1.1.21. int tcnFullVersion = Library.TCN_MAJOR_VERSION * 1000 + Library.TCN_MINOR_VERSION * 100 + Library.TCN_PATCH_VERSION; if (tcnFullVersion <= 1120) { value = SSL.SSL_PROTOCOL_ALL; if ("SSLv2".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_SSLV2; } else if ("SSLv3".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_SSLV3; } else if ("TLSv1".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_TLSV1; } else if ("SSLv2+SSLv3".equalsIgnoreCase(SSLProtocol)) { value = SSL.SSL_PROTOCOL_SSLV2 | SSL.SSL_PROTOCOL_SSLV3; } else if ("all".equalsIgnoreCase(SSLProtocol) || SSLProtocol == null || SSLProtocol.length() == 0) { // NOOP, use the default defined above } else { // Protocol not recognized, fail to start as it is safer than // continuing with the default which might enable more than the // is required throw new Exception(sm.getString( "endpoint.apr.invalidSslProtocol", SSLProtocol)); } } else { value = SSL.SSL_PROTOCOL_NONE; if (SSLProtocol == null || SSLProtocol.length() == 0) { value = SSL.SSL_PROTOCOL_ALL; } else { for (String protocol : SSLProtocol.split("\\+")) { protocol = protocol.trim(); if ("SSLv2".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_SSLV2; } else if ("SSLv3".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_SSLV3; } else if ("TLSv1".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_TLSV1; } else if ("all".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_ALL; } else { // Protocol not recognized, fail to start as it is safer than // continuing with the default which might enable more than the // is required throw new Exception(sm.getString( "endpoint.apr.invalidSslProtocol", SSLProtocol)); } } } } // Create SSL Context sslContext = SSLContext.make(rootPool, value, SSL.SSL_MODE_SERVER); if (SSLInsecureRenegotiation) { boolean legacyRenegSupported = false; try { legacyRenegSupported = SSL.hasOp(SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); if (legacyRenegSupported) SSLContext.setOptions(sslContext, SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); } catch (UnsatisfiedLinkError e) { // Ignore } if (!legacyRenegSupported) { // OpenSSL does not support unsafe legacy renegotiation. log.warn(sm.getString("endpoint.warn.noInsecureReneg", SSL.versionString())); } } // List the ciphers that the client is permitted to negotiate SSLContext.setCipherSuite(sslContext, SSLCipherSuite); // Load Server key and certificate SSLContext.setCertificate(sslContext, SSLCertificateFile, SSLCertificateKeyFile, SSLPassword, SSL.SSL_AIDX_RSA); // Set certificate chain file SSLContext.setCertificateChainFile(sslContext, SSLCertificateChainFile, false); // Support Client Certificates SSLContext.setCACertificate(sslContext, SSLCACertificateFile, SSLCACertificatePath); // Set revocation SSLContext.setCARevocation(sslContext, SSLCARevocationFile, SSLCARevocationPath); // Client certificate verification value = SSL.SSL_CVERIFY_NONE; if ("optional".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_OPTIONAL; } else if ("require".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_REQUIRE; } else if ("optionalNoCA".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_OPTIONAL_NO_CA; } SSLContext.setVerify(sslContext, value, SSLVerifyDepth); // For now, sendfile is not supported with SSL useSendfile = false; } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
Override public void startInternal() throws Exception { if (!running) { running = true; paused = false; // Create worker collection if (getExecutor() == null) { createExecutor(); } initializeConnectionLatch(); // Start poller threads pollers = new Poller[pollerThreadCount]; for (int i = 0; i < pollerThreadCount; i++) { pollers[i] = new Poller(false); pollers[i].init(); pollers[i].setName(getName() + "-Poller-" + i); pollers[i].setPriority(threadPriority); pollers[i].setDaemon(true); pollers[i].start(); } // Start comet poller threads cometPollers = new Poller[pollerThreadCount]; for (int i = 0; i < pollerThreadCount; i++) { cometPollers[i] = new Poller(true); cometPollers[i].init(); cometPollers[i].setName(getName() + "-CometPoller-" + i); cometPollers[i].setPriority(threadPriority); cometPollers[i].setDaemon(true); cometPollers[i].start(); } // Start sendfile threads if (useSendfile) { sendfiles = new Sendfile[sendfileThreadCount]; for (int i = 0; i < sendfileThreadCount; i++) { sendfiles[i] = new Sendfile(); sendfiles[i].init(); sendfiles[i].setName(getName() + "-Sendfile-" + i); sendfiles[i].setPriority(threadPriority); sendfiles[i].setDaemon(true); sendfiles[i].start(); } } startAcceptorThreads(); // Start async timeout thread Thread timeoutThread = new Thread(new AsyncTimeout(), getName() + "-AsyncTimeout"); timeoutThread.setPriority(threadPriority); timeoutThread.setDaemon(true); timeoutThread.start(); } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
Override public void unbind() throws Exception { if (running) { stop(); } // Destroy pool if it was initialised if (serverSockPool != 0) { Pool.destroy(serverSockPool); serverSockPool = 0; } // Close server socket if it was initialised if (serverSock != 0) { Socket.close(serverSock); serverSock = 0; } sslContext = 0; // Close all APR memory pools and resources if initialised if (rootPool != 0) { Pool.destroy(rootPool); rootPool = 0; } handler.recycle(); }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
public final void init() throws Exception { if (bindOnInit) { bind(); bindState = BindState.BOUND_ON_INIT; } }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
public final void start() throws Exception { if (bindState == BindState.UNBOUND) { bind(); bindState = BindState.BOUND_ON_START; } startInternal(); }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
public final void stop() throws Exception { stopInternal(); if (bindState == BindState.BOUND_ON_START) { unbind(); bindState = BindState.UNBOUND; } }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
public final void destroy() throws Exception { if (bindState == BindState.BOUND_ON_INIT) { unbind(); bindState = BindState.UNBOUND; } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
Override public void bind() throws Exception { // Initialize thread count defaults for acceptor if (acceptorThreadCount == 0) { acceptorThreadCount = 1; } // Initialize maxConnections if (getMaxConnections() == 0) { // User hasn't set a value - use the default setMaxConnections(getMaxThreadsExecutor(true)); } if (serverSocketFactory == null) { if (isSSLEnabled()) { serverSocketFactory = handler.getSslImplementation().getServerSocketFactory(this); } else { serverSocketFactory = new DefaultServerSocketFactory(this); } } if (serverSocket == null) { try { if (getAddress() == null) { serverSocket = serverSocketFactory.createSocket(getPort(), getBacklog()); } else { serverSocket = serverSocketFactory.createSocket(getPort(), getBacklog(), getAddress()); } } catch (BindException orig) { String msg; if (getAddress() == null) msg = orig.getMessage() + " <null>:" + getPort(); else msg = orig.getMessage() + " " + getAddress().toString() + ":" + getPort(); BindException be = new BindException(msg); be.initCause(orig); throw be; } } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
Override public void startInternal() throws Exception { if (!running) { running = true; paused = false; // Create worker collection if (getExecutor() == null) { createExecutor(); } initializeConnectionLatch(); startAcceptorThreads(); // Start async timeout thread Thread timeoutThread = new Thread(new AsyncTimeout(), getName() + "-AsyncTimeout"); timeoutThread.setPriority(threadPriority); timeoutThread.setDaemon(true); timeoutThread.start(); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
Override public void unbind() throws Exception { if (running) { stop(); } if (serverSocket != null) { try { if (serverSocket != null) serverSocket.close(); } catch (Exception e) { log.error(sm.getString("endpoint.err.close"), e); } serverSocket = null; } handler.recycle(); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public SSLContext createSSLContext() throws Exception { // SSL protocol variant (e.g., TLS, SSL v3, etc.) String protocol = endpoint.getSslProtocol(); if (protocol == null) { protocol = defaultProtocol; } SSLContext context = SSLContext.getInstance(protocol); return context; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public KeyManager[] getKeyManagers() throws Exception { String keystoreType = endpoint.getKeystoreType(); if (keystoreType == null) { keystoreType = defaultKeystoreType; } String algorithm = endpoint.getAlgorithm(); if (algorithm == null) { algorithm = KeyManagerFactory.getDefaultAlgorithm(); } return getKeyManagers(keystoreType, endpoint.getKeystoreProvider(), algorithm, endpoint.getKeyAlias()); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public TrustManager[] getTrustManagers() throws Exception { String truststoreType = endpoint.getTruststoreType(); if (truststoreType == null) { truststoreType = System.getProperty("javax.net.ssl.trustStoreType"); } if (truststoreType == null) { truststoreType = endpoint.getKeystoreType(); } if (truststoreType == null) { truststoreType = defaultKeystoreType; } String algorithm = endpoint.getTruststoreAlgorithm(); if (algorithm == null) { algorithm = TrustManagerFactory.getDefaultAlgorithm(); } return getTrustManagers(truststoreType, endpoint.getKeystoreProvider(), algorithm); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected KeyManager[] getKeyManagers(String keystoreType, String keystoreProvider, String algorithm, String keyAlias) throws Exception { KeyManager[] kms = null; String keystorePass = getKeystorePassword(); KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass); if (keyAlias != null && !ks.isKeyEntry(keyAlias)) { throw new IOException( sm.getString("jsse.alias_no_key_entry", keyAlias)); } KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); String keyPass = endpoint.getKeyPass(); if (keyPass == null) { keyPass = keystorePass; } kmf.init(ks, keyPass.toCharArray()); kms = kmf.getKeyManagers(); if (keyAlias != null) { String alias = keyAlias; if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) { alias = alias.toLowerCase(Locale.ENGLISH); } for(int i=0; i<kms.length; i++) { kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias); } } return kms; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected TrustManager[] getTrustManagers(String keystoreType, String keystoreProvider, String algorithm) throws Exception { String crlf = endpoint.getCrlFile(); String className = endpoint.getTrustManagerClassName(); if(className != null && className.length() > 0) { ClassLoader classLoader = getClass().getClassLoader(); Class<?> clazz = classLoader.loadClass(className); if(!(TrustManager.class.isAssignableFrom(clazz))){ throw new InstantiationException(sm.getString( "jsse.invalidTrustManagerClassName", className)); } Object trustManagerObject = clazz.newInstance(); TrustManager trustManager = (TrustManager) trustManagerObject; return new TrustManager[]{ trustManager }; } TrustManager[] tms = null; KeyStore trustStore = getTrustStore(keystoreType, keystoreProvider); if (trustStore != null || endpoint.getTrustManagerClassName() != null) { if (crlf == null) { TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init(trustStore); tms = tmf.getTrustManagers(); } else { TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); CertPathParameters params = getParameters(algorithm, crlf, trustStore); ManagerFactoryParameters mfp = new CertPathTrustManagerParameters(params); tmf.init(mfp); tms = tmf.getTrustManagers(); } } return tms; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected CertPathParameters getParameters(String algorithm, String crlf, KeyStore trustStore) throws Exception { CertPathParameters params = null; if("PKIX".equalsIgnoreCase(algorithm)) { PKIXBuilderParameters xparams = new PKIXBuilderParameters(trustStore, new X509CertSelector()); Collection<? extends CRL> crls = getCRLs(crlf); CertStoreParameters csp = new CollectionCertStoreParameters(crls); CertStore store = CertStore.getInstance("Collection", csp); xparams.addCertStore(store); xparams.setRevocationEnabled(true); String trustLength = endpoint.getTrustMaxCertLength(); if(trustLength != null) { try { xparams.setMaxPathLength(Integer.parseInt(trustLength)); } catch(Exception ex) { log.warn("Bad maxCertLength: "+trustLength); } } params = xparams; } else { throw new CRLException("CRLs not supported for type: "+algorithm); } return params; }
// in java/org/apache/tomcat/util/http/mapper/Mapper.java
public void map(MessageBytes host, MessageBytes uri, String version, MappingData mappingData) throws Exception { if (host.isNull()) { host.getCharChunk().append(defaultHostName); } host.toChars(); uri.toChars(); internalMap(host.getCharChunk(), uri.getCharChunk(), version, mappingData); }
// in java/org/apache/tomcat/util/http/mapper/Mapper.java
public void map(MessageBytes uri, MappingData mappingData) throws Exception { uri.toChars(); CharChunk uricc = uri.getCharChunk(); uricc.setLimit(-1); internalMapWrapper(context, uricc, mappingData); }
// in java/org/apache/tomcat/util/http/mapper/Mapper.java
private final void internalMap(CharChunk host, CharChunk uri, String version, MappingData mappingData) throws Exception { uri.setLimit(-1); Context[] contexts = null; Context context = null; ContextVersion contextVersion = null; int nesting = 0; // Virtual host mapping if (mappingData.host == null) { Host[] hosts = this.hosts; int pos = findIgnoreCase(hosts, host); if ((pos != -1) && (host.equalsIgnoreCase(hosts[pos].name))) { mappingData.host = hosts[pos].object; contexts = hosts[pos].contextList.contexts; nesting = hosts[pos].contextList.nesting; } else { if (defaultHostName == null) { return; } pos = find(hosts, defaultHostName); if ((pos != -1) && (defaultHostName.equals(hosts[pos].name))) { mappingData.host = hosts[pos].object; contexts = hosts[pos].contextList.contexts; nesting = hosts[pos].contextList.nesting; } else { return; } } } // Context mapping if (mappingData.context == null) { int pos = find(contexts, uri); if (pos == -1) { return; } int lastSlash = -1; int uriEnd = uri.getEnd(); int length = -1; boolean found = false; while (pos >= 0) { if (uri.startsWith(contexts[pos].name)) { length = contexts[pos].name.length(); if (uri.getLength() == length) { found = true; break; } else if (uri.startsWithIgnoreCase("/", length)) { found = true; break; } } if (lastSlash == -1) { lastSlash = nthSlash(uri, nesting + 1); } else { lastSlash = lastSlash(uri); } uri.setEnd(lastSlash); pos = find(contexts, uri); } uri.setEnd(uriEnd); if (!found) { if (contexts[0].name.equals("")) { context = contexts[0]; } } else { context = contexts[pos]; } if (context != null) { mappingData.contextPath.setString(context.name); } } if (context != null) { ContextVersion[] contextVersions = context.versions; int versionCount = contextVersions.length; if (versionCount > 1) { Object[] contextObjects = new Object[contextVersions.length]; for (int i = 0; i < contextObjects.length; i++) { contextObjects[i] = contextVersions[i].object; } mappingData.contexts = contextObjects; } if (version == null) { // Return the latest version contextVersion = contextVersions[versionCount - 1]; } else { int pos = find(contextVersions, version); if (pos < 0 || !contextVersions[pos].name.equals(version)) { // Return the latest version contextVersion = contextVersions[versionCount - 1]; } else { contextVersion = contextVersions[pos]; } } mappingData.context = contextVersion.object; } // Wrapper mapping if ((contextVersion != null) && (mappingData.wrapper == null)) { internalMapWrapper(contextVersion, uri, mappingData); } }
// in java/org/apache/tomcat/util/http/mapper/Mapper.java
private final void internalMapWrapper(ContextVersion contextVersion, CharChunk path, MappingData mappingData) throws Exception { int pathOffset = path.getOffset(); int pathEnd = path.getEnd(); int servletPath = pathOffset; boolean noServletPath = false; int length = contextVersion.path.length(); if (length != (pathEnd - pathOffset)) { servletPath = pathOffset + length; } else { noServletPath = true; path.append('/'); pathOffset = path.getOffset(); pathEnd = path.getEnd(); servletPath = pathOffset+length; } path.setOffset(servletPath); // Rule 1 -- Exact Match Wrapper[] exactWrappers = contextVersion.exactWrappers; internalMapExactWrapper(exactWrappers, path, mappingData); // Rule 2 -- Prefix Match boolean checkJspWelcomeFiles = false; Wrapper[] wildcardWrappers = contextVersion.wildcardWrappers; if (mappingData.wrapper == null) { internalMapWildcardWrapper(wildcardWrappers, contextVersion.nesting, path, mappingData); if (mappingData.wrapper != null && mappingData.jspWildCard) { char[] buf = path.getBuffer(); if (buf[pathEnd - 1] == '/') { /* * Path ending in '/' was mapped to JSP servlet based on * wildcard match (e.g., as specified in url-pattern of a * jsp-property-group. * Force the context's welcome files, which are interpreted * as JSP files (since they match the url-pattern), to be * considered. See Bugzilla 27664. */ mappingData.wrapper = null; checkJspWelcomeFiles = true; } else { // See Bugzilla 27704 mappingData.wrapperPath.setChars(buf, path.getStart(), path.getLength()); mappingData.pathInfo.recycle(); } } } if(mappingData.wrapper == null && noServletPath) { // The path is empty, redirect to "/" mappingData.redirectPath.setChars (path.getBuffer(), pathOffset, pathEnd-pathOffset); path.setEnd(pathEnd - 1); return; } // Rule 3 -- Extension Match Wrapper[] extensionWrappers = contextVersion.extensionWrappers; if (mappingData.wrapper == null && !checkJspWelcomeFiles) { internalMapExtensionWrapper(extensionWrappers, path, mappingData, true); } // Rule 4 -- Welcome resources processing for servlets if (mappingData.wrapper == null) { boolean checkWelcomeFiles = checkJspWelcomeFiles; if (!checkWelcomeFiles) { char[] buf = path.getBuffer(); checkWelcomeFiles = (buf[pathEnd - 1] == '/'); } if (checkWelcomeFiles) { for (int i = 0; (i < contextVersion.welcomeResources.length) && (mappingData.wrapper == null); i++) { path.setOffset(pathOffset); path.setEnd(pathEnd); path.append(contextVersion.welcomeResources[i], 0, contextVersion.welcomeResources[i].length()); path.setOffset(servletPath); // Rule 4a -- Welcome resources processing for exact macth internalMapExactWrapper(exactWrappers, path, mappingData); // Rule 4b -- Welcome resources processing for prefix match if (mappingData.wrapper == null) { internalMapWildcardWrapper (wildcardWrappers, contextVersion.nesting, path, mappingData); } // Rule 4c -- Welcome resources processing // for physical folder if (mappingData.wrapper == null && contextVersion.resources != null) { Object file = null; String pathStr = path.toString(); try { file = contextVersion.resources.lookup(pathStr); } catch(NamingException nex) { // Swallow not found, since this is normal } if (file != null && !(file instanceof DirContext) ) { internalMapExtensionWrapper(extensionWrappers, path, mappingData, true); if (mappingData.wrapper == null && contextVersion.defaultWrapper != null) { mappingData.wrapper = contextVersion.defaultWrapper.object; mappingData.requestPath.setChars (path.getBuffer(), path.getStart(), path.getLength()); mappingData.wrapperPath.setChars (path.getBuffer(), path.getStart(), path.getLength()); mappingData.requestPath.setString(pathStr); mappingData.wrapperPath.setString(pathStr); } } } } path.setOffset(servletPath); path.setEnd(pathEnd); } }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
Override public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { // Save the length of the file size = outputFile.length(); /* * The uploaded file is being stored on disk * in a temporary location so move it to the * desired file. */ if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream( new FileInputStream(outputFile)); out = new BufferedOutputStream( new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } if (out != null) { try { out.close(); } catch (IOException e) { // ignore } } } } } else { /* * For whatever reason we cannot write the * file to disk. */ throw new FileUploadException( "Cannot write uploaded file to disk!"); } } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { if( log.isDebugEnabled()) log.debug("preRegister " + resource + " " + name ); oname=name; if( resource instanceof MBeanRegistration ) { oname = ((MBeanRegistration)resource).preRegister(server, name ); } return oname; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void preDeregister() throws Exception { if( resource instanceof MBeanRegistration ) { ((MBeanRegistration)resource).preDeregister(); } }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsSerSource.java
Override public List<ObjectName> loadDescriptors( Registry registry, String type, Object source) throws Exception { setRegistry(registry); setType(type); setSource(source); execute(); return mbeans; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsSerSource.java
public void execute() throws Exception { if( registry==null ) registry=Registry.getRegistry(null, null); long t1=System.currentTimeMillis(); try { InputStream stream=null; if( source instanceof URL ) { stream=((URL)source).openStream(); } if( source instanceof InputStream ) { stream=(InputStream)source; } if( stream==null ) { throw new Exception( "Can't process "+ source); } ObjectInputStream ois=new ObjectInputStream(stream); Thread.currentThread().setContextClassLoader(ManagedBean.class.getClassLoader()); Object obj=ois.readObject(); //log.info("Reading " + obj); ManagedBean beans[]=(ManagedBean[])obj; // after all are read without error for( int i=0; i<beans.length; i++ ) { registry.addManagedBean(beans[i]); } } catch( Exception ex ) { log.error( "Error reading descriptors " + source + " " + ex.toString(), ex); throw ex; } long t2=System.currentTimeMillis(); log.info( "Reading descriptors ( ser ) " + (t2-t1)); }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java
Override public List<ObjectName> loadDescriptors( Registry registry, String type, Object source) throws Exception { setRegistry(registry); setType(type); setSource(source); execute(); return mbeans; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java
public void execute() throws Exception { if (registry == null) { registry = Registry.getRegistry(null, null); } InputStream stream = (InputStream) source; if (digester == null) { digester = createDigester(); } ArrayList<ManagedBean> loadedMbeans = new ArrayList<ManagedBean>(); synchronized (digester) { // Process the input file to configure our registry try { // Push our registry object onto the stack digester.push(loadedMbeans); digester.parse(stream); } catch (Exception e) { log.error("Error digesting Registry data", e); throw e; } finally { digester.reset(); } } Iterator<ManagedBean> iter = loadedMbeans.iterator(); while (iter.hasNext()) { registry.addManagedBean(iter.next()); } }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsIntrospectionSource.java
Override public List<ObjectName> loadDescriptors(Registry registry, String type, Object source) throws Exception { setRegistry(registry); setType(type); setSource(source); execute(); return mbeans; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsIntrospectionSource.java
public void execute() throws Exception { if( registry==null ) registry=Registry.getRegistry(null, null); try { ManagedBean managed = createManagedBean(registry, null, (Class<?>)source, type); if( managed==null ) return; managed.setName( type ); registry.addManagedBean(managed); } catch( Exception ex ) { log.error( "Error reading descriptors ", ex); } }
// in java/org/apache/tomcat/util/modeler/Registry.java
Override public void registerComponent(Object bean, String oname, String type) throws Exception { registerComponent(bean, new ObjectName(oname), type); }
// in java/org/apache/tomcat/util/modeler/Registry.java
Override public void invoke(List<ObjectName> mbeans, String operation, boolean failFirst ) throws Exception { if( mbeans==null ) { return; } Iterator<ObjectName> itr = mbeans.iterator(); while(itr.hasNext()) { ObjectName current = itr.next(); try { if(current == null) { continue; } if(getMethodInfo(current, operation) == null) { continue; } getMBeanServer().invoke(current, operation, new Object[] {}, new String[] {}); } catch( Exception t ) { if( failFirst ) throw t; log.info("Error initializing " + current + " " + t.toString()); } } }
// in java/org/apache/tomcat/util/modeler/Registry.java
public ManagedBean findManagedBean(Object bean, Class<?> beanClass, String type) throws Exception { if( bean!=null && beanClass==null ) { beanClass=bean.getClass(); } if( type==null ) { type=beanClass.getName(); } // first look for existing descriptor ManagedBean managed = findManagedBean(type); // Search for a descriptor in the same package if( managed==null ) { // check package and parent packages if( log.isDebugEnabled() ) { log.debug( "Looking for descriptor "); } findDescriptor( beanClass, type ); managed=findManagedBean(type); } // Still not found - use introspection if( managed==null ) { if( log.isDebugEnabled() ) { log.debug( "Introspecting "); } // introspection load("MbeansDescriptorsIntrospectionSource", beanClass, type); managed=findManagedBean(type); if( managed==null ) { log.warn( "No metadata found for " + type ); return null; } managed.setName( type ); addManagedBean(managed); } return managed; }
// in java/org/apache/tomcat/util/modeler/Registry.java
public List<ObjectName> load( String sourceType, Object source, String param) throws Exception { if( log.isTraceEnabled()) { log.trace("load " + source ); } String location=null; String type=null; Object inputsource=null; if( source instanceof URL ) { URL url=(URL)source; location=url.toString(); type=param; inputsource=url.openStream(); if( sourceType == null ) { sourceType = sourceTypeFromExt(location); } } else if( source instanceof File ) { location=((File)source).getAbsolutePath(); inputsource=new FileInputStream((File)source); type=param; if( sourceType == null ) { sourceType = sourceTypeFromExt(location); } } else if( source instanceof InputStream ) { type=param; inputsource=source; } else if( source instanceof Class<?> ) { location=((Class<?>)source).getName(); type=param; inputsource=source; if( sourceType== null ) { sourceType="MbeansDescriptorsIntrospectionSource"; } } if( sourceType==null ) { sourceType="MbeansDescriptorsDigesterSource"; } ModelerSource ds=getModelerSource(sourceType); List<ObjectName> mbeans = ds.loadDescriptors(this, type, inputsource); return mbeans; }
// in java/org/apache/tomcat/util/modeler/Registry.java
public void registerComponent(Object bean, ObjectName oname, String type) throws Exception { if( log.isDebugEnabled() ) { log.debug( "Managed= "+ oname); } if( bean ==null ) { log.error("Null component " + oname ); return; } try { if( type==null ) { type=bean.getClass().getName(); } ManagedBean managed = findManagedBean(null, bean.getClass(), type); // The real mbean is created and registered DynamicMBean mbean = managed.createMBean(bean); if( getMBeanServer().isRegistered( oname )) { if( log.isDebugEnabled()) { log.debug("Unregistering existing component " + oname ); } getMBeanServer().unregisterMBean( oname ); } getMBeanServer().registerMBean( mbean, oname); } catch( Exception ex) { log.error("Error registering " + oname, ex ); throw ex; } }
// in java/org/apache/tomcat/util/modeler/Registry.java
private ModelerSource getModelerSource( String type ) throws Exception { if( type==null ) type="MbeansDescriptorsDigesterSource"; if( type.indexOf( ".") < 0 ) { type="org.apache.tomcat.util.modeler.modules." + type; } Class<?> c = Class.forName(type); ModelerSource ds=(ModelerSource)c.newInstance(); return ds; }
// in java/org/apache/tomcat/util/modeler/Registry.java
Override public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { this.server=server; return name; }
// in java/org/apache/tomcat/util/modeler/Registry.java
Override public void preDeregister() throws Exception { }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
public static Object callMethod1(Object target, String methodN, Object param1, String typeParam1, ClassLoader cl) throws Exception { if (target == null || param1 == null) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Assert: Illegal params " + target + " " + param1); } if (log.isDebugEnabled()) log.debug("IntrospectionUtils: callMethod1 " + target.getClass().getName() + " " + param1.getClass().getName() + " " + typeParam1); Class<?> params[] = new Class[1]; if (typeParam1 == null) params[0] = param1.getClass(); else params[0] = cl.loadClass(typeParam1); Method m = findMethod(target.getClass(), methodN, params); if (m == null) throw new NoSuchMethodException(target.getClass().getName() + " " + methodN); try { return m.invoke(target, new Object[] { param1 }); } catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; } }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
public static Object callMethodN(Object target, String methodN, Object params[], Class<?> typeParams[]) throws Exception { Method m = null; m = findMethod(target.getClass(), methodN, typeParams); if (m == null) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Can't find method " + methodN + " in " + target + " CLASS " + target.getClass()); return null; } try { Object o = m.invoke(target, params); if (log.isDebugEnabled()) { // debug StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()).append('.') .append(methodN).append("( "); for (int i = 0; i < params.length; i++) { if (i > 0) sb.append(", "); sb.append(params[i]); } sb.append(")"); log.debug("IntrospectionUtils:" + sb.toString()); } return o; } catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; } }
// in java/org/apache/tomcat/util/digester/SetPropertyRule.java
Override public void begin(String namespace, String theName, Attributes attributes) throws Exception { // Identify the actual property name and value to be used String actualName = null; String actualValue = null; for (int i = 0; i < attributes.getLength(); i++) { String name = attributes.getLocalName(i); if ("".equals(name)) { name = attributes.getQName(i); } String value = attributes.getValue(i); if (name.equals(this.name)) { actualName = value; } else if (name.equals(this.value)) { actualValue = value; } } // Get a reference to the top object Object top = digester.peek(); // Log some debugging information if (digester.log.isDebugEnabled()) { digester.log.debug("[SetPropertyRule]{" + digester.match + "} Set " + top.getClass().getName() + " property " + actualName + " to " + actualValue); } // Set the property (with conversion as necessary) if (!digester.isFakeAttribute(top, actualName) && !IntrospectionUtils.setProperty(top, actualName, actualValue) && digester.getRulesValidation()) { digester.log.warn("[SetPropertyRule]{" + digester.match + "} Setting property '" + name + "' to '" + value + "' did not find a matching property."); } }
// in java/org/apache/tomcat/util/digester/ObjectCreateRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { // Identify the name of the class to instantiate String realClassName = className; if (attributeName != null) { String value = attributes.getValue(attributeName); if (value != null) { realClassName = value; } } if (digester.log.isDebugEnabled()) { digester.log.debug("[ObjectCreateRule]{" + digester.match + "}New " + realClassName); } if (realClassName == null) { throw new NullPointerException("No class name specified for " + namespace + " " + name); } // Instantiate the new object and push it on the context stack Class<?> clazz = digester.getClassLoader().loadClass(realClassName); Object instance = clazz.newInstance(); digester.push(instance); }
// in java/org/apache/tomcat/util/digester/ObjectCreateRule.java
Override public void end(String namespace, String name) throws Exception { Object top = digester.pop(); if (digester.log.isDebugEnabled()) { digester.log.debug("[ObjectCreateRule]{" + digester.match + "} Pop " + top.getClass().getName()); } }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (ignoreCreateExceptions) { if (exceptionIgnoredStack == null) { exceptionIgnoredStack = new ArrayStack<Boolean>(); } try { Object instance = getFactory(attributes).createObject(attributes); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule]{" + digester.match + "} New " + instance.getClass().getName()); } digester.push(instance); exceptionIgnoredStack.push(Boolean.FALSE); } catch (Exception e) { // log message and error if (digester.log.isInfoEnabled()) { digester.log.info("[FactoryCreateRule] Create exception ignored: " + ((e.getMessage() == null) ? e.getClass().getName() : e.getMessage())); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule] Ignored exception:", e); } } exceptionIgnoredStack.push(Boolean.TRUE); } } else { Object instance = getFactory(attributes).createObject(attributes); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule]{" + digester.match + "} New " + instance.getClass().getName()); } digester.push(instance); } }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
Override public void end(String namespace, String name) throws Exception { // check if object was created // this only happens if an exception was thrown and we're ignoring them if ( ignoreCreateExceptions && exceptionIgnoredStack != null && !(exceptionIgnoredStack.empty())) { if ((exceptionIgnoredStack.pop()).booleanValue()) { // creation exception was ignored // nothing was put onto the stack if (digester.log.isTraceEnabled()) { digester.log.trace("[FactoryCreateRule] No creation so no push so no pop"); } return; } } Object top = digester.pop(); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule]{" + digester.match + "} Pop " + top.getClass().getName()); } }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
Override public void finish() throws Exception { if (attributeName != null) { creationFactory = null; } }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
protected ObjectCreationFactory getFactory(Attributes attributes) throws Exception { if (creationFactory == null) { String realClassName = className; if (attributeName != null) { String value = attributes.getValue(attributeName); if (value != null) { realClassName = value; } } if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule]{" + digester.match + "} New factory " + realClassName); } Class<?> clazz = digester.getClassLoader().loadClass(realClassName); creationFactory = (ObjectCreationFactory) clazz.newInstance(); creationFactory.setDigester(digester); } return (creationFactory); }
// in java/org/apache/tomcat/util/digester/SetPropertiesRule.java
Override public void begin(String namespace, String theName, Attributes attributes) throws Exception { // Populate the corresponding properties of the top object Object top = digester.peek(); if (digester.log.isDebugEnabled()) { if (top != null) { digester.log.debug("[SetPropertiesRule]{" + digester.match + "} Set " + top.getClass().getName() + " properties"); } else { digester.log.debug("[SetPropertiesRule]{" + digester.match + "} Set NULL properties"); } } // set up variables for custom names mappings int attNamesLength = 0; if (attributeNames != null) { attNamesLength = attributeNames.length; } int propNamesLength = 0; if (propertyNames != null) { propNamesLength = propertyNames.length; } for (int i = 0; i < attributes.getLength(); i++) { String name = attributes.getLocalName(i); if ("".equals(name)) { name = attributes.getQName(i); } String value = attributes.getValue(i); // we'll now check for custom mappings for (int n = 0; n<attNamesLength; n++) { if (name.equals(attributeNames[n])) { if (n < propNamesLength) { // set this to value from list name = propertyNames[n]; } else { // set name to null // we'll check for this later name = null; } break; } } if (digester.log.isDebugEnabled()) { digester.log.debug("[SetPropertiesRule]{" + digester.match + "} Setting property '" + name + "' to '" + value + "'"); } if (!digester.isFakeAttribute(top, name) && !IntrospectionUtils.setProperty(top, name, value) && digester.getRulesValidation()) { digester.log.warn("[SetPropertiesRule]{" + digester.match + "} Setting property '" + name + "' to '" + value + "' did not find a matching property."); } } }
// in java/org/apache/tomcat/util/digester/CallMethodRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { // Push an array to capture the parameter values if necessary if (paramCount > 0) { Object parameters[] = new Object[paramCount]; for (int i = 0; i < parameters.length; i++) { parameters[i] = null; } digester.pushParams(parameters); } }
// in java/org/apache/tomcat/util/digester/CallMethodRule.java
Override public void body(String namespace, String name, String bodyText) throws Exception { if (paramCount == 0) { this.bodyText = bodyText.trim(); } }
// in java/org/apache/tomcat/util/digester/CallMethodRule.java
Override public void end(String namespace, String name) throws Exception { // Retrieve or construct the parameter values array Object parameters[] = null; if (paramCount > 0) { parameters = (Object[]) digester.popParams(); if (digester.log.isTraceEnabled()) { for (int i=0,size=parameters.length;i<size;i++) { digester.log.trace("[CallMethodRule](" + i + ")" + parameters[i]) ; } } // In the case where the parameter for the method // is taken from an attribute, and that attribute // isn't actually defined in the source XML file, // skip the method call if (paramCount == 1 && parameters[0] == null) { return; } } else if (paramTypes != null && paramTypes.length != 0) { // In the case where the parameter for the method // is taken from the body text, but there is no // body text included in the source XML file, // skip the method call if (bodyText == null) { return; } parameters = new Object[1]; parameters[0] = bodyText; if (paramTypes.length == 0) { paramTypes = new Class[1]; paramTypes[0] = "abc".getClass(); } } // Construct the parameter values array we will need // We only do the conversion if the param value is a String and // the specified paramType is not String. Object paramValues[] = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { // convert nulls and convert stringy parameters // for non-stringy param types if( parameters[i] == null || (parameters[i] instanceof String && !String.class.isAssignableFrom(paramTypes[i]))) { paramValues[i] = IntrospectionUtils.convert((String) parameters[i], paramTypes[i]); } else { paramValues[i] = parameters[i]; } } // Determine the target object for the method call Object target; if (targetOffset >= 0) { target = digester.peek(targetOffset); } else { target = digester.peek( digester.getCount() + targetOffset ); } if (target == null) { StringBuilder sb = new StringBuilder(); sb.append("[CallMethodRule]{"); sb.append(digester.match); sb.append("} Call target is null ("); sb.append("targetOffset="); sb.append(targetOffset); sb.append(",stackdepth="); sb.append(digester.getCount()); sb.append(")"); throw new org.xml.sax.SAXException(sb.toString()); } // Invoke the required method on the top object if (digester.log.isDebugEnabled()) { StringBuilder sb = new StringBuilder("[CallMethodRule]{"); sb.append(digester.match); sb.append("} Call "); sb.append(target.getClass().getName()); sb.append("."); sb.append(methodName); sb.append("("); for (int i = 0; i < paramValues.length; i++) { if (i > 0) { sb.append(","); } if (paramValues[i] == null) { sb.append("null"); } else { sb.append(paramValues[i].toString()); } sb.append("/"); if (paramTypes[i] == null) { sb.append("null"); } else { sb.append(paramTypes[i].getName()); } } sb.append(")"); digester.log.debug(sb.toString()); } Object result = IntrospectionUtils.callMethodN(target, methodName, paramValues, paramTypes); processMethodCallResult(result); }
// in java/org/apache/tomcat/util/digester/CallMethodRule.java
Override public void finish() throws Exception { bodyText = null; }
// in java/org/apache/tomcat/util/digester/SetTopRule.java
Override public void end(String namespace, String name) throws Exception { // Identify the objects to be used Object child = digester.peek(0); Object parent = digester.peek(1); if (digester.log.isDebugEnabled()) { if (child == null) { digester.log.debug("[SetTopRule]{" + digester.match + "} Call [NULL CHILD]." + methodName + "(" + parent + ")"); } else { digester.log.debug("[SetTopRule]{" + digester.match + "} Call " + child.getClass().getName() + "." + methodName + "(" + parent + ")"); } } // Call the specified method IntrospectionUtils.callMethod1(child, methodName, parent, paramType, digester.getClassLoader()); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void begin(String namespaceURI, String name, Attributes attributes) throws Exception { XMLReader xmlReader = getDigester().getXMLReader(); Document doc = documentBuilder.newDocument(); NodeBuilder builder = null; if (nodeType == Node.ELEMENT_NODE) { Element element = null; if (getDigester().getNamespaceAware()) { element = doc.createElementNS(namespaceURI, name); for (int i = 0; i < attributes.getLength(); i++) { element.setAttributeNS(attributes.getURI(i), attributes.getLocalName(i), attributes.getValue(i)); } } else { element = doc.createElement(name); for (int i = 0; i < attributes.getLength(); i++) { element.setAttribute(attributes.getQName(i), attributes.getValue(i)); } } builder = new NodeBuilder(doc, element); } else { builder = new NodeBuilder(doc, doc.createDocumentFragment()); } xmlReader.setContentHandler(builder); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void end(String namespace, String name) throws Exception { digester.pop(); }
// in java/org/apache/tomcat/util/digester/ObjectParamRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { Object anAttribute = null; Object parameters[] = (Object[]) digester.peekParams(); if (attributeName != null) { anAttribute = attributes.getValue(attributeName); if(anAttribute != null) { parameters[paramIndex] = param; } // note -- if attributeName != null and anAttribute == null, this rule // will pass null as its parameter! }else{ parameters[paramIndex] = param; } }
// in java/org/apache/tomcat/util/digester/SetRootRule.java
Override public void end(String namespace, String name) throws Exception { // Identify the objects to be used Object child = digester.peek(0); Object parent = digester.root; if (digester.log.isDebugEnabled()) { if (parent == null) { digester.log.debug("[SetRootRule]{" + digester.match + "} Call [NULL ROOT]." + methodName + "(" + child + ")"); } else { digester.log.debug("[SetRootRule]{" + digester.match + "} Call " + parent.getClass().getName() + "." + methodName + "(" + child + ")"); } } // Call the specified method IntrospectionUtils.callMethod1(parent, methodName, child, paramType, digester.getClassLoader()); }
// in java/org/apache/tomcat/util/digester/CallParamRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { Object param = null; if (attributeName != null) { param = attributes.getValue(attributeName); } else if(fromStack) { param = digester.peek(stackIndex); if (digester.log.isDebugEnabled()) { StringBuilder sb = new StringBuilder("[CallParamRule]{"); sb.append(digester.match); sb.append("} Save from stack; from stack?").append(fromStack); sb.append("; object=").append(param); digester.log.debug(sb.toString()); } } // Have to save the param object to the param stack frame here. // Can't wait until end(). Otherwise, the object will be lost. // We can't save the object as instance variables, as // the instance variables will be overwritten // if this CallParamRule is reused in subsequent nesting. if(param != null) { Object parameters[] = (Object[]) digester.peekParams(); parameters[paramIndex] = param; } }
// in java/org/apache/tomcat/util/digester/CallParamRule.java
Override public void body(String namespace, String name, String bodyText) throws Exception { if (attributeName == null && !fromStack) { // We must wait to set the parameter until end // so that we can make sure that the right set of parameters // is at the top of the stack if (bodyTextStack == null) { bodyTextStack = new ArrayStack<String>(); } bodyTextStack.push(bodyText.trim()); } }
// in java/org/apache/tomcat/util/digester/Rule.java
Deprecated public void begin(Attributes attributes) throws Exception { // The default implementation does nothing }
// in java/org/apache/tomcat/util/digester/Rule.java
public void begin(String namespace, String name, Attributes attributes) throws Exception { begin(attributes); }
// in java/org/apache/tomcat/util/digester/Rule.java
Deprecated public void body(String text) throws Exception { // The default implementation does nothing }
// in java/org/apache/tomcat/util/digester/Rule.java
public void body(String namespace, String name, String text) throws Exception { body(text); }
// in java/org/apache/tomcat/util/digester/Rule.java
Deprecated public void end() throws Exception { // The default implementation does nothing }
// in java/org/apache/tomcat/util/digester/Rule.java
public void end(String namespace, String name) throws Exception { end(); }
// in java/org/apache/tomcat/util/digester/Rule.java
public void finish() throws Exception { // The default implementation does nothing }
// in java/org/apache/tomcat/util/digester/SetNextRule.java
Override public void end(String namespace, String name) throws Exception { // Identify the objects to be used Object child = digester.peek(0); Object parent = digester.peek(1); if (digester.log.isDebugEnabled()) { if (parent == null) { digester.log.debug("[SetNextRule]{" + digester.match + "} Call [NULL PARENT]." + methodName + "(" + child + ")"); } else { digester.log.debug("[SetNextRule]{" + digester.match + "} Call " + parent.getClass().getName() + "." + methodName + "(" + child + ")"); } } // Call the specified method IntrospectionUtils.callMethod1(parent, methodName, child, paramType, digester.getClassLoader()); }
// in java/org/apache/tomcat/util/digester/PathCallParamRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { String param = getDigester().getMatch(); if(param != null) { Object parameters[] = (Object[]) digester.peekParams(); parameters[paramIndex] = param; } }
// in java/org/apache/el/parser/SimpleNode.java
Override public void accept(NodeVisitor visitor) throws Exception { visitor.visit(this); if (this.children != null && this.children.length > 0) { for (int i = 0; i < this.children.length; i++) { this.children[i].accept(visitor); } } }
// in java/org/apache/catalina/startup/ConnectorCreateRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { Service svc = (Service)digester.peek(); Executor ex = null; if ( attributes.getValue("executor")!=null ) { ex = svc.getExecutor(attributes.getValue("executor")); } Connector con = new Connector(attributes.getValue("protocol")); if ( ex != null ) _setExecutor(con,ex); digester.push(con); }
// in java/org/apache/catalina/startup/ConnectorCreateRule.java
public void _setExecutor(Connector con, Executor ex) throws Exception { Method m = IntrospectionUtils.findMethod(con.getProtocolHandler().getClass(),"setExecutor",new Class[] {java.util.concurrent.Executor.class}); if (m!=null) { m.invoke(con.getProtocolHandler(), new Object[] {ex}); }else { log.warn("Connector ["+con+"] does not support external executors. Method setExecutor(java.util.concurrent.Executor) not found."); } }
// in java/org/apache/catalina/startup/ConnectorCreateRule.java
Override public void end(String namespace, String name) throws Exception { digester.pop(); }
// in java/org/apache/catalina/startup/LifecycleListenerRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { Container c = (Container) digester.peek(); Container p = null; Object obj = digester.peek(1); if (obj instanceof Container) { p = (Container) obj; } String className = null; // Check the container for the specified attribute if (attributeName != null) { String value = attributes.getValue(attributeName); if (value != null) className = value; } // Check the container's parent for the specified attribute if (p != null && className == null) { String configClass = (String) IntrospectionUtils.getProperty(p, attributeName); if (configClass != null && configClass.length() > 0) { className = configClass; } } // Use the default if (className == null) { className = listenerClass; } // Instantiate a new LifecyleListener implementation object Class<?> clazz = Class.forName(className); LifecycleListener listener = (LifecycleListener) clazz.newInstance(); // Add this LifecycleListener to our associated component c.addLifecycleListener(listener); }
// in java/org/apache/catalina/startup/SetAllPropertiesRule.java
Override public void begin(String namespace, String nameX, Attributes attributes) throws Exception { for (int i = 0; i < attributes.getLength(); i++) { String name = attributes.getLocalName(i); if ("".equals(name)) { name = attributes.getQName(i); } String value = attributes.getValue(i); if ( !excludes.containsKey(name)) { if (!digester.isFakeAttribute(digester.peek(), name) && !IntrospectionUtils.setProperty(digester.peek(), name, value) && digester.getRulesValidation()) { digester.getLogger().warn("[SetAllPropertiesRule]{" + digester.getMatch() + "} Setting property '" + name + "' to '" + value + "' did not find a matching property."); } } } }
// in java/org/apache/catalina/startup/SetContextPropertiesRule.java
Override public void begin(String namespace, String nameX, Attributes attributes) throws Exception { for (int i = 0; i < attributes.getLength(); i++) { String name = attributes.getLocalName(i); if ("".equals(name)) { name = attributes.getQName(i); } if ("path".equals(name) || "docBase".equals(name)) { continue; } String value = attributes.getValue(i); if (!digester.isFakeAttribute(digester.peek(), name) && !IntrospectionUtils.setProperty(digester.peek(), name, value) && digester.getRulesValidation()) { digester.getLogger().warn("[SetContextPropertiesRule]{" + digester.getMatch() + "} Setting property '" + name + "' to '" + value + "' did not find a matching property."); } } }
// in java/org/apache/catalina/startup/ClassLoaderFactory.java
public static ClassLoader createClassLoader(File unpacked[], File packed[], final ClassLoader parent) throws Exception { if (log.isDebugEnabled()) log.debug("Creating new class loader"); // Construct the "class path" for this class loader Set<URL> set = new LinkedHashSet<URL>(); // Add unpacked directories if (unpacked != null) { for (int i = 0; i < unpacked.length; i++) { File file = unpacked[i]; if (!file.exists() || !file.canRead()) continue; file = new File(file.getCanonicalPath() + File.separator); URL url = file.toURI().toURL(); if (log.isDebugEnabled()) log.debug(" Including directory " + url); set.add(url); } } // Add packed directory JAR files if (packed != null) { for (int i = 0; i < packed.length; i++) { File directory = packed[i]; if (!directory.isDirectory() || !directory.exists() || !directory.canRead()) continue; String filenames[] = directory.list(); for (int j = 0; j < filenames.length; j++) { String filename = filenames[j].toLowerCase(Locale.ENGLISH); if (!filename.endsWith(".jar")) continue; File file = new File(directory, filenames[j]); if (log.isDebugEnabled()) log.debug(" Including jar file " + file.getAbsolutePath()); URL url = file.toURI().toURL(); set.add(url); } } } // Construct the class loader itself final URL[] array = set.toArray(new URL[set.size()]); return AccessController.doPrivileged( new PrivilegedAction<URLClassLoader>() { @Override public URLClassLoader run() { if (parent == null) return new URLClassLoader(array); else return new URLClassLoader(array, parent); } }); }
// in java/org/apache/catalina/startup/ClassLoaderFactory.java
public static ClassLoader createClassLoader(List<Repository> repositories, final ClassLoader parent) throws Exception { if (log.isDebugEnabled()) log.debug("Creating new class loader"); // Construct the "class path" for this class loader Set<URL> set = new LinkedHashSet<URL>(); if (repositories != null) { for (Repository repository : repositories) { if (repository.getType() == RepositoryType.URL) { URL url = new URL(repository.getLocation()); if (log.isDebugEnabled()) log.debug(" Including URL " + url); set.add(url); } else if (repository.getType() == RepositoryType.DIR) { File directory = new File(repository.getLocation()); directory = directory.getCanonicalFile(); if (!validateFile(directory, RepositoryType.DIR)) { continue; } URL url = directory.toURI().toURL(); if (log.isDebugEnabled()) log.debug(" Including directory " + url); set.add(url); } else if (repository.getType() == RepositoryType.JAR) { File file=new File(repository.getLocation()); file = file.getCanonicalFile(); if (!validateFile(file, RepositoryType.JAR)) { continue; } URL url = file.toURI().toURL(); if (log.isDebugEnabled()) log.debug(" Including jar file " + url); set.add(url); } else if (repository.getType() == RepositoryType.GLOB) { File directory=new File(repository.getLocation()); directory = directory.getCanonicalFile(); if (!validateFile(directory, RepositoryType.GLOB)) { continue; } if (log.isDebugEnabled()) log.debug(" Including directory glob " + directory.getAbsolutePath()); String filenames[] = directory.list(); for (int j = 0; j < filenames.length; j++) { String filename = filenames[j].toLowerCase(Locale.ENGLISH); if (!filename.endsWith(".jar")) continue; File file = new File(directory, filenames[j]); file = file.getCanonicalFile(); if (!validateFile(file, RepositoryType.JAR)) { continue; } if (log.isDebugEnabled()) log.debug(" Including glob jar file " + file.getAbsolutePath()); URL url = file.toURI().toURL(); set.add(url); } } } } // Construct the class loader itself final URL[] array = set.toArray(new URL[set.size()]); if (log.isDebugEnabled()) for (int i = 0; i < array.length; i++) { log.debug(" location " + i + " is " + array[i]); } return AccessController.doPrivileged( new PrivilegedAction<URLClassLoader>() { @Override public URLClassLoader run() { if (parent == null) return new URLClassLoader(array); else return new URLClassLoader(array, parent); } }); }
// in java/org/apache/catalina/startup/CopyParentClassLoaderRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (digester.getLogger().isDebugEnabled()) digester.getLogger().debug("Copying parent class loader"); Container child = (Container) digester.peek(0); Object parent = digester.peek(1); Method method = parent.getClass().getMethod("getParentClassLoader", new Class[0]); ClassLoader classLoader = (ClassLoader) method.invoke(parent, new Object[0]); child.setParentClassLoader(classLoader); }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isLoginConfigSet){ throw new IllegalArgumentException( "<login-config> element is limited to 1 occurrence"); } isLoginConfigSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isJspConfigSet){ throw new IllegalArgumentException( "<jsp-config> element is limited to 1 occurrence"); } isJspConfigSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isSessionConfigSet){ throw new IllegalArgumentException( "<session-config> element is limited to 1 occurrence"); } isSessionConfigSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { SecurityConstraint securityConstraint = (SecurityConstraint) digester.peek(); securityConstraint.setAuthConstraint(true); if (digester.getLogger().isDebugEnabled()) { digester.getLogger() .debug("Calling SecurityConstraint.setAuthConstraint(true)"); } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { WebXml webXml = (WebXml) digester.peek(); webXml.setDistributable(true); if (digester.getLogger().isDebugEnabled()) { digester.getLogger().debug (webXml.getClass().getName() + ".setDistributable(true)"); } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { Object top = digester.peek(); Class<?> paramClasses[] = new Class[1]; paramClasses[0] = "String".getClass(); String paramValues[] = new String[1]; paramValues[0] = digester.getPublicId(); Method m = null; try { m = top.getClass().getMethod(method, paramClasses); } catch (NoSuchMethodException e) { digester.getLogger().error("Can't find method " + method + " in " + top + " CLASS " + top.getClass()); return; } m.invoke(top, (Object [])paramValues); if (digester.getLogger().isDebugEnabled()) digester.getLogger().debug("" + top.getClass().getName() + "." + method + "(" + paramValues[0] + ")"); }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { ServletDef servletDef = new ServletDef(); digester.push(servletDef); if (digester.getLogger().isDebugEnabled()) digester.getLogger().debug("new " + servletDef.getClass().getName()); }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void end(String namespace, String name) throws Exception { ServletDef servletDef = (ServletDef) digester.pop(); if (digester.getLogger().isDebugEnabled()) digester.getLogger().debug("pop " + servletDef.getClass().getName()); }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void end(String namespace, String name) throws Exception { // Retrieve or construct the parameter values array Object parameters[] = null; if (paramCount > 0) { parameters = (Object[]) digester.popParams(); } else { parameters = new Object[0]; super.end(namespace, name); } ArrayList<?> multiParams = (ArrayList<?>) parameters[multiParamIndex]; // Construct the parameter values array we will need // We only do the conversion if the param value is a String and // the specified paramType is not String. Object paramValues[] = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { if (i != multiParamIndex) { // convert nulls and convert stringy parameters // for non-stringy param types if(parameters[i] == null || (parameters[i] instanceof String && !String.class.isAssignableFrom(paramTypes[i]))) { paramValues[i] = IntrospectionUtils.convert((String) parameters[i], paramTypes[i]); } else { paramValues[i] = parameters[i]; } } } // Determine the target object for the method call Object target; if (targetOffset >= 0) { target = digester.peek(targetOffset); } else { target = digester.peek(digester.getCount() + targetOffset); } if (target == null) { StringBuilder sb = new StringBuilder(); sb.append("[CallMethodRule]{"); sb.append(""); sb.append("} Call target is null ("); sb.append("targetOffset="); sb.append(targetOffset); sb.append(",stackdepth="); sb.append(digester.getCount()); sb.append(")"); throw new org.xml.sax.SAXException(sb.toString()); } if (multiParams == null) { paramValues[multiParamIndex] = null; IntrospectionUtils.callMethodN(target, methodName, paramValues, paramTypes); return; } for (int j = 0; j < multiParams.size(); j++) { Object param = multiParams.get(j); if(param == null || (param instanceof String && !String.class.isAssignableFrom(paramTypes[multiParamIndex]))) { paramValues[multiParamIndex] = IntrospectionUtils.convert((String) param, paramTypes[multiParamIndex]); } else { paramValues[multiParamIndex] = param; } IntrospectionUtils.callMethodN(target, methodName, paramValues, paramTypes); } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { WebXml webxml = (WebXml) digester.peek(digester.getCount() - 1); String value = attributes.getValue("metadata-complete"); if ("true".equals(value)) { webxml.setMetadataComplete(true); } else if ("false".equals(value)) { webxml.setMetadataComplete(false); } if (digester.getLogger().isDebugEnabled()) { digester.getLogger().debug (webxml.getClass().getName() + ".setMetadataComplete( " + webxml.isMetadataComplete() + ")"); } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { WebXml webxml = (WebXml) digester.peek(digester.getCount() - 1); webxml.setVersion(attributes.getValue("version")); if (digester.getLogger().isDebugEnabled()) { digester.getLogger().debug (webxml.getClass().getName() + ".setVersion( " + webxml.getVersion() + ")"); } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isNameSet){ throw new IllegalArgumentException(WebRuleSet.sm.getString( "webRuleSet.nameCount")); } isNameSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void body(String namespace, String name, String text) throws Exception { super.body(namespace, name, text); ((WebXml) digester.peek()).setName(text); }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (fragment) { digester.getLogger().warn( WebRuleSet.sm.getString("webRuleSet.absoluteOrdering")); } if (isAbsoluteOrderingSet) { throw new IllegalArgumentException(WebRuleSet.sm.getString( "webRuleSet.absoluteOrderingCount")); } else { isAbsoluteOrderingSet = true; } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (!fragment) { digester.getLogger().warn( WebRuleSet.sm.getString("webRuleSet.relativeOrdering")); } if (isRelativeOrderingSet) { throw new IllegalArgumentException(WebRuleSet.sm.getString( "webRuleSet.relativeOrderingCount")); } else { isRelativeOrderingSet = true; } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void body(String namespace, String name, String text) throws Exception { String namespaceuri = null; String localpart = text; int colon = text.indexOf(':'); if (colon >= 0) { String prefix = text.substring(0,colon); namespaceuri = digester.findNamespaceURI(prefix); localpart = text.substring(colon+1); } ContextHandler contextHandler = (ContextHandler)digester.peek(); contextHandler.addSoapHeaders(localpart,namespaceuri); }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void body(String namespace, String name, String text) throws Exception { String namespaceuri = null; String localpart = text; int colon = text.indexOf(':'); if (colon >= 0) { String prefix = text.substring(0,colon); namespaceuri = digester.findNamespaceURI(prefix); localpart = text.substring(colon+1); } ContextService contextService = (ContextService)digester.peek(); contextService.setServiceqnameLocalpart(localpart); contextService.setServiceqnameNamespaceURI(namespaceuri); }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { WebXml webXml = (WebXml) digester.peek(digester.getCount() - 1); // If we have a public ID, this is not a 2.4 or later webapp boolean havePublicId = (webXml.getPublicId() != null); // havePublicId and isServlet24OrLater should be mutually exclusive if (havePublicId == isServlet24OrLater) { throw new IllegalArgumentException( "taglib definition not consistent with specification version"); } }
// in java/org/apache/catalina/startup/Catalina.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (digester.getLogger().isDebugEnabled()) { digester.getLogger().debug("Setting parent class loader"); } Container top = (Container) digester.peek(); top.setParentClassLoader(parentClassLoader); }
// in java/org/apache/catalina/startup/SetNextNamingRule.java
Override public void end(String namespace, String name) throws Exception { // Identify the objects to be used Object child = digester.peek(0); Object parent = digester.peek(1); NamingResources namingResources = null; if (parent instanceof Context) { namingResources = ((Context) parent).getNamingResources(); } else { namingResources = (NamingResources) parent; } // Call the specified method IntrospectionUtils.callMethod1(namingResources, methodName, child, paramType, digester.getClassLoader()); }
// in java/org/apache/catalina/startup/Bootstrap.java
private ClassLoader createClassLoader(String name, ClassLoader parent) throws Exception { String value = CatalinaProperties.getProperty(name + ".loader"); if ((value == null) || (value.equals(""))) return parent; value = replace(value); List<Repository> repositories = new ArrayList<Repository>(); StringTokenizer tokenizer = new StringTokenizer(value, ","); while (tokenizer.hasMoreElements()) { String repository = tokenizer.nextToken().trim(); if (repository.length() == 0) { continue; } // Check for a JAR URL repository try { @SuppressWarnings("unused") URL url = new URL(repository); repositories.add( new Repository(repository, RepositoryType.URL)); continue; } catch (MalformedURLException e) { // Ignore } // Local repository if (repository.endsWith("*.jar")) { repository = repository.substring (0, repository.length() - "*.jar".length()); repositories.add( new Repository(repository, RepositoryType.GLOB)); } else if (repository.endsWith(".jar")) { repositories.add( new Repository(repository, RepositoryType.JAR)); } else { repositories.add( new Repository(repository, RepositoryType.DIR)); } } return ClassLoaderFactory.createClassLoader(repositories, parent); }
// in java/org/apache/catalina/startup/Bootstrap.java
public void init() throws Exception { initClassLoaders(); Thread.currentThread().setContextClassLoader(catalinaLoader); SecurityClassLoad.securityClassLoad(catalinaLoader); // Load our startup class and call its process() method if (log.isDebugEnabled()) log.debug("Loading startup class"); Class<?> startupClass = catalinaLoader.loadClass ("org.apache.catalina.startup.Catalina"); Object startupInstance = startupClass.newInstance(); // Set the shared extensions class loader if (log.isDebugEnabled()) log.debug("Setting startup class properties"); String methodName = "setParentClassLoader"; Class<?> paramTypes[] = new Class[1]; paramTypes[0] = Class.forName("java.lang.ClassLoader"); Object paramValues[] = new Object[1]; paramValues[0] = sharedLoader; Method method = startupInstance.getClass().getMethod(methodName, paramTypes); method.invoke(startupInstance, paramValues); catalinaDaemon = startupInstance; }
// in java/org/apache/catalina/startup/Bootstrap.java
private void load(String[] arguments) throws Exception { // Call the load() method String methodName = "load"; Object param[]; Class<?> paramTypes[]; if (arguments==null || arguments.length==0) { paramTypes = null; param = null; } else { paramTypes = new Class[1]; paramTypes[0] = arguments.getClass(); param = new Object[1]; param[0] = arguments; } Method method = catalinaDaemon.getClass().getMethod(methodName, paramTypes); if (log.isDebugEnabled()) log.debug("Calling startup class " + method); method.invoke(catalinaDaemon, param); }
// in java/org/apache/catalina/startup/Bootstrap.java
private Object getServer() throws Exception { String methodName = "getServer"; Method method = catalinaDaemon.getClass().getMethod(methodName); return method.invoke(catalinaDaemon); }
// in java/org/apache/catalina/startup/Bootstrap.java
public void init(String[] arguments) throws Exception { init(); load(arguments); }
// in java/org/apache/catalina/startup/Bootstrap.java
public void start() throws Exception { if( catalinaDaemon==null ) init(); Method method = catalinaDaemon.getClass().getMethod("start", (Class [] )null); method.invoke(catalinaDaemon, (Object [])null); }
// in java/org/apache/catalina/startup/Bootstrap.java
public void stop() throws Exception { Method method = catalinaDaemon.getClass().getMethod("stop", (Class [] ) null); method.invoke(catalinaDaemon, (Object [] ) null); }
// in java/org/apache/catalina/startup/Bootstrap.java
public void stopServer() throws Exception { Method method = catalinaDaemon.getClass().getMethod("stopServer", (Class []) null); method.invoke(catalinaDaemon, (Object []) null); }
// in java/org/apache/catalina/startup/Bootstrap.java
public void stopServer(String[] arguments) throws Exception { Object param[]; Class<?> paramTypes[]; if (arguments==null || arguments.length==0) { paramTypes = null; param = null; } else { paramTypes = new Class[1]; paramTypes[0] = arguments.getClass(); param = new Object[1]; param[0] = arguments; } Method method = catalinaDaemon.getClass().getMethod("stopServer", paramTypes); method.invoke(catalinaDaemon, param); }
// in java/org/apache/catalina/startup/Bootstrap.java
public void setAwait(boolean await) throws Exception { Class<?> paramTypes[] = new Class[1]; paramTypes[0] = Boolean.TYPE; Object paramValues[] = new Object[1]; paramValues[0] = Boolean.valueOf(await); Method method = catalinaDaemon.getClass().getMethod("setAwait", paramTypes); method.invoke(catalinaDaemon, paramValues); }
// in java/org/apache/catalina/startup/Bootstrap.java
public boolean getAwait() throws Exception { Class<?> paramTypes[] = new Class[0]; Object paramValues[] = new Object[0]; Method method = catalinaDaemon.getClass().getMethod("getAwait", paramTypes); Boolean b=(Boolean)method.invoke(catalinaDaemon, paramValues); return b.booleanValue(); }
// in java/org/apache/catalina/startup/TldRuleSet.java
Override public void body(String namespace, String name, String text) throws Exception { taglibUriRule.setDuplicateUri(false); }
// in java/org/apache/catalina/startup/TldRuleSet.java
Override public void body(String namespace, String name, String text) throws Exception { TldConfig tldConfig = (TldConfig) digester.peek(digester.getCount() - 1); if (tldConfig.isKnownTaglibUri(text)) { // Already seen this URI duplicateUri = true; // This is expected if the URI was defined in web.xml // Log message at debug in this case if (tldConfig.isKnownWebxmlTaglibUri(text)) { if (digester.getLogger().isDebugEnabled()) { digester.getLogger().debug( "TLD skipped. URI: " + text + " is already defined"); } } else { digester.getLogger().info( "TLD skipped. URI: " + text + " is already defined"); } } else { // New URI. Add it to known list and carry on tldConfig.addTaglibUri(text); } }
// in java/org/apache/catalina/startup/TldRuleSet.java
Override public void body(String namespace, String name, String text) throws Exception { TldConfig tldConfig = (TldConfig) digester.peek(digester.getCount() - 1); // Only process the listener if the URI is not a duplicate if (!taglibUriRule.isDuplicateUri()) { tldConfig.addApplicationListener(text.trim()); } }
// in java/org/apache/catalina/loader/WebappLoader.java
private WebappClassLoader createClassLoader() throws Exception { Class<?> clazz = Class.forName(loaderClass); WebappClassLoader classLoader = null; if (parentClassLoader == null) { parentClassLoader = container.getParentClassLoader(); } Class<?>[] argTypes = { ClassLoader.class }; Object[] args = { parentClassLoader }; Constructor<?> constr = clazz.getConstructor(argTypes); classLoader = (WebappClassLoader) constr.newInstance(args); return classLoader; }
// in java/org/apache/catalina/realm/MemoryRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { String username = attributes.getValue("name"); if (username == null) { username = attributes.getValue("username"); } String password = attributes.getValue("password"); String roles = attributes.getValue("roles"); MemoryRealm realm = (MemoryRealm) digester.peek(digester.getCount() - 1); realm.addUser(username, password, roles); }
// in java/org/apache/catalina/realm/GenericPrincipal.java
Override public void logout() throws Exception { if (loginContext != null) { loginContext.logout(); } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
private Container getParentContainerFromParent(ObjectName pname) throws Exception { String type = pname.getKeyProperty("type"); String j2eeType = pname.getKeyProperty("j2eeType"); Service service = getService(pname); StandardEngine engine = (StandardEngine) service.getContainer(); if ((j2eeType!=null) && (j2eeType.equals("WebModule"))) { String name = pname.getKeyProperty("name"); name = name.substring(2); int i = name.indexOf("/"); String hostName = name.substring(0,i); String path = name.substring(i); Container host = engine.findChild(hostName); String pathStr = getPathStr(path); Container context = host.findChild(pathStr); return context; } else if (type != null) { if (type.equals("Engine")) { return engine; } else if (type.equals("Host")) { String hostName = pname.getKeyProperty("host"); Container host = engine.findChild(hostName); return host; } } return null; }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
private Container getParentContainerFromChild(ObjectName oname) throws Exception { String hostName = oname.getKeyProperty("host"); String path = oname.getKeyProperty("path"); Service service = getService(oname); Container engine = service.getContainer(); if (hostName == null) { // child's container is Engine return engine; } else if (path == null) { // child's container is Host Container host = engine.findChild(hostName); return host; } else { // child's container is Context Container host = engine.findChild(hostName); path = getPathStr(path); Container context = host.findChild(path); return context; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
private Service getService(ObjectName oname) throws Exception { if (container instanceof Service) { // Don't bother checking the domain - this is the only option return (Service) container; } StandardService service = null; String domain = oname.getDomain(); if (container instanceof Server) { Service[] services = ((Server)container).findServices(); for (int i = 0; i < services.length; i++) { service = (StandardService) services[i]; if (domain.equals(service.getObjectName().getDomain())) { break; } } } if (service == null || !service.getObjectName().getDomain().equals(domain)) { throw new Exception("Service with the domain is not found"); } return service; }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createAjpConnector(String parent, String address, int port) throws Exception { return createConnector(parent, address, port, true, false); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createDataSourceRealm(String parent, String dataSourceName, String roleNameCol, String userCredCol, String userNameCol, String userRoleTable, String userTable) throws Exception { // Create a new DataSourceRealm instance DataSourceRealm realm = new DataSourceRealm(); realm.setDataSourceName(dataSourceName); realm.setRoleNameCol(roleNameCol); realm.setUserCredCol(userCredCol); realm.setUserNameCol(userNameCol); realm.setUserRoleTable(userRoleTable); realm.setUserTable(userTable); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); // Add the new instance to its parent component container.setRealm(realm); // Return the corresponding MBean name ObjectName oname = realm.getObjectName(); if (oname != null) { return (oname.toString()); } else { return null; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createHttpConnector(String parent, String address, int port) throws Exception { return createConnector(parent, address, port, false, false); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
private String createConnector(String parent, String address, int port, boolean isAjp, boolean isSSL) throws Exception { Connector retobj = new Connector(); if ((address!=null) && (address.length()>0)) { retobj.setProperty("address", address); } // Set port number retobj.setPort(port); // Set the protocol retobj.setProtocol(isAjp ? "AJP/1.3" : "HTTP/1.1"); // Set SSL retobj.setSecure(isSSL); retobj.setScheme(isSSL ? "https" : "http"); // Add the new instance to its parent component // FIX ME - addConnector will fail ObjectName pname = new ObjectName(parent); Service service = getService(pname); service.addConnector(retobj); // Return the corresponding MBean name ObjectName coname = retobj.getObjectName(); return (coname.toString()); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createHttpsConnector(String parent, String address, int port) throws Exception { return createConnector(parent, address, port, false, true); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createJDBCRealm(String parent, String driverName, String connectionName, String connectionPassword, String connectionURL) throws Exception { // Create a new JDBCRealm instance JDBCRealm realm = new JDBCRealm(); realm.setDriverName(driverName); realm.setConnectionName(connectionName); realm.setConnectionPassword(connectionPassword); realm.setConnectionURL(connectionURL); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); // Add the new instance to its parent component container.setRealm(realm); // Return the corresponding MBean name ObjectName oname = realm.getObjectName(); if (oname != null) { return (oname.toString()); } else { return null; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createJNDIRealm(String parent) throws Exception { // Create a new JNDIRealm instance JNDIRealm realm = new JNDIRealm(); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); // Add the new instance to its parent component container.setRealm(realm); // Return the corresponding MBean name ObjectName oname = realm.getObjectName(); if (oname != null) { return (oname.toString()); } else { return null; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createMemoryRealm(String parent) throws Exception { // Create a new MemoryRealm instance MemoryRealm realm = new MemoryRealm(); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); // Add the new instance to its parent component container.setRealm(realm); // Return the corresponding MBean name ObjectName oname = realm.getObjectName(); if (oname != null) { return (oname.toString()); } else { return null; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createStandardContext(String parent, String path, String docBase) throws Exception { return createStandardContext(parent, path, docBase, false, false, false, false); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createStandardContext(String parent, String path, String docBase, boolean xmlValidation, boolean xmlNamespaceAware, boolean tldValidation, boolean tldNamespaceAware) throws Exception { // Create a new StandardContext instance StandardContext context = new StandardContext(); path = getPathStr(path); context.setPath(path); context.setDocBase(docBase); context.setXmlValidation(xmlValidation); context.setXmlNamespaceAware(xmlNamespaceAware); context.setTldValidation(tldValidation); context.setTldNamespaceAware(tldNamespaceAware); ContextConfig contextConfig = new ContextConfig(); context.addLifecycleListener(contextConfig); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); ObjectName deployer = new ObjectName(pname.getDomain()+ ":type=Deployer,host="+ pname.getKeyProperty("host")); if(mserver.isRegistered(deployer)) { String contextName = context.getName(); mserver.invoke(deployer, "addServiced", new Object [] {contextName}, new String [] {"java.lang.String"}); String configPath = (String)mserver.getAttribute(deployer, "configBaseName"); String baseName = context.getBaseName(); File configFile = new File(new File(configPath), baseName+".xml"); if (configFile.isFile()) { context.setConfigFile(configFile.toURI().toURL()); } mserver.invoke(deployer, "manageApp", new Object[] {context}, new String[] {"org.apache.catalina.Context"}); mserver.invoke(deployer, "removeServiced", new Object [] {contextName}, new String [] {"java.lang.String"}); } else { log.warn("Deployer not found for "+pname.getKeyProperty("host")); Service service = getService(pname); Engine engine = (Engine) service.getContainer(); Host host = (Host) engine.findChild(pname.getKeyProperty("host")); host.addChild(context); } // Return the corresponding MBean name return context.getObjectName().toString(); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createStandardHost(String parent, String name, String appBase, boolean autoDeploy, boolean deployOnStartup, boolean deployXML, boolean unpackWARs) throws Exception { // Create a new StandardHost instance StandardHost host = new StandardHost(); host.setName(name); host.setAppBase(appBase); host.setAutoDeploy(autoDeploy); host.setDeployOnStartup(deployOnStartup); host.setDeployXML(deployXML); host.setUnpackWARs(unpackWARs); // add HostConfig for active reloading HostConfig hostConfig = new HostConfig(); host.addLifecycleListener(hostConfig); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Service service = getService(pname); Engine engine = (Engine) service.getContainer(); engine.addChild(host); // Return the corresponding MBean name return (host.getObjectName().toString()); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createStandardServiceEngine(String domain, String defaultHost, String baseDir) throws Exception{ if (!(container instanceof Server)) { throw new Exception("Container not Server"); } StandardEngine engine = new StandardEngine(); engine.setDomain(domain); engine.setName(domain); engine.setDefaultHost(defaultHost); Service service = new StandardService(); service.setContainer(engine); service.setName(domain); ((Server) container).addService(service); return engine.getObjectName().toString(); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createStandardManager(String parent) throws Exception { // Create a new StandardManager instance StandardManager manager = new StandardManager(); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); if (container != null) { container.setManager(manager); } ObjectName oname = manager.getObjectName(); if (oname != null) { return (oname.toString()); } else { return null; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createUserDatabaseRealm(String parent, String resourceName) throws Exception { // Create a new UserDatabaseRealm instance UserDatabaseRealm realm = new UserDatabaseRealm(); realm.setResourceName(resourceName); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); // Add the new instance to its parent component container.setRealm(realm); // Return the corresponding MBean name ObjectName oname = realm.getObjectName(); // FIXME getObjectName() returns null //ObjectName oname = // MBeanUtils.createObjectName(pname.getDomain(), realm); if (oname != null) { return (oname.toString()); } else { return null; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createValve(String className, String parent) throws Exception { // Look for the parent ObjectName parentName = new ObjectName(parent); Container container = getParentContainerFromParent(parentName); if (container == null) { // TODO throw new IllegalArgumentException(); } Valve valve = (Valve) Class.forName(className).newInstance(); container.getPipeline().addValve(valve); if (valve instanceof JmxEnabled) { return ((JmxEnabled) valve).getObjectName().toString(); } else { return null; } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createWebappLoader(String parent) throws Exception { // Create a new WebappLoader instance WebappLoader loader = new WebappLoader(); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); if (container != null) { container.setLoader(loader); } // FIXME add Loader.getObjectName //ObjectName oname = loader.getObjectName(); ObjectName oname = MBeanUtils.createObjectName(pname.getDomain(), loader); return (oname.toString()); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeConnector(String name) throws Exception { // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(name); Service service = getService(oname); String port = oname.getKeyProperty("port"); //String address = oname.getKeyProperty("address"); Connector conns[] = service.findConnectors(); for (int i = 0; i < conns.length; i++) { String connAddress = String.valueOf(conns[i].getProperty("address")); String connPort = ""+conns[i].getPort(); // if (((address.equals("null")) && if ((connAddress==null) && port.equals(connPort)) { service.removeConnector(conns[i]); conns[i].destroy(); break; } // } else if (address.equals(connAddress)) if (port.equals(connPort)) { // Remove this component from its parent component service.removeConnector(conns[i]); conns[i].destroy(); break; } } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeContext(String contextName) throws Exception { // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(contextName); String domain = oname.getDomain(); StandardService service = (StandardService) getService(oname); Engine engine = (Engine) service.getContainer(); String name = oname.getKeyProperty("name"); name = name.substring(2); int i = name.indexOf("/"); String hostName = name.substring(0,i); String path = name.substring(i); ObjectName deployer = new ObjectName(domain+":type=Deployer,host="+ hostName); String pathStr = getPathStr(path); if(mserver.isRegistered(deployer)) { mserver.invoke(deployer,"addServiced", new Object[]{pathStr}, new String[] {"java.lang.String"}); mserver.invoke(deployer,"unmanageApp", new Object[] {pathStr}, new String[] {"java.lang.String"}); mserver.invoke(deployer,"removeServiced", new Object[] {pathStr}, new String[] {"java.lang.String"}); } else { log.warn("Deployer not found for "+hostName); Host host = (Host) engine.findChild(hostName); Context context = (Context) host.findChild(pathStr); // Remove this component from its parent component host.removeChild(context); if(context instanceof StandardContext) try { ((StandardContext)context).destroy(); } catch (Exception e) { log.warn("Error during context [" + context.getName() + "] destroy ", e); } } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeHost(String name) throws Exception { // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(name); String hostName = oname.getKeyProperty("host"); Service service = getService(oname); Engine engine = (Engine) service.getContainer(); Host host = (Host) engine.findChild(hostName); // Remove this component from its parent component if(host!=null) { engine.removeChild(host); } }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeLoader(String name) throws Exception { ObjectName oname = new ObjectName(name); // Acquire a reference to the component to be removed Container container = getParentContainerFromChild(oname); container.setLoader(null); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeManager(String name) throws Exception { ObjectName oname = new ObjectName(name); // Acquire a reference to the component to be removed Container container = getParentContainerFromChild(oname); container.setManager(null); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeRealm(String name) throws Exception { ObjectName oname = new ObjectName(name); // Acquire a reference to the component to be removed Container container = getParentContainerFromChild(oname); container.setRealm(null); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeService(String name) throws Exception { if (!(container instanceof Server)) { throw new Exception(); } // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(name); Service service = getService(oname); ((Server) container).removeService(service); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public void removeValve(String name) throws Exception { // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(name); Container container = getParentContainerFromChild(oname); Valve[] valves = container.getPipeline().getValves(); for (int i = 0; i < valves.length; i++) { ObjectName voname = ((JmxEnabled) valves[i]).getObjectName(); if (voname.equals(oname)) { container.getPipeline().removeValve(valves[i]); } } }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
protected void createMBeans(String name, UserDatabase database) throws Exception { // Create the MBean for the UserDatabase itself if (log.isDebugEnabled()) { log.debug("Creating UserDatabase MBeans for resource " + name); log.debug("Database=" + database); } if (MBeanUtils.createMBean(database) == null) { throw new IllegalArgumentException ("Cannot create UserDatabase MBean for resource " + name); } // Create the MBeans for each defined Role Iterator<Role> roles = database.getRoles(); while (roles.hasNext()) { Role role = roles.next(); if (log.isDebugEnabled()) { log.debug(" Creating Role MBean for role " + role); } if (MBeanUtils.createMBean(role) == null) { throw new IllegalArgumentException ("Cannot create Role MBean for role " + role); } } // Create the MBeans for each defined Group Iterator<Group> groups = database.getGroups(); while (groups.hasNext()) { Group group = groups.next(); if (log.isDebugEnabled()) { log.debug(" Creating Group MBean for group " + group); } if (MBeanUtils.createMBean(group) == null) { throw new IllegalArgumentException ("Cannot create Group MBean for group " + group); } } // Create the MBeans for each defined User Iterator<User> users = database.getUsers(); while (users.hasNext()) { User user = users.next(); if (log.isDebugEnabled()) { log.debug(" Creating User MBean for user " + user); } if (MBeanUtils.createMBean(user) == null) { throw new IllegalArgumentException ("Cannot create User MBean for user " + user); } } }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static DynamicMBean createMBean(ContextEnvironment environment) throws Exception { String mname = createManagedName(environment); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(environment); ObjectName oname = createObjectName(domain, environment); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static DynamicMBean createMBean(ContextResource resource) throws Exception { String mname = createManagedName(resource); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(resource); ObjectName oname = createObjectName(domain, resource); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static DynamicMBean createMBean(ContextResourceLink resourceLink) throws Exception { String mname = createManagedName(resourceLink); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(resourceLink); ObjectName oname = createObjectName(domain, resourceLink); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(Group group) throws Exception { String mname = createManagedName(group); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(group); ObjectName oname = createObjectName(domain, group); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(Role role) throws Exception { String mname = createManagedName(role); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(role); ObjectName oname = createObjectName(domain, role); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(User user) throws Exception { String mname = createManagedName(user); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(user); ObjectName oname = createObjectName(domain, user); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(UserDatabase userDatabase) throws Exception { String mname = createManagedName(userDatabase); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(userDatabase); ObjectName oname = createObjectName(domain, userDatabase); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static void destroyMBean(ContextEnvironment environment) throws Exception { String mname = createManagedName(environment); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, environment); if( mserver.isRegistered(oname) ) mserver.unregisterMBean(oname); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static void destroyMBean(ContextResource resource) throws Exception { // If this is a user database resource need to destroy groups, roles, // users and UserDatabase mbean if ("org.apache.catalina.UserDatabase".equals(resource.getType())) { destroyMBeanUserDatabase(resource.getName()); } String mname = createManagedName(resource); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, resource); if( mserver.isRegistered(oname )) mserver.unregisterMBean(oname); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static void destroyMBean(ContextResourceLink resourceLink) throws Exception { String mname = createManagedName(resourceLink); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, resourceLink); if( mserver.isRegistered(oname) ) mserver.unregisterMBean(oname); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static void destroyMBean(Group group) throws Exception { String mname = createManagedName(group); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, group); if( mserver.isRegistered(oname) ) mserver.unregisterMBean(oname); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static void destroyMBean(Role role) throws Exception { String mname = createManagedName(role); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, role); if( mserver.isRegistered(oname) ) mserver.unregisterMBean(oname); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static void destroyMBean(User user) throws Exception { String mname = createManagedName(user); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, user); if( mserver.isRegistered(oname) ) mserver.unregisterMBean(oname); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static void destroyMBeanUserDatabase(String userDatabase) throws Exception { ObjectName query = null; Set<ObjectName> results = null; // Groups query = new ObjectName( "Users:type=Group,database=" + userDatabase + ",*"); results = mserver.queryNames(query, null); for(ObjectName result : results) { mserver.unregisterMBean(result); } // Roles query = new ObjectName( "Users:type=Role,database=" + userDatabase + ",*"); results = mserver.queryNames(query, null); for(ObjectName result : results) { mserver.unregisterMBean(result); } // Users query = new ObjectName( "Users:type=User,database=" + userDatabase + ",*"); results = mserver.queryNames(query, null); for(ObjectName result : results) { mserver.unregisterMBean(result); } // The database itself ObjectName db = new ObjectName( "Users:type=UserDatabase,database=" + userDatabase); mserver.unregisterMBean(db); }
// in java/org/apache/catalina/users/MemoryUserDatabaseFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { // We only know how to deal with <code>javax.naming.Reference</code>s // that specify a class name of "org.apache.catalina.UserDatabase" if ((obj == null) || !(obj instanceof Reference)) { return (null); } Reference ref = (Reference) obj; if (!"org.apache.catalina.UserDatabase".equals(ref.getClassName())) { return (null); } // Create and configure a MemoryUserDatabase instance based on the // RefAddr values associated with this Reference MemoryUserDatabase database = new MemoryUserDatabase(name.toString()); RefAddr ra = null; ra = ref.get("pathname"); if (ra != null) { database.setPathname(ra.getContent().toString()); } ra = ref.get("readonly"); if (ra != null) { database.setReadonly(Boolean.valueOf(ra.getContent().toString()).booleanValue()); } // Return the configured database instance database.open(); // Don't try something we know won't work if (!database.getReadonly()) database.save(); return (database); }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
Override public void close() throws Exception { save(); synchronized (groups) { synchronized (users) { users.clear(); groups.clear(); } } }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
Override public void open() throws Exception { synchronized (groups) { synchronized (users) { // Erase any previous groups and users users.clear(); groups.clear(); roles.clear(); // Construct a reader for the XML input file (if it exists) File file = new File(pathname); if (!file.isAbsolute()) { file = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathname); } if (!file.exists()) { return; } // Construct a digester to read the XML input file Digester digester = new Digester(); try { digester.setFeature( "http://apache.org/xml/features/allow-java-encodings", true); } catch (Exception e) { log.warn(sm.getString("memoryUserDatabase.xmlFeatureEncoding"), e); } digester.addFactoryCreate ("tomcat-users/group", new MemoryGroupCreationFactory(this), true); digester.addFactoryCreate ("tomcat-users/role", new MemoryRoleCreationFactory(this), true); digester.addFactoryCreate ("tomcat-users/user", new MemoryUserCreationFactory(this), true); // Parse the XML input file to load this database FileInputStream fis = null; try { fis = new FileInputStream(file); digester.parse(fis); } finally { if (fis != null) { try { fis.close(); } catch (IOException ioe) { // Ignore } } } } } }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
Override public void save() throws Exception { if (getReadonly()) { log.error(sm.getString("memoryUserDatabase.readOnly")); return; } if (!isWriteable()) { log.warn(sm.getString("memoryUserDatabase.notPersistable")); return; } // Write out contents to a temporary file File fileNew = new File(pathnameNew); if (!fileNew.isAbsolute()) { fileNew = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathnameNew); } PrintWriter writer = null; try { // Configure our PrintWriter FileOutputStream fos = new FileOutputStream(fileNew); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF8"); writer = new PrintWriter(osw); // Print the file prolog writer.println("<?xml version='1.0' encoding='utf-8'?>"); writer.println("<tomcat-users>"); // Print entries for each defined role, group, and user Iterator<?> values = null; values = getRoles(); while (values.hasNext()) { writer.print(" "); writer.println(values.next()); } values = getGroups(); while (values.hasNext()) { writer.print(" "); writer.println(values.next()); } values = getUsers(); while (values.hasNext()) { writer.print(" "); writer.println(((MemoryUser) values.next()).toXml()); } // Print the file epilog writer.println("</tomcat-users>"); // Check for errors that occurred while printing if (writer.checkError()) { writer.close(); fileNew.delete(); throw new IOException (sm.getString("memoryUserDatabase.writeException", fileNew.getAbsolutePath())); } writer.close(); } catch (IOException e) { if (writer != null) { writer.close(); } fileNew.delete(); throw e; } // Perform the required renames to permanently save this file File fileOld = new File(pathnameOld); if (!fileOld.isAbsolute()) { fileOld = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathnameOld); } fileOld.delete(); File fileOrig = new File(pathname); if (!fileOrig.isAbsolute()) { fileOrig = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathname); } if (fileOrig.exists()) { fileOld.delete(); if (!fileOrig.renameTo(fileOld)) { throw new IOException (sm.getString("memoryUserDatabase.renameOld", fileOld.getAbsolutePath())); } } if (!fileNew.renameTo(fileOrig)) { if (fileOld.exists()) { fileOld.renameTo(fileOrig); } throw new IOException (sm.getString("memoryUserDatabase.renameNew", fileOrig.getAbsolutePath())); } fileOld.delete(); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if ((jmxServerConnection == null)) { throw new BuildException("Must open a connection!"); } else if (isEcho()) { handleOutput("JMX Connection ref=" + ref + " is open!"); } return null; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorSetTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((attribute == null || value == null)) { throw new BuildException( "Must specify a 'attribute' and 'value' for set"); } return jmxSet(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorSetTask.java
protected String jmxSet(MBeanServerConnection jmxServerConnection, String name) throws Exception { Object realValue; if (type != null) { realValue = convertStringToType(value, type); } else { if (isConvert()) { String mType = getMBeanAttributeType(jmxServerConnection, name, attribute); realValue = convertStringToType(value, mType); } else realValue = value; } jmxServerConnection.setAttribute(new ObjectName(name), new Attribute( attribute, realValue)); return null; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorSetTask.java
protected String getMBeanAttributeType( MBeanServerConnection jmxServerConnection, String name, String attribute) throws Exception { ObjectName oname = new ObjectName(name); String mattrType = null; MBeanInfo minfo = jmxServerConnection.getMBeanInfo(oname); MBeanAttributeInfo attrs[] = minfo.getAttributes(); if (attrs != null) { for (int i = 0; mattrType == null && i < attrs.length; i++) { if (attribute.equals(attrs[i].getName())) mattrType = attrs[i].getType(); } } return mattrType; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorGetTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((attribute == null)) { throw new BuildException( "Must specify a 'attribute' for get"); } return jmxGet(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorGetTask.java
protected String jmxGet(MBeanServerConnection jmxServerConnection,String name) throws Exception { String error = null; if(isEcho()) { handleOutput("MBean " + name + " get attribute " + attribute ); } Object result = jmxServerConnection.getAttribute( new ObjectName(name), attribute); if (result != null) { echoResult(attribute,result); createProperty(result); } else error = "Attribute " + attribute + " is empty"; return error; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } return jmxQuery(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorUnregisterTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } return jmxUuregister(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorUnregisterTask.java
protected String jmxUuregister(MBeanServerConnection jmxServerConnection,String name) throws Exception { String error = null; if(isEcho()) { handleOutput("Unregister MBean " + name ); } jmxServerConnection.unregisterMBean( new ObjectName(name)); return error; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorCreateTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((className == null)) { throw new BuildException( "Must specify a 'className' for get"); } return jmxCreate(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorCreateTask.java
protected String jmxCreate(MBeanServerConnection jmxServerConnection, String name) throws Exception { String error = null; Object argsA[] = null; String sigA[] = null; if (args != null) { argsA = new Object[ args.size()]; sigA = new String[args.size()]; for( int i=0; i<args.size(); i++ ) { Arg arg=args.get(i); if( arg.type==null) { arg.type="java.lang.String"; sigA[i]=arg.getType(); argsA[i]=arg.getValue(); } else { sigA[i]=arg.getType(); argsA[i]=convertStringToType(arg.getValue(),arg.getType()); } } } if (classLoader != null && !"".equals(classLoader)) { if (isEcho()) { handleOutput("create MBean " + name + " from class " + className + " with classLoader " + classLoader); } if(args == null) jmxServerConnection.createMBean(className, new ObjectName(name), new ObjectName(classLoader)); else jmxServerConnection.createMBean(className, new ObjectName(name), new ObjectName(classLoader),argsA,sigA); } else { if (isEcho()) { handleOutput("create MBean " + name + " from class " + className); } if(args == null) jmxServerConnection.createMBean(className, new ObjectName(name)); else jmxServerConnection.createMBean(className, new ObjectName(name),argsA,sigA); } return error; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorInvokeTask.java
Override public String jmxExecute(MBeanServerConnection jmxServerConnection) throws Exception { if (getName() == null) { throw new BuildException("Must specify a 'name'"); } if ((operation == null)) { throw new BuildException( "Must specify a 'operation' for call"); } return jmxInvoke(jmxServerConnection, getName()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorInvokeTask.java
protected String jmxInvoke(MBeanServerConnection jmxServerConnection, String name) throws Exception { Object result ; if (args == null) { result = jmxServerConnection.invoke(new ObjectName(name), operation, null, null); } else { Object argsA[]=new Object[ args.size()]; String sigA[]=new String[args.size()]; for( int i=0; i<args.size(); i++ ) { Arg arg=args.get(i); if( arg.type==null) { arg.type="java.lang.String"; sigA[i]=arg.getType(); argsA[i]=arg.getValue(); } else { sigA[i]=arg.getType(); argsA[i]=convertStringToType(arg.getValue(),arg.getType()); } } result = jmxServerConnection.invoke(new ObjectName(name), operation, argsA, sigA); } if(result != null) { echoResult(operation,result); createProperty(result); } return null; }
// in java/org/apache/catalina/manager/StatusTransformer.java
public static void writeVMState(PrintWriter writer, int mode) throws Exception { if (mode == 0){ writer.print("<h1>JVM</h1>"); writer.print("<p>"); writer.print(" Free memory: "); writer.print(formatSize( Long.valueOf(Runtime.getRuntime().freeMemory()), true)); writer.print(" Total memory: "); writer.print(formatSize( Long.valueOf(Runtime.getRuntime().totalMemory()), true)); writer.print(" Max memory: "); writer.print(formatSize( Long.valueOf(Runtime.getRuntime().maxMemory()), true)); writer.print("</p>"); } else if (mode == 1){ writer.write("<jvm>"); writer.write("<memory"); writer.write(" free='" + Runtime.getRuntime().freeMemory() + "'"); writer.write(" total='" + Runtime.getRuntime().totalMemory() + "'"); writer.write(" max='" + Runtime.getRuntime().maxMemory() + "'/>"); writer.write("</jvm>"); } }
// in java/org/apache/catalina/manager/StatusTransformer.java
public static void writeConnectorState(PrintWriter writer, ObjectName tpName, String name, MBeanServer mBeanServer, Vector<ObjectName> globalRequestProcessors, Vector<ObjectName> requestProcessors, int mode) throws Exception { if (mode == 0) { writer.print("<h1>"); writer.print(name); writer.print("</h1>"); writer.print("<p>"); writer.print(" Max threads: "); writer.print(mBeanServer.getAttribute(tpName, "maxThreads")); writer.print(" Current thread count: "); writer.print(mBeanServer.getAttribute(tpName, "currentThreadCount")); writer.print(" Current thread busy: "); writer.print(mBeanServer.getAttribute(tpName, "currentThreadsBusy")); try { Object value = mBeanServer.getAttribute(tpName, "keepAliveCount"); writer.print(" Keeped alive sockets count: "); writer.print(value); } catch (Exception e) { // Ignore } writer.print("<br>"); ObjectName grpName = null; Enumeration<ObjectName> enumeration = globalRequestProcessors.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); if (name.equals(objectName.getKeyProperty("name"))) { grpName = objectName; } } if (grpName == null) { return; } writer.print(" Max processing time: "); writer.print(formatTime(mBeanServer.getAttribute (grpName, "maxTime"), false)); writer.print(" Processing time: "); writer.print(formatTime(mBeanServer.getAttribute (grpName, "processingTime"), true)); writer.print(" Request count: "); writer.print(mBeanServer.getAttribute(grpName, "requestCount")); writer.print(" Error count: "); writer.print(mBeanServer.getAttribute(grpName, "errorCount")); writer.print(" Bytes received: "); writer.print(formatSize(mBeanServer.getAttribute (grpName, "bytesReceived"), true)); writer.print(" Bytes sent: "); writer.print(formatSize(mBeanServer.getAttribute (grpName, "bytesSent"), true)); writer.print("</p>"); writer.print("<table border=\"0\"><tr><th>Stage</th><th>Time</th><th>B Sent</th><th>B Recv</th><th>Client</th><th>VHost</th><th>Request</th></tr>"); enumeration = requestProcessors.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); if (name.equals(objectName.getKeyProperty("worker"))) { writer.print("<tr>"); writeProcessorState(writer, objectName, mBeanServer, mode); writer.print("</tr>"); } } writer.print("</table>"); writer.print("<p>"); writer.print("P: Parse and prepare request S: Service F: Finishing R: Ready K: Keepalive"); writer.print("</p>"); } else if (mode == 1){ writer.write("<connector name='" + name + "'>"); writer.write("<threadInfo "); writer.write(" maxThreads=\"" + mBeanServer.getAttribute(tpName, "maxThreads") + "\""); writer.write(" currentThreadCount=\"" + mBeanServer.getAttribute(tpName, "currentThreadCount") + "\""); writer.write(" currentThreadsBusy=\"" + mBeanServer.getAttribute(tpName, "currentThreadsBusy") + "\""); writer.write(" />"); ObjectName grpName = null; Enumeration<ObjectName> enumeration = globalRequestProcessors.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); if (name.equals(objectName.getKeyProperty("name"))) { grpName = objectName; } } if (grpName != null) { writer.write("<requestInfo "); writer.write(" maxTime=\"" + mBeanServer.getAttribute(grpName, "maxTime") + "\""); writer.write(" processingTime=\"" + mBeanServer.getAttribute(grpName, "processingTime") + "\""); writer.write(" requestCount=\"" + mBeanServer.getAttribute(grpName, "requestCount") + "\""); writer.write(" errorCount=\"" + mBeanServer.getAttribute(grpName, "errorCount") + "\""); writer.write(" bytesReceived=\"" + mBeanServer.getAttribute(grpName, "bytesReceived") + "\""); writer.write(" bytesSent=\"" + mBeanServer.getAttribute(grpName, "bytesSent") + "\""); writer.write(" />"); writer.write("<workers>"); enumeration = requestProcessors.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); if (name.equals(objectName.getKeyProperty("worker"))) { writeProcessorState(writer, objectName, mBeanServer, mode); } } writer.write("</workers>"); } writer.write("</connector>"); } }
// in java/org/apache/catalina/manager/StatusTransformer.java
protected static void writeProcessorState(PrintWriter writer, ObjectName pName, MBeanServer mBeanServer, int mode) throws Exception { Integer stageValue = (Integer) mBeanServer.getAttribute(pName, "stage"); int stage = stageValue.intValue(); boolean fullStatus = true; boolean showRequest = true; String stageStr = null; switch (stage) { case (1/*org.apache.coyote.Constants.STAGE_PARSE*/): stageStr = "P"; fullStatus = false; break; case (2/*org.apache.coyote.Constants.STAGE_PREPARE*/): stageStr = "P"; fullStatus = false; break; case (3/*org.apache.coyote.Constants.STAGE_SERVICE*/): stageStr = "S"; break; case (4/*org.apache.coyote.Constants.STAGE_ENDINPUT*/): stageStr = "F"; break; case (5/*org.apache.coyote.Constants.STAGE_ENDOUTPUT*/): stageStr = "F"; break; case (7/*org.apache.coyote.Constants.STAGE_ENDED*/): stageStr = "R"; fullStatus = false; break; case (6/*org.apache.coyote.Constants.STAGE_KEEPALIVE*/): stageStr = "K"; fullStatus = true; showRequest = false; break; case (0/*org.apache.coyote.Constants.STAGE_NEW*/): stageStr = "R"; fullStatus = false; break; default: // Unknown stage stageStr = "?"; fullStatus = false; } if (mode == 0) { writer.write("<td><strong>"); writer.write(stageStr); writer.write("</strong></td>"); if (fullStatus) { writer.write("<td>"); writer.print(formatTime(mBeanServer.getAttribute (pName, "requestProcessingTime"), false)); writer.write("</td>"); writer.write("<td>"); if (showRequest) { writer.print(formatSize(mBeanServer.getAttribute (pName, "requestBytesSent"), false)); } else { writer.write("?"); } writer.write("</td>"); writer.write("<td>"); if (showRequest) { writer.print(formatSize(mBeanServer.getAttribute (pName, "requestBytesReceived"), false)); } else { writer.write("?"); } writer.write("</td>"); writer.write("<td>"); writer.print(filter(mBeanServer.getAttribute (pName, "remoteAddr"))); writer.write("</td>"); writer.write("<td nowrap>"); writer.write(filter(mBeanServer.getAttribute (pName, "virtualHost"))); writer.write("</td>"); writer.write("<td nowrap>"); if (showRequest) { writer.write(filter(mBeanServer.getAttribute (pName, "method"))); writer.write(" "); writer.write(filter(mBeanServer.getAttribute (pName, "currentUri"))); String queryString = (String) mBeanServer.getAttribute (pName, "currentQueryString"); if ((queryString != null) && (!queryString.equals(""))) { writer.write("?"); writer.print(RequestUtil.filter(queryString)); } writer.write(" "); writer.write(filter(mBeanServer.getAttribute (pName, "protocol"))); } else { writer.write("?"); } writer.write("</td>"); } else { writer.write("<td>?</td><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td>"); } } else if (mode == 1){ writer.write("<worker "); writer.write(" stage=\"" + stageStr + "\""); if (fullStatus) { writer.write(" requestProcessingTime=\"" + mBeanServer.getAttribute (pName, "requestProcessingTime") + "\""); writer.write(" requestBytesSent=\""); if (showRequest) { writer.write("" + mBeanServer.getAttribute (pName, "requestBytesSent")); } else { writer.write("0"); } writer.write("\""); writer.write(" requestBytesReceived=\""); if (showRequest) { writer.write("" + mBeanServer.getAttribute (pName, "requestBytesReceived")); } else { writer.write("0"); } writer.write("\""); writer.write(" remoteAddr=\"" + filter(mBeanServer.getAttribute (pName, "remoteAddr")) + "\""); writer.write(" virtualHost=\"" + filter(mBeanServer.getAttribute (pName, "virtualHost")) + "\""); if (showRequest) { writer.write(" method=\"" + filter(mBeanServer.getAttribute (pName, "method")) + "\""); writer.write(" currentUri=\"" + filter(mBeanServer.getAttribute (pName, "currentUri")) + "\""); String queryString = (String) mBeanServer.getAttribute (pName, "currentQueryString"); if ((queryString != null) && (!queryString.equals(""))) { writer.write(" currentQueryString=\"" + RequestUtil.filter(queryString) + "\""); } else { writer.write(" currentQueryString=\"&#63;\""); } writer.write(" protocol=\"" + filter(mBeanServer.getAttribute (pName, "protocol")) + "\""); } else { writer.write(" method=\"&#63;\""); writer.write(" currentUri=\"&#63;\""); writer.write(" currentQueryString=\"&#63;\""); writer.write(" protocol=\"&#63;\""); } } else { writer.write(" requestProcessingTime=\"0\""); writer.write(" requestBytesSent=\"0\""); writer.write(" requestBytesRecieved=\"0\""); writer.write(" remoteAddr=\"&#63;\""); writer.write(" virtualHost=\"&#63;\""); writer.write(" method=\"&#63;\""); writer.write(" currentUri=\"&#63;\""); writer.write(" currentQueryString=\"&#63;\""); writer.write(" protocol=\"&#63;\""); } writer.write(" />"); } }
// in java/org/apache/catalina/manager/StatusTransformer.java
public static void writeDetailedState(PrintWriter writer, MBeanServer mBeanServer, int mode) throws Exception { if (mode == 0){ ObjectName queryHosts = new ObjectName("*:j2eeType=WebModule,*"); Set<ObjectName> hostsON = mBeanServer.queryNames(queryHosts, null); // Navigation menu writer.print("<h1>"); writer.print("Application list"); writer.print("</h1>"); writer.print("<p>"); int count = 0; Iterator<ObjectName> iterator = hostsON.iterator(); while (iterator.hasNext()) { ObjectName contextON = iterator.next(); String webModuleName = contextON.getKeyProperty("name"); if (webModuleName.startsWith("//")) { webModuleName = webModuleName.substring(2); } int slash = webModuleName.indexOf("/"); if (slash == -1) { count++; continue; } writer.print("<a href=\"#" + (count++) + ".0\">"); writer.print(filter(webModuleName)); writer.print("</a>"); if (iterator.hasNext()) { writer.print("<br>"); } } writer.print("</p>"); // Webapp list count = 0; iterator = hostsON.iterator(); while (iterator.hasNext()) { ObjectName contextON = iterator.next(); writer.print("<a class=\"A.name\" name=\"" + (count++) + ".0\">"); writeContext(writer, contextON, mBeanServer, mode); } } else if (mode == 1){ // for now we don't write out the Detailed state in XML } }
// in java/org/apache/catalina/manager/StatusTransformer.java
protected static void writeContext(PrintWriter writer, ObjectName objectName, MBeanServer mBeanServer, int mode) throws Exception { if (mode == 0){ String webModuleName = objectName.getKeyProperty("name"); String name = webModuleName; if (name == null) { return; } String hostName = null; String contextName = null; if (name.startsWith("//")) { name = name.substring(2); } int slash = name.indexOf("/"); if (slash != -1) { hostName = name.substring(0, slash); contextName = name.substring(slash); } else { return; } ObjectName queryManager = new ObjectName (objectName.getDomain() + ":type=Manager,context=" + contextName + ",host=" + hostName + ",*"); Set<ObjectName> managersON = mBeanServer.queryNames(queryManager, null); ObjectName managerON = null; Iterator<ObjectName> iterator2 = managersON.iterator(); while (iterator2.hasNext()) { managerON = iterator2.next(); } ObjectName queryJspMonitor = new ObjectName (objectName.getDomain() + ":type=JspMonitor,WebModule=" + webModuleName + ",*"); Set<ObjectName> jspMonitorONs = mBeanServer.queryNames(queryJspMonitor, null); // Special case for the root context if (contextName.equals("/")) { contextName = ""; } writer.print("<h1>"); writer.print(filter(name)); writer.print("</h1>"); writer.print("</a>"); writer.print("<p>"); Object startTime = mBeanServer.getAttribute(objectName, "startTime"); writer.print(" Start time: " + new Date(((Long) startTime).longValue())); writer.print(" Startup time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "startupTime"), false)); writer.print(" TLD scan time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "tldScanTime"), false)); if (managerON != null) { writeManager(writer, managerON, mBeanServer, mode); } if (jspMonitorONs != null) { writeJspMonitor(writer, jspMonitorONs, mBeanServer, mode); } writer.print("</p>"); String onStr = objectName.getDomain() + ":j2eeType=Servlet,WebModule=" + webModuleName + ",*"; ObjectName servletObjectName = new ObjectName(onStr); Set<ObjectInstance> set = mBeanServer.queryMBeans(servletObjectName, null); Iterator<ObjectInstance> iterator = set.iterator(); while (iterator.hasNext()) { ObjectInstance oi = iterator.next(); writeWrapper(writer, oi.getObjectName(), mBeanServer, mode); } } else if (mode == 1){ // for now we don't write out the context in XML } }
// in java/org/apache/catalina/manager/StatusTransformer.java
public static void writeManager(PrintWriter writer, ObjectName objectName, MBeanServer mBeanServer, int mode) throws Exception { if (mode == 0) { writer.print("<br>"); writer.print(" Active sessions: "); writer.print(mBeanServer.getAttribute (objectName, "activeSessions")); writer.print(" Session count: "); writer.print(mBeanServer.getAttribute (objectName, "sessionCounter")); writer.print(" Max active sessions: "); writer.print(mBeanServer.getAttribute(objectName, "maxActive")); writer.print(" Rejected session creations: "); writer.print(mBeanServer.getAttribute (objectName, "rejectedSessions")); writer.print(" Expired sessions: "); writer.print(mBeanServer.getAttribute (objectName, "expiredSessions")); writer.print(" Longest session alive time: "); writer.print(formatSeconds(mBeanServer.getAttribute( objectName, "sessionMaxAliveTime"))); writer.print(" Average session alive time: "); writer.print(formatSeconds(mBeanServer.getAttribute( objectName, "sessionAverageAliveTime"))); writer.print(" Processing time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "processingTime"), false)); } else if (mode == 1) { // for now we don't write out the wrapper details } }
// in java/org/apache/catalina/manager/StatusTransformer.java
public static void writeJspMonitor(PrintWriter writer, Set<ObjectName> jspMonitorONs, MBeanServer mBeanServer, int mode) throws Exception { int jspCount = 0; int jspReloadCount = 0; Iterator<ObjectName> iter = jspMonitorONs.iterator(); while (iter.hasNext()) { ObjectName jspMonitorON = iter.next(); Object obj = mBeanServer.getAttribute(jspMonitorON, "jspCount"); jspCount += ((Integer) obj).intValue(); obj = mBeanServer.getAttribute(jspMonitorON, "jspReloadCount"); jspReloadCount += ((Integer) obj).intValue(); } if (mode == 0) { writer.print("<br>"); writer.print(" JSPs loaded: "); writer.print(jspCount); writer.print(" JSPs reloaded: "); writer.print(jspReloadCount); } else if (mode == 1) { // for now we don't write out anything } }
// in java/org/apache/catalina/manager/StatusTransformer.java
public static void writeWrapper(PrintWriter writer, ObjectName objectName, MBeanServer mBeanServer, int mode) throws Exception { if (mode == 0) { String servletName = objectName.getKeyProperty("name"); String[] mappings = (String[]) mBeanServer.invoke(objectName, "findMappings", null, null); writer.print("<h2>"); writer.print(filter(servletName)); if ((mappings != null) && (mappings.length > 0)) { writer.print(" [ "); for (int i = 0; i < mappings.length; i++) { writer.print(filter(mappings[i])); if (i < mappings.length - 1) { writer.print(" , "); } } writer.print(" ] "); } writer.print("</h2>"); writer.print("<p>"); writer.print(" Processing time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "processingTime"), true)); writer.print(" Max time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "maxTime"), false)); writer.print(" Request count: "); writer.print(mBeanServer.getAttribute(objectName, "requestCount")); writer.print(" Error count: "); writer.print(mBeanServer.getAttribute(objectName, "errorCount")); writer.print(" Load time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "loadTime"), false)); writer.print(" Classloading time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "classLoadTime"), false)); writer.print("</p>"); } else if (mode == 1){ // for now we don't write out the wrapper details } }
// in java/org/apache/catalina/manager/ManagerServlet.java
protected boolean isDeployed(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; Boolean result = (Boolean) mBeanServer.invoke(oname, "isDeployed", params, signature); return result.booleanValue(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
protected void check(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; mBeanServer.invoke(oname, "check", params, signature); }
// in java/org/apache/catalina/manager/ManagerServlet.java
protected boolean isServiced(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; Boolean result = (Boolean) mBeanServer.invoke(oname, "isServiced", params, signature); return result.booleanValue(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
protected void addServiced(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; mBeanServer.invoke(oname, "addServiced", params, signature); }
// in java/org/apache/catalina/manager/ManagerServlet.java
protected void removeServiced(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; mBeanServer.invoke(oname, "removeServiced", params, signature); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
public void listen() throws Exception { if (doListen()) { log.warn("ServerSocket already started"); return; } setListen(true); while ( doListen() ) { Socket socket = null; if ( getTaskPool().available() < 1 ) { if ( log.isWarnEnabled() ) log.warn("All BIO server replication threads are busy, unable to handle more requests until a thread is freed up."); } BioReplicationTask task = (BioReplicationTask)getTaskPool().getRxTask(); if ( task == null ) continue; //should never happen try { socket = serverSocket.accept(); }catch ( Exception x ) { if ( doListen() ) throw x; } if ( !doListen() ) { task.setDoRun(false); task.serviceSocket(null,null); getExecutor().execute(task); break; //regular shutdown } if ( socket == null ) continue; socket.setReceiveBufferSize(getRxBufSize()); socket.setSendBufferSize(getTxBufSize()); socket.setTcpNoDelay(getTcpNoDelay()); socket.setKeepAlive(getSoKeepAlive()); socket.setOOBInline(getOoBInline()); socket.setReuseAddress(getSoReuseAddress()); socket.setSoLinger(getSoLingerOn(),getSoLingerTime()); socket.setTrafficClass(getSoTrafficClass()); socket.setSoTimeout(getTimeout()); ObjectReader reader = new ObjectReader(socket); task.serviceSocket(socket,reader); getExecutor().execute(task); }//while }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
protected void execute(ObjectReader reader) throws Exception{ int pkgcnt = reader.count(); if ( pkgcnt > 0 ) { ChannelMessage[] msgs = reader.execute(); for ( int i=0; i<msgs.length; i++ ) { /** * Use send ack here if you want to ack the request to the remote * server before completing the request * This is considered an asynchronized request */ if (ChannelData.sendAckAsync(msgs[i].getOptions())) sendAck(Constants.ACK_COMMAND); try { //process the message getCallback().messageDataReceived(msgs[i]); /** * Use send ack here if you want the request to complete on this * server before sending the ack to the remote server * This is considered a synchronized request */ if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(Constants.ACK_COMMAND); }catch ( Exception x ) { if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(Constants.FAIL_ACK_COMMAND); log.error("Error thrown from messageDataReceived.",x); } if ( getUseBufferPool() ) { BufferPool.getBufferPool().returnBuffer(msgs[i].getMessage()); msgs[i].setMessage(null); } } } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
protected void drainSocket () throws Exception { InputStream in = socket.getInputStream(); // loop while data available, channel is non-blocking byte[] buf = new byte[1024]; int length = in.read(buf); while ( length >= 0 ) { int count = reader.append(buf,0,length,true); if ( count > 0 ) execute(reader); length = in.read(buf); } }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
protected void drainChannel (final SelectionKey key, ObjectReader reader) throws Exception { reader.setLastAccess(System.currentTimeMillis()); reader.access(); ReadableByteChannel channel = (ReadableByteChannel) key.channel(); int count=-1; buffer.clear(); // make buffer empty SocketAddress saddr = null; if (channel instanceof SocketChannel) { // loop while data available, channel is non-blocking while ((count = channel.read (buffer)) > 0) { buffer.flip(); // make buffer readable if ( buffer.hasArray() ) reader.append(buffer.array(),0,count,false); else reader.append(buffer,count,false); buffer.clear(); // make buffer empty //do we have at least one package? if ( reader.hasPackage() ) break; } } else if (channel instanceof DatagramChannel) { DatagramChannel dchannel = (DatagramChannel)channel; saddr = dchannel.receive(buffer); buffer.flip(); // make buffer readable if ( buffer.hasArray() ) reader.append(buffer.array(),0,buffer.limit()-buffer.position(),false); else reader.append(buffer,buffer.limit()-buffer.position(),false); buffer.clear(); // make buffer empty //did we get a package count = reader.hasPackage()?1:-1; } int pkgcnt = reader.count(); if (count < 0 && pkgcnt == 0 ) { //end of stream, and no more packages to process remoteEof(key); return; } ChannelMessage[] msgs = pkgcnt == 0? ChannelData.EMPTY_DATA_ARRAY : reader.execute(); registerForRead(key,reader);//register to read new data, before we send it off to avoid dead locks for ( int i=0; i<msgs.length; i++ ) { /** * Use send ack here if you want to ack the request to the remote * server before completing the request * This is considered an asynchronized request */ if (ChannelData.sendAckAsync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.ACK_COMMAND,saddr); try { if ( Logs.MESSAGES.isTraceEnabled() ) { try { Logs.MESSAGES.trace("NioReplicationThread - Received msg:" + new UniqueId(msgs[i].getUniqueId()) + " at " + new java.sql.Timestamp(System.currentTimeMillis())); }catch ( Throwable t ) {} } //process the message getCallback().messageDataReceived(msgs[i]); /** * Use send ack here if you want the request to complete on this * server before sending the ack to the remote server * This is considered a synchronized request */ if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.ACK_COMMAND,saddr); }catch ( RemoteProcessException e ) { if ( log.isDebugEnabled() ) log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); }catch ( Exception e ) { log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); } if ( getUseBufferPool() ) { BufferPool.getBufferPool().returnBuffer(msgs[i].getMessage()); msgs[i].setMessage(null); } } if (count < 0) { remoteEof(key); return; } }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
protected void listen() throws Exception { if (doListen()) { log.warn("ServerSocketChannel already started"); return; } setListen(true); // Avoid NPEs if selector is set to null on stop. Selector selector = this.selector; if (selector!=null && datagramChannel!=null) { ObjectReader oreader = new ObjectReader(MAX_UDP_SIZE); //max size for a datagram packet datagramChannel.socket().setSendBufferSize(getUdpTxBufSize()); datagramChannel.socket().setReceiveBufferSize(getUdpRxBufSize()); datagramChannel.socket().setReuseAddress(getSoReuseAddress()); datagramChannel.socket().setSoTimeout(getTimeout()); datagramChannel.socket().setTrafficClass(getSoTrafficClass()); registerChannel(selector,datagramChannel,SelectionKey.OP_READ,oreader); } while (doListen() && selector != null) { // this may block for a long time, upon return the // selected set contains keys of the ready channels try { events(); socketTimeouts(); int n = selector.select(getSelectorTimeout()); if (n == 0) { //there is a good chance that we got here //because the TcpReplicationThread called //selector wakeup(). //if that happens, we must ensure that that //thread has enough time to call interestOps // synchronized (interestOpsMutex) { //if we got the lock, means there are no //keys trying to register for the //interestOps method // } continue; // nothing to do } // get an iterator over the set of selected keys Iterator<SelectionKey> it = selector.selectedKeys().iterator(); // look at each key in the selected set while (it!=null && it.hasNext()) { SelectionKey key = it.next(); // Is a new connection coming in? if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel channel = server.accept(); channel.socket().setReceiveBufferSize(getRxBufSize()); channel.socket().setSendBufferSize(getTxBufSize()); channel.socket().setTcpNoDelay(getTcpNoDelay()); channel.socket().setKeepAlive(getSoKeepAlive()); channel.socket().setOOBInline(getOoBInline()); channel.socket().setReuseAddress(getSoReuseAddress()); channel.socket().setSoLinger(getSoLingerOn(),getSoLingerTime()); channel.socket().setTrafficClass(getSoTrafficClass()); channel.socket().setSoTimeout(getTimeout()); Object attach = new ObjectReader(channel); registerChannel(selector, channel, SelectionKey.OP_READ, attach); } // is there data to read on this channel? if (key.isReadable()) { readDataFromSocket(key); } else { key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE)); } // remove key from selected set, it's been handled it.remove(); } } catch (java.nio.channels.ClosedSelectorException cse) { // ignore is normal at shutdown or stop listen socket } catch (java.nio.channels.CancelledKeyException nx) { log.warn("Replication client disconnected, error when polling key. Ignoring client."); } catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } log.error("Unable to process request in NioReceiver", t); } } serverChannel.close(); if (datagramChannel!=null) { try { datagramChannel.close(); }catch (Exception iox) { if (log.isDebugEnabled()) log.debug("Unable to close datagram channel.",iox); } datagramChannel=null; } closeSelector(); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
protected void registerChannel(Selector selector, SelectableChannel channel, int ops, Object attach) throws Exception { if (channel == null)return; // could happen // set the new channel non-blocking channel.configureBlocking(false); // register it with the selector channel.register(selector, ops, attach); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
protected void readDataFromSocket(SelectionKey key) throws Exception { NioReplicationTask task = (NioReplicationTask) getTaskPool().getRxTask(); if (task == null) { // No threads/tasks available, do nothing, the selection // loop will keep calling this method until a // thread becomes available, the thread pool itself has a waiting mechanism // so we will not wait here. if (log.isDebugEnabled()) log.debug("No TcpReplicationThread available"); } else { // invoking this wakes up the worker thread then returns //add task to thread pool task.serviceChannel(key); getExecutor().execute(task); } }
// in java/org/apache/catalina/tribes/membership/McastService.java
Override public void start() throws java.lang.Exception { start(MembershipService.MBR_RX); start(MembershipService.MBR_TX); }
// in java/org/apache/catalina/tribes/membership/McastService.java
Override public void start(int level) throws java.lang.Exception { hasProperty(properties,"mcastPort"); hasProperty(properties,"mcastAddress"); hasProperty(properties,"memberDropTime"); hasProperty(properties,"mcastFrequency"); hasProperty(properties,"tcpListenPort"); hasProperty(properties,"tcpListenHost"); hasProperty(properties,"tcpSecurePort"); hasProperty(properties,"udpListenPort"); if ( impl != null ) { impl.start(level); return; } String host = getProperties().getProperty("tcpListenHost"); int port = Integer.parseInt(getProperties().getProperty("tcpListenPort")); int securePort = Integer.parseInt(getProperties().getProperty("tcpSecurePort")); int udpPort = Integer.parseInt(getProperties().getProperty("udpListenPort")); if ( localMember == null ) { localMember = new MemberImpl(host, port, 100); localMember.setUniqueId(UUIDGenerator.randomUUID(true)); } else { localMember.setHostname(host); localMember.setPort(port); localMember.setMemberAliveTime(100); } localMember.setSecurePort(securePort); localMember.setUdpPort(udpPort); if ( this.payload != null ) localMember.setPayload(payload); if ( this.domain != null ) localMember.setDomain(domain); localMember.setServiceStartTime(System.currentTimeMillis()); java.net.InetAddress bind = null; if ( properties.getProperty("mcastBindAddress")!= null ) { bind = java.net.InetAddress.getByName(properties.getProperty("mcastBindAddress")); } int ttl = -1; int soTimeout = -1; if ( properties.getProperty("mcastTTL") != null ) { try { ttl = Integer.parseInt(properties.getProperty("mcastTTL")); } catch ( Exception x ) { log.error("Unable to parse mcastTTL="+properties.getProperty("mcastTTL"),x); } } if ( properties.getProperty("mcastSoTimeout") != null ) { try { soTimeout = Integer.parseInt(properties.getProperty("mcastSoTimeout")); } catch ( Exception x ) { log.error("Unable to parse mcastSoTimeout="+properties.getProperty("mcastSoTimeout"),x); } } impl = new McastServiceImpl(localMember,Long.parseLong(properties.getProperty("mcastFrequency")), Long.parseLong(properties.getProperty("memberDropTime")), Integer.parseInt(properties.getProperty("mcastPort")), bind, java.net.InetAddress.getByName(properties.getProperty("mcastAddress")), ttl, soTimeout, this, this, Boolean.valueOf(properties.getProperty("localLoopbackDisabled","false")).booleanValue()); String value = properties.getProperty("recoveryEnabled","true"); boolean recEnabled = Boolean.valueOf(value).booleanValue() ; impl.setRecoveryEnabled(recEnabled); int recCnt = Integer.parseInt(properties.getProperty("recoveryCounter","10")); impl.setRecoveryCounter(recCnt); long recSlpTime = Long.parseLong(properties.getProperty("recoverySleepTime","5000")); impl.setRecoverySleepTime(recSlpTime); impl.start(level); }
// in java/org/apache/catalina/tribes/membership/McastService.java
public static void main(String args[]) throws Exception { if(log.isInfoEnabled()) log.info("Usage McastService hostname tcpport"); McastService service = new McastService(); java.util.Properties p = new java.util.Properties(); p.setProperty("mcastPort","5555"); p.setProperty("mcastAddress","224.10.10.10"); p.setProperty("mcastClusterDomain","catalina"); p.setProperty("bindAddress","localhost"); p.setProperty("memberDropTime","3000"); p.setProperty("mcastFrequency","500"); p.setProperty("tcpListenPort","4000"); p.setProperty("tcpListenHost","127.0.0.1"); service.setProperties(p); service.start(); Thread.sleep(60*1000*60); }
// in java/org/apache/catalina/tribes/membership/Constants.java
public static void main(String[] args) throws Exception { System.out.println(Arrays.toString("TRIBES-B".getBytes())); System.out.println(Arrays.toString("TRIBES-E".getBytes())); }
// in java/org/apache/catalina/session/StandardManager.java
Override public Void run() throws Exception{ doLoad(); return null; }
// in java/org/apache/catalina/session/StandardManager.java
Override public Void run() throws Exception{ doUnload(); return null; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override public Void run() throws Exception{ store.clear(); return null; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override public Void run() throws Exception{ store.remove(id); return null; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override public Session run() throws Exception{ return store.load(id); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override public Void run() throws Exception{ store.save(session); return null; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override public String[] run() throws Exception{ return store.keys(); }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
public static MBeanServer getMBeanServer() throws Exception { if (mbeanServer == null) { if (MBeanServerFactory.findMBeanServer(null).size() > 0) { mbeanServer = MBeanServerFactory.findMBeanServer(null).get(0); } else { mbeanServer = MBeanServerFactory.createMBeanServer(); } } return mbeanServer; }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
public static DynamicMBean getManagedBean(Object object) throws Exception { DynamicMBean mbean = null; if (getRegistry() != null) { ManagedBean managedBean = registry.findManagedBean(object.getClass().getName()); mbean = managedBean.createMBean(object); } return mbean; }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
private static ObjectName getDefaultClusterName(SimpleTcpCluster cluster) throws Exception { String domain = getMBeanServer().getDefaultDomain(); String type = ":type="; String clusterType= type+"Cluster"; if (cluster.getContainer() instanceof StandardHost) { domain = ((StandardHost) cluster.getContainer()).getDomain(); clusterType += ",host=" + cluster.getContainer().getName(); } else { if (cluster.getContainer() instanceof StandardEngine) { domain = ((StandardEngine) cluster.getContainer()).getDomain(); } } ObjectName clusterName = new ObjectName(domain + clusterType); return clusterName; }
// in java/org/apache/catalina/ha/backend/TcpSender.java
Override public void init(HeartbeatListener config) throws Exception { this.config = config; StringTokenizer tok = new StringTokenizer(config.getProxyList(), ","); proxies = new Proxy[tok.countTokens()]; int i = 0; while (tok.hasMoreTokens()) { String token = tok.nextToken().trim(); int pos = token.indexOf(':'); if (pos <=0) throw new Exception("bad ProxyList"); proxies[i] = new Proxy(); proxies[i].port = Integer.parseInt(token.substring(pos + 1)); try { proxies[i].address = InetAddress.getByName(token.substring(0, pos)); } catch (Exception e) { throw new Exception("bad ProxyList"); } i++; } connections = new Socket[proxies.length]; connectionReaders = new BufferedReader[proxies.length]; connectionWriters = new BufferedWriter[proxies.length]; }
// in java/org/apache/catalina/ha/backend/TcpSender.java
Override public int send(String mess) throws Exception { if (connections == null) { log.error("Not initialized"); return -1; } String requestLine = "POST " + config.getProxyURL() + " HTTP/1.0"; for (int i = 0; i < connections.length; i++) { if (connections[i] == null) { try { if (config.host != null) { connections[i] = new Socket(); InetAddress addr = InetAddress.getByName(config.host); InetSocketAddress addrs = new InetSocketAddress(addr, 0); connections[i].setReuseAddress(true); connections[i].bind(addrs); addrs = new InetSocketAddress(proxies[i].address, proxies[i].port); connections[i].connect(addrs); } else connections[i] = new Socket(proxies[i].address, proxies[i].port); connectionReaders[i] = new BufferedReader(new InputStreamReader(connections[i].getInputStream())); connectionWriters[i] = new BufferedWriter(new OutputStreamWriter(connections[i].getOutputStream())); } catch (Exception ex) { log.error("Unable to connect to proxy: " + ex); close(i); } } if (connections[i] == null) continue; // try next proxy in the list BufferedWriter writer = connectionWriters[i]; try { writer.write(requestLine); writer.write("\r\n"); writer.write("Content-Length: " + mess.length() + "\r\n"); writer.write("User-Agent: HeartbeatListener/1.0\r\n"); writer.write("Connection: Keep-Alive\r\n"); writer.write("\r\n"); writer.write(mess); writer.write("\r\n"); writer.flush(); } catch (Exception ex) { log.error("Unable to send collected load information to proxy: " + ex); close(i); } if (connections[i] == null) continue; // try next proxy in the list /* Read httpd answer */ String responseStatus = connectionReaders[i].readLine(); if (responseStatus == null) { log.error("Unable to read response from proxy"); close(i); continue; } else { responseStatus = responseStatus.substring(responseStatus.indexOf(' ') + 1, responseStatus.indexOf(' ', responseStatus.indexOf(' ') + 1)); int status = Integer.parseInt(responseStatus); if (status != 200) { log.error("Status is " + status); close(i); continue; } // read all the headers. String header = connectionReaders[i].readLine(); int contentLength = 0; while (!"".equals(header)) { int colon = header.indexOf(':'); String headerName = header.substring(0, colon).trim(); String headerValue = header.substring(colon + 1).trim(); if ("content-length".equalsIgnoreCase(headerName)) { contentLength = Integer.parseInt(headerValue); } header = connectionReaders[i].readLine(); } if (contentLength > 0) { char[] buf = new char[512]; while (contentLength > 0) { int thisTime = (contentLength > buf.length) ? buf.length : contentLength; int n = connectionReaders[i].read(buf, 0, thisTime); if (n <= 0) { log.error("Read content failed"); close(i); break; } else { contentLength -= n; } } } } } return 0; }
// in java/org/apache/catalina/ha/backend/CollectedInfo.java
public void init(String host, int port) throws Exception { int iport = 0; String shost = null; mBeanServer = Registry.getRegistry(null, null).getMBeanServer(); String onStr = "*:type=ThreadPool,*"; ObjectName objectName = new ObjectName(onStr); Set<ObjectInstance> set = mBeanServer.queryMBeans(objectName, null); Iterator<ObjectInstance> iterator = set.iterator(); while (iterator.hasNext()) { ObjectInstance oi = iterator.next(); objName = oi.getObjectName(); String name = objName.getKeyProperty("name"); /* Name are: * http-8080 * jk-10.33.144.3-8009 * jk-jfcpc%2F10.33.144.3-8009 */ String [] elenames = name.split("-"); String sport = elenames[elenames.length-1]; iport = Integer.parseInt(sport); String [] shosts = elenames[1].split("%2F"); shost = shosts[0]; if (port==0 && host==null) break; /* Take the first one */ if (host==null && iport==port) break; /* Only port done */ if (shost.compareTo(host) == 0) break; /* Done port and host are the expected ones */ } if (objName == null) throw(new Exception("Can't find connector for " + host + ":" + port)); this.port = iport; this.host = shost; }
// in java/org/apache/catalina/ha/backend/CollectedInfo.java
public void refresh() throws Exception { if (mBeanServer == null || objName == null) { throw(new Exception("Not initialized!!!")); } Integer imax = (Integer) mBeanServer.getAttribute(objName, "maxThreads"); // the currentThreadCount could be 0 before the threads are created... // Integer iready = (Integer) mBeanServer.getAttribute(objName, "currentThreadCount"); Integer ibusy = (Integer) mBeanServer.getAttribute(objName, "currentThreadsBusy"); busy = ibusy.intValue(); ready = imax.intValue() - ibusy.intValue(); }
// in java/org/apache/catalina/ha/backend/MultiCastSender.java
Override public void init(HeartbeatListener config) throws Exception { this.config = config; }
// in java/org/apache/catalina/ha/backend/MultiCastSender.java
Override public int send(String mess) throws Exception { if (s == null) { try { group = InetAddress.getByName(config.getGroup()); if (config.host != null) { InetAddress addr = InetAddress.getByName(config.host); InetSocketAddress addrs = new InetSocketAddress(addr, config.getMultiport()); s = new MulticastSocket(addrs); } else s = new MulticastSocket(config.getMultiport()); s.setTimeToLive(config.getTtl()); s.joinGroup(group); } catch (Exception ex) { log.error("Unable to use multicast: " + ex); s = null; return -1; } } byte[] buf; buf = mess.getBytes(US_ASCII); DatagramPacket data = new DatagramPacket(buf, buf.length, group, config.getMultiport()); try { s.send(data); } catch (Exception ex) { log.error("Unable to send colllected load information: " + ex); s.close(); s = null; return -1; } return 0; }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public static void main(String[] args) throws Exception { System.out .println("Usage: FileMessageFactory fileToBeRead fileToBeWritten"); System.out .println("Usage: This will make a copy of the file on the local file system"); FileMessageFactory read = getInstance(new File(args[0]), false); FileMessageFactory write = getInstance(new File(args[1]), true); FileMessage msg = new FileMessage(null, args[0], args[0]); msg = read.readMessage(msg); System.out.println("Expecting to write " + msg.getTotalNrOfMsgs() + " messages."); int cnt = 0; while (msg != null) { write.writeMessage(msg); cnt++; msg = read.readMessage(msg); }//while System.out.println("Actually wrote " + cnt + " messages."); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
Override public void start() throws Exception { if (started) return; Container hcontainer = getCluster().getContainer(); if(!(hcontainer instanceof Host)) { log.error(sm.getString("farmWarDeployer.hostOnly")); return ; } host = (Host) hcontainer; // Check to correct engine and host setup Container econtainer = host.getParent(); if(!(econtainer instanceof Engine)) { log.error(sm.getString("farmWarDeployer.hostParentEngine", host.getName())); return ; } Engine engine = (Engine) econtainer; String hostname = null; hostname = host.getName(); try { oname = new ObjectName(engine.getName() + ":type=Deployer,host=" + hostname); } catch (Exception e) { log.error(sm.getString("farmWarDeployer.mbeanNameFail", engine.getName(), hostname),e); return; } if (watchEnabled) { watcher = new WarWatcher(this, new File(getWatchDir())); if (log.isInfoEnabled()) { log.info(sm.getString( "farmWarDeployer.watchDir", getWatchDir())); } } configBase = new File(engine.getCatalinaBase(), "conf"); configBase = new File(configBase, engine.getName()); configBase = new File(configBase, hostname); // Retrieve the MBean server mBeanServer = Registry.getRegistry(null, null).getMBeanServer(); started = true; count = 0; getCluster().addClusterListener(this); if (log.isInfoEnabled()) log.info(sm.getString("farmWarDeployer.started")); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
protected void remove(String contextName) throws Exception { // TODO Handle remove also work dir content ! // Stop the context first to be nicer Context context = (Context) host.findChild(contextName); if (context != null) { if(log.isDebugEnabled()) log.debug(sm.getString("farmWarDeployer.undeployLocal", contextName)); context.stop(); String baseName = context.getBaseName(); File war = new File(host.getAppBaseFile(), baseName + ".war"); File dir = new File(host.getAppBaseFile(), baseName); File xml = new File(configBase, baseName + ".xml"); if (war.exists()) { if (!war.delete()) { log.error(sm.getString("farmWarDeployer.deleteFail", war)); } } else if (dir.exists()) { undeployDir(dir); } else { if (!xml.delete()) { log.error(sm.getString("farmWarDeployer.deleteFail", xml)); } } // Perform new deployment and remove internal HostConfig state check(contextName); } }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
protected void check(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; mBeanServer.invoke(oname, "check", params, signature); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
protected boolean isServiced(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; Boolean result = (Boolean) mBeanServer.invoke(oname, "isServiced", params, signature); return result.booleanValue(); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
protected void addServiced(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; mBeanServer.invoke(oname, "addServiced", params, signature); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
protected void removeServiced(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; mBeanServer.invoke(oname, "removeServiced", params, signature); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
protected void registerClusterValve() throws Exception { if(container != null ) { for (Iterator<Valve> iter = valves.iterator(); iter.hasNext();) { ClusterValve valve = (ClusterValve) iter.next(); if (log.isDebugEnabled()) log.debug("Invoking addValve on " + getContainer() + " with class=" + valve.getClass().getName()); if (valve != null) { IntrospectionUtils.callMethodN(getContainer(), "addValve", new Object[] { valve }, new Class[] { org.apache.catalina.Valve.class }); valve.setCluster(this); } } } }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
protected void unregisterClusterValve() throws Exception { for (Iterator<Valve> iter = valves.iterator(); iter.hasNext();) { ClusterValve valve = (ClusterValve) iter.next(); if (log.isDebugEnabled()) log.debug("Invoking removeValve on " + getContainer() + " with class=" + valve.getClass().getName()); if (valve != null) { IntrospectionUtils.callMethodN(getContainer(), "removeValve", new Object[] { valve }, new Class[] { org.apache.catalina.Valve.class }); valve.setCluster(this); } } }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
Override public boolean asyncDispatch(org.apache.coyote.Request req, org.apache.coyote.Response res, SocketStatus status) throws Exception { Request request = (Request) req.getNote(ADAPTER_NOTES); Response response = (Response) res.getNote(ADAPTER_NOTES); if (request == null) { throw new IllegalStateException( "Dispatch may only happen on an existing request."); } boolean comet = false; boolean success = true; AsyncContextImpl asyncConImpl = (AsyncContextImpl)request.getAsyncContext(); req.getRequestProcessor().setWorkerThreadName(Thread.currentThread().getName()); try { if (!request.isAsync() && !comet) { // Error or timeout - need to tell listeners the request is over // Have to test this first since state may change while in this // method and this is only required if entering this method in // this state Context ctxt = (Context) request.getMappingData().context; if (ctxt != null) { ctxt.fireRequestDestroyEvent(request); } // Lift any suspension (e.g. if sendError() was used by an async // request) to allow the response to be written to the client response.setSuspended(false); } if (status==SocketStatus.TIMEOUT) { success = true; if (!asyncConImpl.timeout()) { asyncConImpl.setErrorState(null); } } if (request.isAsyncDispatching()) { success = true; connector.getService().getContainer().getPipeline().getFirst().invoke(request, response); Throwable t = (Throwable) request.getAttribute( RequestDispatcher.ERROR_EXCEPTION); if (t != null) { asyncConImpl.setErrorState(t); } } if (request.isComet()) { if (!response.isClosed() && !response.isError()) { if (request.getAvailable() || (request.getContentLength() > 0 && (!request.isParametersParsed()))) { // Invoke a read event right away if there are available bytes if (event(req, res, SocketStatus.OPEN)) { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { // Clear the filter chain, as otherwise it will not be reset elsewhere // since this is a Comet request request.setFilterChain(null); } } if (!request.isAsync() && !comet) { request.finishRequest(); response.finishResponse(); req.action(ActionCode.POST_REQUEST , null); ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); } } catch (IOException e) { success = false; // Ignore } catch (Throwable t) { ExceptionUtils.handleThrowable(t); success = false; log.error(sm.getString("coyoteAdapter.service"), t); } finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!success || (!comet && !request.isAsync())) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } } return success; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
Override public void service(org.apache.coyote.Request req, org.apache.coyote.Response res) throws Exception { Request request = (Request) req.getNote(ADAPTER_NOTES); Response response = (Response) res.getNote(ADAPTER_NOTES); if (request == null) { // Create objects request = connector.createRequest(); request.setCoyoteRequest(req); response = connector.createResponse(); response.setCoyoteResponse(res); // Link objects request.setResponse(response); response.setRequest(request); // Set as notes req.setNote(ADAPTER_NOTES, request); res.setNote(ADAPTER_NOTES, response); // Set query string encoding req.getParameters().setQueryStringEncoding (connector.getURIEncoding()); } if (connector.getXpoweredBy()) { response.addHeader("X-Powered-By", POWERED_BY); } boolean comet = false; boolean async = false; try { // Parse and set Catalina and configuration specific // request parameters req.getRequestProcessor().setWorkerThreadName(Thread.currentThread().getName()); boolean postParseSuccess = postParseRequest(req, request, res, response); if (postParseSuccess) { //check valves if we support async request.setAsyncSupported(connector.getService().getContainer().getPipeline().isAsyncSupported()); // Calling the container connector.getService().getContainer().getPipeline().getFirst().invoke(request, response); if (request.isComet()) { if (!response.isClosed() && !response.isError()) { if (request.getAvailable() || (request.getContentLength() > 0 && (!request.isParametersParsed()))) { // Invoke a read event right away if there are available bytes if (event(req, res, SocketStatus.OPEN)) { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { // Clear the filter chain, as otherwise it will not be reset elsewhere // since this is a Comet request request.setFilterChain(null); } } } AsyncContextImpl asyncConImpl = (AsyncContextImpl)request.getAsyncContext(); if (asyncConImpl != null) { async = true; } else if (!comet) { request.finishRequest(); response.finishResponse(); if (postParseSuccess && request.getMappingData().context != null) { // Log only if processing was invoked. // If postParseRequest() failed, it has already logged it. // If context is null this was the start of a comet request // that failed and has already been logged. ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); } req.action(ActionCode.POST_REQUEST , null); } } catch (IOException e) { // Ignore } finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!comet && !async) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } } }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
protected boolean postParseRequest(org.apache.coyote.Request req, Request request, org.apache.coyote.Response res, Response response) throws Exception { // XXX the processor may have set a correct scheme and port prior to this point, // in ajp13 protocols dont make sense to get the port from the connector... // otherwise, use connector configuration if (! req.scheme().isNull()) { // use processor specified scheme to determine secure state request.setSecure(req.scheme().equals("https")); } else { // use connector scheme and secure configuration, (defaults to // "http" and false respectively) req.scheme().setString(connector.getScheme()); request.setSecure(connector.getSecure()); } // FIXME: the code below doesnt belongs to here, // this is only have sense // in Http11, not in ajp13.. // At this point the Host header has been processed. // Override if the proxyPort/proxyHost are set String proxyName = connector.getProxyName(); int proxyPort = connector.getProxyPort(); if (proxyPort != 0) { req.setServerPort(proxyPort); } if (proxyName != null) { req.serverName().setString(proxyName); } // Copy the raw URI to the decodedURI MessageBytes decodedURI = req.decodedURI(); decodedURI.duplicate(req.requestURI()); // Parse the path parameters. This will: // - strip out the path parameters // - convert the decodedURI to bytes parsePathParameters(req, request); // URI decoding // %xx decoding of the URL try { req.getURLDecoder().convert(decodedURI, false); } catch (IOException ioe) { res.setStatus(400); res.setMessage("Invalid URI: " + ioe.getMessage()); connector.getService().getContainer().logAccess( request, response, 0, true); return false; } // Normalization if (!normalize(req.decodedURI())) { res.setStatus(400); res.setMessage("Invalid URI"); connector.getService().getContainer().logAccess( request, response, 0, true); return false; } // Character decoding convertURI(decodedURI, request); // Check that the URI is still normalized if (!checkNormalize(req.decodedURI())) { res.setStatus(400); res.setMessage("Invalid URI character encoding"); connector.getService().getContainer().logAccess( request, response, 0, true); return false; } // Set the remote principal String principal = req.getRemoteUser().toString(); if (principal != null) { request.setUserPrincipal(new CoyotePrincipal(principal)); } // Set the authorization type String authtype = req.getAuthType().toString(); if (authtype != null) { request.setAuthType(authtype); } // Request mapping. MessageBytes serverName; if (connector.getUseIPVHosts()) { serverName = req.localName(); if (serverName.isNull()) { // well, they did ask for it res.action(ActionCode.REQ_LOCAL_NAME_ATTRIBUTE, null); } } else { serverName = req.serverName(); } if (request.isAsyncStarted()) { //TODO SERVLET3 - async //reset mapping data, should prolly be done elsewhere request.getMappingData().recycle(); } boolean mapRequired = true; String version = null; while (mapRequired) { if (version != null) { // Once we have a version - that is it mapRequired = false; } // This will map the the latest version by default connector.getMapper().map(serverName, decodedURI, version, request.getMappingData()); request.setContext((Context) request.getMappingData().context); request.setWrapper((Wrapper) request.getMappingData().wrapper); // Single contextVersion therefore no possibility of remap if (request.getMappingData().contexts == null) { mapRequired = false; } // If there is no context at this point, it is likely no ROOT context // has been deployed if (request.getContext() == null) { res.setStatus(404); res.setMessage("Not found"); // No context, so use host Host host = request.getHost(); // Make sure there is a host (might not be during shutdown) if (host != null) { host.logAccess(request, response, 0, true); } return false; } // Now we have the context, we can parse the session ID from the URL // (if any). Need to do this before we redirect in case we need to // include the session id in the redirect String sessionID = null; if (request.getServletContext().getEffectiveSessionTrackingModes() .contains(SessionTrackingMode.URL)) { // Get the session ID if there was one sessionID = request.getPathParameter( SessionConfig.getSessionUriParamName( request.getContext())); if (sessionID != null) { request.setRequestedSessionId(sessionID); request.setRequestedSessionURL(true); } } // Look for session ID in cookies and SSL session parseSessionCookiesId(req, request); parseSessionSslId(request); sessionID = request.getRequestedSessionId(); if (mapRequired) { if (sessionID == null) { // No session means no possibility of needing to remap mapRequired = false; } else { // Find the context associated with the session Object[] objs = request.getMappingData().contexts; for (int i = (objs.length); i > 0; i--) { Context ctxt = (Context) objs[i - 1]; if (ctxt.getManager().findSession(sessionID) != null) { // Was the correct context already mapped? if (ctxt.equals(request.getMappingData().context)) { mapRequired = false; } else { // Set version so second time through mapping the // correct context is found version = ctxt.getWebappVersion(); // Reset mapping request.getMappingData().recycle(); break; } } } if (version == null) { // No matching context found. No need to re-map mapRequired = false; } } } if (!mapRequired && request.getContext().getPaused()) { // Found a matching context but it is paused. Mapping data will // be wrong since some Wrappers may not be registered at this // point. try { Thread.sleep(1000); } catch (InterruptedException e) { // Should never happen } // Reset mapping request.getMappingData().recycle(); mapRequired = true; } } // Possible redirect MessageBytes redirectPathMB = request.getMappingData().redirectPath; if (!redirectPathMB.isNull()) { String redirectPath = urlEncoder.encode(redirectPathMB.toString()); String query = request.getQueryString(); if (request.isRequestedSessionIdFromURL()) { // This is not optimal, but as this is not very common, it // shouldn't matter redirectPath = redirectPath + ";" + SessionConfig.getSessionUriParamName( request.getContext()) + "=" + request.getRequestedSessionId(); } if (query != null) { // This is not optimal, but as this is not very common, it // shouldn't matter redirectPath = redirectPath + "?" + query; } response.sendRedirect(redirectPath); request.getContext().logAccess(request, response, 0, true); return false; } // Filter trace method if (!connector.getAllowTrace() && req.method().equalsIgnoreCase("TRACE")) { Wrapper wrapper = request.getWrapper(); String header = null; if (wrapper != null) { String[] methods = wrapper.getServletMethods(); if (methods != null) { for (int i=0; i<methods.length; i++) { if ("TRACE".equals(methods[i])) { continue; } if (header == null) { header = methods[i]; } else { header += ", " + methods[i]; } } } } res.setStatus(405); res.addHeader("Allow", header); res.setMessage("TRACE method is not allowed"); request.getContext().logAccess(request, response, 0, true); return false; } return true; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
protected void convertURI(MessageBytes uri, Request request) throws Exception { ByteChunk bc = uri.getByteChunk(); int length = bc.getLength(); CharChunk cc = uri.getCharChunk(); cc.allocate(length, -1); String enc = connector.getURIEncoding(); if (enc != null) { B2CConverter conv = request.getURIConverter(); try { if (conv == null) { conv = new B2CConverter(enc); request.setURIConverter(conv); } } catch (IOException e) { // Ignore log.error("Invalid URI encoding; using HTTP default"); connector.setURIEncoding(null); } if (conv != null) { try { conv.convert(bc, cc, cc.getBuffer().length - cc.getEnd()); uri.setChars(cc.getBuffer(), cc.getStart(), cc.getLength()); return; } catch (IOException e) { log.error("Invalid URI character encoding; trying ascii"); cc.recycle(); } } } // Default encoding: fast conversion byte[] bbuf = bc.getBuffer(); char[] cbuf = cc.getBuffer(); int start = bc.getStart(); for (int i = 0; i < length; i++) { cbuf[i] = (char) (bbuf[i + start] & 0xff); } uri.setChars(cbuf, 0, length); }
// in java/org/apache/catalina/core/StandardHost.java
public String [] getValveNames() throws Exception { Valve [] valves = this.getPipeline().getValves(); String [] mbeanNames = new String[valves.length]; for (int i = 0; i < valves.length; i++) { if (valves[i] instanceof JmxEnabled) { ObjectName oname = ((JmxEnabled) valves[i]).getObjectName(); if (oname != null) { mbeanNames[i] = oname.toString(); } } } return mbeanNames; }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected Class<?> loadClassMaybePrivileged(final String className, final ClassLoader classLoader) throws ClassNotFoundException { Class<?> clazz; if (SecurityUtil.isPackageProtectionEnabled()) { try { clazz = AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() { @Override public Class<?> run() throws Exception { return loadClass(className, classLoader); } }); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Class<?> run() throws Exception { return loadClass(className, classLoader); }
// in java/org/apache/catalina/core/StandardServer.java
public synchronized void storeConfig() throws Exception { ObjectName sname = new ObjectName("Catalina:type=StoreConfig"); mserver.invoke(sname, "storeConfig", null, null); }
// in java/org/apache/catalina/core/StandardServer.java
public synchronized void storeContext(Context context) throws Exception { ObjectName sname = null; try { sname = new ObjectName("Catalina:type=StoreConfig"); if(mserver.isRegistered(sname)) { mserver.invoke(sname, "store", new Object[] {context}, new String [] { "java.lang.String"}); } else log.error("StoreConfig mbean not registered" + sname); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(t); } }
// in java/org/apache/catalina/core/StandardContext.java
private void resetContext() throws Exception { // Restore the original state ( pre reading web.xml in start ) // If you extend this - override this method and make sure to clean up // Don't reset anything that is read from a <Context.../> element since // <Context .../> elements are read at initialisation will not be read // again for this object for (Container child : findChildren()) { removeChild(child); } startupTime = 0; startTime = 0; tldScanTime = 0; // Bugzilla 32867 distributable = false; applicationListeners = new String[0]; applicationEventListenersObjects = new Object[0]; applicationLifecycleListenersObjects = new Object[0]; jspConfigDescriptor = new ApplicationJspConfigDescriptor(); initializers.clear(); createdServlets.clear(); if(log.isDebugEnabled()) log.debug("resetContext " + getObjectName()); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
Override public Void run() throws java.lang.Exception { doForward(request,response); return null; }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
Override public final void preDeregister() throws Exception { // NOOP }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
Override public final ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { this.mserver = server; this.oname = name; this.domain = name.getDomain(); return oname; }
// in java/org/apache/catalina/security/SecurityUtil.java
public static void doAsPrivilege(final String methodName, final Servlet targetObject) throws java.lang.Exception{ doAsPrivilege(methodName, targetObject, null, null, null); }
// in java/org/apache/catalina/security/SecurityUtil.java
public static void doAsPrivilege(final String methodName, final Servlet targetObject, final Class<?>[] targetType, final Object[] targetArguments) throws java.lang.Exception{ doAsPrivilege(methodName, targetObject, targetType, targetArguments, null); }
// in java/org/apache/catalina/security/SecurityUtil.java
public static void doAsPrivilege(final String methodName, final Servlet targetObject, final Class<?>[] targetType, final Object[] targetArguments, Principal principal) throws java.lang.Exception{ Method method = null; Method[] methodsCache = objectCache.get(targetObject); if(methodsCache == null) { method = createMethodAndCacheIt(methodsCache, methodName, targetObject, targetType); } else { method = findMethod(methodsCache, methodName); if (method == null) { method = createMethodAndCacheIt(methodsCache, methodName, targetObject, targetType); } } execute(method, targetObject, targetArguments, principal); }
// in java/org/apache/catalina/security/SecurityUtil.java
public static void doAsPrivilege(final String methodName, final Filter targetObject) throws java.lang.Exception{ doAsPrivilege(methodName, targetObject, null, null); }
// in java/org/apache/catalina/security/SecurityUtil.java
public static void doAsPrivilege(final String methodName, final Filter targetObject, final Class<?>[] targetType, final Object[] targetArguments) throws java.lang.Exception{ doAsPrivilege( methodName, targetObject, targetType, targetArguments, null); }
// in java/org/apache/catalina/security/SecurityUtil.java
public static void doAsPrivilege(final String methodName, final Filter targetObject, final Class<?>[] targetType, final Object[] targetArguments, Principal principal) throws java.lang.Exception{ Method method = null; Method[] methodsCache = objectCache.get(targetObject); if(methodsCache == null) { method = createMethodAndCacheIt(methodsCache, methodName, targetObject, targetType); } else { method = findMethod(methodsCache, methodName); if (method == null) { method = createMethodAndCacheIt(methodsCache, methodName, targetObject, targetType); } } execute(method, targetObject, targetArguments, principal); }
// in java/org/apache/catalina/security/SecurityUtil.java
private static void execute(final Method method, final Object targetObject, final Object[] targetArguments, Principal principal) throws java.lang.Exception{ try{ Subject subject = null; PrivilegedExceptionAction<Void> pea = new PrivilegedExceptionAction<Void>(){ @Override public Void run() throws Exception{ method.invoke(targetObject, targetArguments); return null; } }; // The first argument is always the request object if (targetArguments != null && targetArguments[0] instanceof HttpServletRequest){ HttpServletRequest request = (HttpServletRequest)targetArguments[0]; boolean hasSubject = false; HttpSession session = request.getSession(false); if (session != null){ subject = (Subject)session.getAttribute(Globals.SUBJECT_ATTR); hasSubject = (subject != null); } if (subject == null){ subject = new Subject(); if (principal != null){ subject.getPrincipals().add(principal); } } if (session != null && !hasSubject) { session.setAttribute(Globals.SUBJECT_ATTR, subject); } } Subject.doAsPrivileged(subject, pea, null); } catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/org/apache/catalina/security/SecurityUtil.java
Override public Void run() throws Exception{ method.invoke(targetObject, targetArguments); return null; }
// in java/org/apache/catalina/security/SecurityUtil.java
private static Method createMethodAndCacheIt(Method[] methodsCache, String methodName, Object targetObject, Class<?>[] targetType) throws Exception{ if ( methodsCache == null){ methodsCache = new Method[4]; } Method method = targetObject.getClass().getMethod(methodName, targetType); if (methodName.equalsIgnoreCase(INIT_METHOD)){ methodsCache[INIT] = method; } else if (methodName.equalsIgnoreCase(DESTROY_METHOD)){ methodsCache[DESTROY] = method; } else if (methodName.equalsIgnoreCase(SERVICE_METHOD)){ methodsCache[SERVICE] = method; } else if (methodName.equalsIgnoreCase(DOFILTER_METHOD)){ methodsCache[DOFILTER] = method; } else if (methodName.equalsIgnoreCase(EVENT_METHOD)){ methodsCache[EVENT] = method; } else if (methodName.equalsIgnoreCase(DOFILTEREVENT_METHOD)){ methodsCache[DOFILTEREVENT] = method; } objectCache.put(targetObject, methodsCache ); return method; }
// in java/org/apache/catalina/security/SecurityClassLoad.java
public static void securityClassLoad(ClassLoader loader) throws Exception { if( System.getSecurityManager() == null ){ return; } loadCorePackage(loader); loadCoyotePackage(loader); loadLoaderPackage(loader); loadRealmPackage(loader); loadSessionPackage(loader); loadUtilPackage(loader); loadJavaxPackage(loader); loadConnectorPackage(loader); loadTomcatPackage(loader); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadCorePackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.catalina.core."; loader.loadClass (basePackage + "ApplicationContextFacade$1"); loader.loadClass (basePackage + "ApplicationDispatcher$PrivilegedForward"); loader.loadClass (basePackage + "ApplicationDispatcher$PrivilegedInclude"); loader.loadClass (basePackage + "AsyncContextImpl"); loader.loadClass (basePackage + "AsyncContextImpl$DebugException"); loader.loadClass (basePackage + "AsyncContextImpl$1"); loader.loadClass (basePackage + "AsyncListenerWrapper"); loader.loadClass (basePackage + "ContainerBase$PrivilegedAddChild"); loader.loadClass (basePackage + "DefaultInstanceManager$1"); loader.loadClass (basePackage + "DefaultInstanceManager$2"); loader.loadClass (basePackage + "DefaultInstanceManager$3"); loader.loadClass (basePackage + "DefaultInstanceManager$AnnotationCacheEntry"); loader.loadClass (basePackage + "DefaultInstanceManager$AnnotationCacheEntryType"); loader.loadClass (basePackage + "ApplicationHttpRequest$AttributeNamesEnumerator"); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadLoaderPackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.catalina.loader."; loader.loadClass (basePackage + "WebappClassLoader$PrivilegedFindResourceByName"); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadRealmPackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.catalina.realm."; loader.loadClass (basePackage + "LockOutRealm$LockRecord"); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadSessionPackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.catalina.session."; loader.loadClass (basePackage + "StandardSession"); loader.loadClass (basePackage + "StandardSession$PrivilegedSetTccl"); loader.loadClass (basePackage + "StandardSession$1"); loader.loadClass (basePackage + "StandardManager$PrivilegedDoUnload"); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadUtilPackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.catalina.util."; loader.loadClass(basePackage + "ParameterMap"); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadCoyotePackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.coyote."; loader.loadClass(basePackage + "http11.AbstractOutputBuffer$1"); loader.loadClass(basePackage + "http11.Constants"); // Make sure system property is read at this point Class<?> clazz = loader.loadClass(basePackage + "Constants"); clazz.newInstance(); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadJavaxPackage(ClassLoader loader) throws Exception { loader.loadClass("javax.servlet.http.Cookie"); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadConnectorPackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.catalina.connector."; loader.loadClass (basePackage + "RequestFacade$GetAttributePrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetParameterMapPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetRequestDispatcherPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetParameterPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetParameterNamesPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetParameterValuePrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetCharacterEncodingPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetHeadersPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetHeaderNamesPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetCookiesPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetLocalePrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetLocalesPrivilegedAction"); loader.loadClass (basePackage + "ResponseFacade$SetContentTypePrivilegedAction"); loader.loadClass (basePackage + "ResponseFacade$DateHeaderPrivilegedAction"); loader.loadClass (basePackage + "RequestFacade$GetSessionPrivilegedAction"); loader.loadClass (basePackage + "ResponseFacade$1"); loader.loadClass (basePackage + "OutputBuffer$1"); loader.loadClass (basePackage + "CoyoteInputStream$1"); loader.loadClass (basePackage + "CoyoteInputStream$2"); loader.loadClass (basePackage + "CoyoteInputStream$3"); loader.loadClass (basePackage + "CoyoteInputStream$4"); loader.loadClass (basePackage + "CoyoteInputStream$5"); loader.loadClass (basePackage + "InputBuffer$1"); loader.loadClass (basePackage + "Response$1"); loader.loadClass (basePackage + "Response$2"); loader.loadClass (basePackage + "Response$3"); }
// in java/org/apache/catalina/security/SecurityClassLoad.java
private static final void loadTomcatPackage(ClassLoader loader) throws Exception { final String basePackage = "org.apache.tomcat."; loader.loadClass(basePackage + "util.buf.HexUtils"); loader.loadClass(basePackage + "util.buf.StringCache"); loader.loadClass(basePackage + "util.buf.StringCache$ByteEntry"); loader.loadClass(basePackage + "util.buf.StringCache$CharEntry"); loader.loadClass(basePackage + "util.http.HttpMessages"); // Make sure system property is read at this point Class<?> clazz = loader.loadClass( basePackage + "util.http.FastHttpDateFormat"); clazz.newInstance(); loader.loadClass(basePackage + "util.http.HttpMessages"); loader.loadClass(basePackage + "util.net.Constants"); loader.loadClass(basePackage + "util.net.NioBlockingSelector$BlockPoller$1"); loader.loadClass(basePackage + "util.net.NioBlockingSelector$BlockPoller$2"); loader.loadClass(basePackage + "util.net.NioBlockingSelector$BlockPoller$3"); loader.loadClass(basePackage + "util.net.SSLSupport$CipherData"); loader.loadClass (basePackage + "util.net.JIoEndpoint$PrivilegedSetTccl"); loader.loadClass (basePackage + "util.net.AprEndpoint$PrivilegedSetTccl"); }
475
            
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { e.printStackTrace(); result = null; }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception ex) { maxSize = -1; }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JspException(e.getMessage(), t); }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn("Error processing preDestroy on tag instance of " + handler.getClass().getName(), t); }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn("Error processing preDestroy on tag instance of " + handler.getClass().getName(), t); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException ("error in invoking method", ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (writer != null) { try { writer.close(); writer = null; } catch (Exception e1) { // do nothing } } // Remove the generated .java file File file = new File(javaFileName); if (file.exists()) { if (!file.delete()) { log.warn(Localizer.getMessage( "jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath())); } } throw e; }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e1) { // do nothing }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e2) { // do nothing }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (log.isDebugEnabled()) log.debug("Problem accessing resource. Treat as outdated.", e); return true; }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { // Remove as much as possible, log possible exceptions log.warn(Localizer.getMessage("jsp.warning.compiler.classfile.delete.fail.unknown"), e); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { // Remove as much as possible, log possible exceptions log.warn(Localizer.getMessage("jsp.warning.compiler.classfile.delete.fail.unknown"), e); }
// in java/org/apache/jasper/compiler/ParserController.java
catch (Exception any) { }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Exception ex) { err.jspError(mark, "jsp.error.tld.unable_to_read", jarResource.getUrl(), tldName, ex.toString()); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Exception ex) { err.jspError("jsp.error.tld.unable_to_get_jar", uri, ex .toString()); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Exception e) { err.jspError("jsp.error.teiclass.instantiation", teiClassName, e); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Exception e) { err.jspError("jsp.error.tlvclass.instantiation", validatorClass, e); }
// in java/org/apache/jasper/compiler/Parser.java
catch (Exception ex) { err.jspError(start, ex.getMessage()); }
// in java/org/apache/jasper/compiler/Parser.java
catch (Exception e) { err.jspError(start, "jsp.error.loadclass.taghandler", handlerClassName, tagName); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
catch (Exception e) { // ignore errors }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage( "jsp.error.internal.tldinit", ex.getMessage()), ex); }
// in java/org/apache/jasper/compiler/JspReader.java
catch (Exception any) { if(log.isDebugEnabled()) { log.debug("Exception closing reader: ", any); } }
// in java/org/apache/jasper/compiler/JspReader.java
catch (Exception any) { if(log.isDebugEnabled()) { log.debug("Exception closing reader: ", any); } }
// in java/org/apache/jasper/compiler/Generator.java
catch (Exception e) { // Cannot instantiate the specified class, either a // compilation error or a runtime error will be raised, // depending on a compiler flag. if (ctxt.getOptions() .getErrorOnUseBeanInvalidClassAttribute()) { err.jspError(n, "jsp.error.invalid.bean", klass); } if (canonicalName == null) { // Doing our best here to get a canonical name // from the binary name, should work 99.99% of time. canonicalName = klass.replace('$', '.'); } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (EnableDTDValidationException e) { saxParser = getSAXParser(true, jspDocParser); jspDocParser.isValidating = true; if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } inStream = JspUtil.getInputStream(path, jarFile, jspDocParser.ctxt); saxParser.parse(new InputSource(inStream), jspDocParser); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception any) { }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception any) { }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { jspDocParser.err.jspError(e); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { throw new SAXException( Localizer.getMessage("jsp.error.loadclass.taghandler", handlerClassName, qName), e); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { throw new SAXException(e); }
// in java/org/apache/jasper/compiler/TagPluginManager.java
catch (Exception e) { throw new JasperException(e); }
// in java/org/apache/jasper/compiler/Validator.java
catch (Exception e) { err.jspError (n, "jsp.error.coerce_to_type", tldAttr.getName(), expectedType, attrs.getValue(i)); }
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch(Exception e) { context.log("Security Init for context failed",e); }
// in java/org/apache/jasper/compiler/JspConfig.java
catch (Exception ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JasperException(t); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); // Log any exception, since it can't be passed along log.error(Localizer.getMessage("jsp.error.file.not.found", e.getMessage()), t); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception je) { // If anything goes wrong, just revert to the original behaviour if (ex instanceof JasperException) { return (JasperException) ex; } return new JasperException(ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (Exception ex) { JasperException je = new JasperException( Localizer.getMessage("jsp.error.unable.compile"), ex); // Cache compilation exception jsw.setCompilationException(je); throw je; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); }
// in java/org/apache/jasper/JspC.java
catch( Exception ex ) { uriRoot = s; }
// in java/org/apache/jasper/JspC.java
catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); }
// in java/org/apache/naming/factory/SendMailFactory.java
catch (Exception e) {/*Ignore*/}
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
catch (Exception e) { throw new ServiceException(e); }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { if (e instanceof InvocationTargetException) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } } NamingException ex = new NamingException ("Error while reading Wsdl File"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
catch (Exception x) { if (x instanceof InvocationTargetException) { Throwable cause = x.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } if (cause instanceof Exception) { x = (Exception) cause; } } if (x instanceof NamingException) throw (NamingException)x; else { NamingException nx = new NamingException(x.getMessage()); nx.initCause(x); throw nx; } }
// in java/org/apache/naming/factory/ResourceFactory.java
catch (Exception e) { if (e instanceof NamingException) throw (NamingException) e; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (Exception e) { NamingException ne = new NamingException(e.getMessage()); ne.initCause(e); throw ne; }
// in java/org/apache/naming/NamingContext.java
catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); }
// in java/org/apache/naming/resources/WARDirContext.java
catch (Exception e) { throw new IllegalArgumentException (sm.getString("warResources.invalidWar", e.getMessage())); }
// in java/org/apache/naming/resources/WARDirContext.java
catch (Exception e) { // Ignore }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (Exception e) { // Ignore }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (Exception e) { throw new IllegalArgumentException(sm.getString( "resources.invalidCache", cacheClassName), e); }
// in java/org/apache/naming/resources/ResourceCache.java
catch (Exception e) { // Ignore: the reliability of this lookup is not critical }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (Exception e) { // Ignore }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (Exception e) { // Report error System.err.println("Handler error"); e.printStackTrace(); }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { reportError(null, e, ErrorManager.FORMAT_FAILURE); return; }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { reportError(null, e, ErrorManager.WRITE_FAILURE); return; }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { reportError(null, e, ErrorManager.CLOSE_FAILURE); }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { reportError(null, e, ErrorManager.FLUSH_FAILURE); }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { // Ignore }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { // Ignore and fallback to defaults setFormatter(new SimpleFormatter()); }
// in java/org/apache/juli/FileHandler.java
catch (Exception e) { reportError(null, e, ErrorManager.OPEN_FAILURE); writer = null; }
// in java/org/apache/juli/AsyncFileHandler.java
catch (Exception x) { x.printStackTrace(); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().error(sm.getString( "abstractProtocolHandler.mbeanRegistrationFailed", tpOname, getName()), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.initError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.startError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.pauseError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.resumeError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.stopError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().error(sm.getString("abstractProtocolHandler.destroyError", getName()), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().warn("Error registering request"); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception e) { getLog().warn("Error unregistering request", e); }
// in java/org/apache/coyote/ajp/Constants.java
catch (Exception e) { // Do nothing }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.info"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Exception e) { this.compressionLevel = 0; }
// in java/org/apache/coyote/http11/Http11Processor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/Http11Processor.java
catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); }
// in java/org/apache/coyote/http11/AbstractHttp11Protocol.java
catch (Exception ex) { getLog().warn("Failed to init light protocol " + impl, ex); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Exception e) { //TODO Auto-generated catch block e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Exception e) { noApr = new IOException("APR not present", e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Exception ex) { // ignore - the acceptor may have shut down by itself. }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
catch (Exception e) { e.printStackTrace(); }
// in java/org/apache/tomcat/util/net/URL.java
catch (Exception e) { throw new MalformedURLException(e.toString()); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
catch (Exception cx) { IOException x = new IOException(cx); throw x; }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
catch (Exception ignore) {}
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
catch (Exception ignore) {}
// in java/org/apache/tomcat/util/net/SSLImplementation.java
catch (Exception e) { if (logger.isTraceEnabled()) logger.trace("Error creating " + implementations[i], e); }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
catch (Exception e) { if (logger.isDebugEnabled()) logger .debug("Error loading SSL Implementation " + className, e); throw new ClassNotFoundException( "Error loading SSL Implementation " + className + " :" + e.toString()); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch( Exception ignore ) { if (log.isDebugEnabled())log.debug("",ignore); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch( Exception ignore ) { if (log.isDebugEnabled())log.debug("",ignore); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (Exception ignore){}
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Exception x ) { log.error("Unable to set attribute \""+name+"\" to \""+value+"\"",x); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception x) { log.error("", x); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (CancelledKeyException ckx) { try { socket.getPoller().cancelledKey(key,SocketStatus.DISCONNECT); }catch (Exception ignore) {} }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception ignore) {}
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "endpoint.debug.channelCloseFail"), e); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception e){ if (log.isDebugEnabled()) { log.debug(sm.getString( "endpoint.debug.socketCloseFail"), e); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception ignore) { }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception ignore) { }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception ignore) { }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Exception ignore) { }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Exception x ) { log.error("",x); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { return -1; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw e; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { // Pool not created so no need to destroy it. log.error(sm.getString("endpoint.sendfile.error"), e); data.socket = 0; return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { log.error(sm.getString("endpoint.sendfile.error"), e); Pool.destroy(data.fdpool); data.socket = 0; return false; }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
catch ( Exception x ) { getLog().error("Unable to set attribute \""+name+"\" to \""+value+"\"",x); return false; }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
catch(Exception e) { if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("endpoint.debug.unlock", "" + getPort()), e); } }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
catch (Exception e) { // Ignore }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Exception e) { log.error(sm.getString("endpoint.err.close"), e); }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch(Exception ex) { log.info(sm.getString( "jseeSupport.certTranslationError", certs[i]), ex); return null; }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch(Exception bex) { // ignore. }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception e) { if( e instanceof IOException ) throw (IOException)e; throw new IOException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception ex) { log.warn("Bad maxCertLength: "+trustLength); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception ex) { // Ignore }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (Exception e) { /* * Possible ways of getting here * socket.accept() throws a SecurityException * socket.setSoTimeout() throws a SocketException * socket.accept() throws some other exception (after a JDK change) * In these cases the test won't work so carry on - essentially * the behaviour before this patch * socket.accept() throws a SocketTimeoutException * In this case all is well so carry on */ }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (Exception e) { // ignore it }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (Exception e) { return -1; }
// in java/org/apache/tomcat/util/http/fileupload/FileCleaningTracker.java
catch (Exception e) { continue; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (Exception e) { }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (Exception e) { ex=e; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (Exception e) { throw new MBeanException (e, "Cannot instantiate ModelMBean of class " + getClassName()); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { // Not having a particular attribute in the response // is the indication of a getter problem }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch(Exception ex) { log.error("Error sending notification " + name, ex); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { // Ignore all exceptions }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsSerSource.java
catch( Exception ex ) { log.error( "Error reading descriptors " + source + " " + ex.toString(), ex); throw ex; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java
catch (Exception e) { log.error("Error digesting Registry data", e); throw e; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsIntrospectionSource.java
catch( Exception ex ) { log.error( "Error reading descriptors ", ex); }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsIntrospectionSource.java
catch( Exception ex ) { ex.printStackTrace(); return null; }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Exception t ) { if( failFirst ) throw t; log.info("Error initializing " + current + " " + t.toString()); }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch (Exception e) { log.info( "Can't find metadata for object" + oname ); return null; }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch (Exception e) { log.info( "Can't find metadata " + oname ); return null; }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Exception ex) { log.error("Error registering " + oname, ex ); throw ex; }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch(Exception ex ) { log.error("Error loading " + dURL); }
// in java/org/apache/tomcat/util/digester/FactoryCreateRule.java
catch (Exception e) { // log message and error if (digester.log.isInfoEnabled()) { digester.log.info("[FactoryCreateRule] Create exception ignored: " + ((e.getMessage() == null) ? e.getClass().getName() : e.getMessage())); if (digester.log.isDebugEnabled()) { digester.log.debug("[FactoryCreateRule] Ignored exception:", e); } } exceptionIgnoredStack.push(Boolean.TRUE); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Digester.getParser: ", e); return (null); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Finish event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Body event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("End event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Begin event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { // ignore - let the attribute have its original value }
// in java/org/apache/tomcat/util/digester/Digester.java
catch(Exception e) { return bodyText; // return unchanged data }
// in java/org/apache/tomcat/util/digester/XercesParser.java
catch (Exception ex){ // Do nothing. }
// in java/org/apache/tomcat/util/digester/ParserFeatureSetterFactory.java
catch (Exception ex){ isXercesUsed = false; }
// in java/org/apache/el/lang/FunctionMapperImpl.java
catch (Exception e) { e.printStackTrace(); }
// in java/org/apache/el/lang/ExpressionBuilder.java
catch (Exception e) { throw new ELException( MessageFactory.get("error.parseFail", expr), e); }
// in java/org/apache/el/lang/ExpressionBuilder.java
catch (Exception e) { if (e instanceof ELException) { throw (ELException) e; } else { throw (new ELException(e)); } }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString("contextConfig.contextMissing", contextXml) , e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString( "contextConfig.defaultError", filename, file), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Exception e) { log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e); ok = false; }
// in java/org/apache/catalina/startup/TldConfig.java
catch (Exception e) { log.error(sm.getString( "tldConfig.execute", context.getName()), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.threaded.error"), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", contextXml.getAbsolutePath())); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployWar.threaded.error"), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", war.getAbsolutePath())); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", war.getAbsolutePath())); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDir.threaded.error"), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", xml)); context = new FailedContext(); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.warn(sm.getString ("hostConfig.context.restart", app.name), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString("hostConfig.jmx.register", oname), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Exception e) { log.error(sm.getString("hostConfig.jmx.unregister", oname), e); }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage())); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { log.error("Catalina.stop: ", e); System.exit(1); }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", file), e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", getConfigFile()), e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", "server-embed.xml"), e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { log.warn("Catalina.start using " + getConfigFile() + ": " , e); return; }
// in java/org/apache/catalina/startup/Catalina.java
catch (Exception e) { e.printStackTrace(System.out); }
// in java/org/apache/catalina/startup/PasswdUserDatabase.java
catch (Exception e) { if (reader != null) { try { reader.close(); } catch (IOException f) { // Ignore } reader = null; } }
// in java/org/apache/catalina/startup/UserConfig.java
catch (Exception e) { host.getLogger().error(sm.getString("userConfig.database"), e); return; }
// in java/org/apache/catalina/startup/UserConfig.java
catch (Exception e) { host.getLogger().error(sm.getString("userConfig.deploy.threaded.error"), e); }
// in java/org/apache/catalina/startup/UserConfig.java
catch (Exception e) { host.getLogger().error(sm.getString("userConfig.error", user), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.jdbcRemoveFailed", contextName), t); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.stopTimerThreadFail", thread.getName(), contextName), t); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badKey", args[1]), e); args[2] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badValue", args[3]), e); args[4] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { return null; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception e) { clazz = null; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Exception e) { // Log and continue anyway, this is not critical log.error("Error registering jndi stream handler", e); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Exception e) { log.error("LifecycleException ", e); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Exception ex) { // Catch the exception if there is an empty jar file // Should ignore and continue loading other jar files // in the dir }
// in java/org/apache/catalina/loader/WebappLoader.java
catch( Exception ex ) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) log.debug("getClasspath ", ex); }
// in java/org/apache/catalina/realm/MemoryRealm.java
catch (Exception e) { log.warn(sm.getString("memoryRealm.xmlFeatureEncoding"), e); }
// in java/org/apache/catalina/realm/MemoryRealm.java
catch (Exception e) { throw new LifecycleException (sm.getString("memoryRealm.readXml"), e); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (Exception e) { connectionAttempt = 1; // log the first exception. containerLog.warn(sm.getString("jndiRealm.exception"), e); // Try connecting to the alternate url. context = new InitialDirContext(getDirectoryContextEnvironment()); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (Exception e) { // Log the problem for posterity containerLog.error(sm.getString("dataSourceRealm.exception"), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (Exception e) { if (log.isDebugEnabled()) log.debug(" Validity exception", e); return (null); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (Exception e) { log.error(sm.getString("realmBase.digest"), e); return (credentials); }
// in java/org/apache/catalina/realm/RealmBase.java
catch(Exception ex) { log.error(ex); return credentials; }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (Exception e) { log.warn("Error processing configuration file " + file.getAbsolutePath(), e); return; }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
catch (Exception e) { log.warn("Error during context [" + context.getName() + "] destroy ", e); }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
catch (Exception e) { log.error("Exception creating UserDatabase MBeans for " + name, e); }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating group [" + groupname + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating role [" + rolename + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating user [" + username + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying group [" + groupname + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying role [" + rolename + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying user [" + username + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (Exception ParseException) { // Ignore }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
catch (Exception e) { log.warn(sm.getString("memoryUserDatabase.xmlFeatureEncoding"), e); }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorEqualsCondition.java
catch (Exception e) { // ignore access or connection open errors }
// in java/org/apache/catalina/ant/jmx/JMXAccessorCondition.java
catch (Exception e) { // ignore access or connection open errors }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
catch (Exception e) { if (isEcho()) handleErrorOutput(e.getMessage()); return "Can't query mbeans " + qry; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
catch (Exception e) { if (isEcho()) handleErrorOutput("Error getting attribute " + oname + " " + pname + attName + " " + e.toString()); continue; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorQueryTask.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/ant/ValidatorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException("Validation failure", e); } else { handleErrorOutput("Validation failure: " + e); } }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (Exception e) { log("HTMLManagerServlet.sessions[" + cn + "]", e); message = smClient.getString("managerServlet.exception", e.toString()); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch(Exception e) { message = smClient.getString ("htmlManagerServlet.deployUploadFail", e.getMessage()); log(message, e); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (Exception e) { // Assume false on failure for safety isDeployed = false; }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch (Exception ex) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch( Exception ex ) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch (Exception ex) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); return; }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
catch( Exception ex ) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { getServletContext().log (sm.getString("hostManagerServlet.startFailed", name), e); writer.println(smClient.getString( "hostManagerServlet.startFailed", name)); writer.println(smClient.getString( "hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Exception e) { getServletContext().log(sm.getString( "hostManagerServlet.stopFailed", name), e); writer.println(smClient.getString("hostManagerServlet.stopFailed", name)); writer.println(smClient.getString("hostManagerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
catch (Exception e) { e.printStackTrace(); }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
catch (Exception e) { throw new ServletException(e); }
// in java/org/apache/catalina/manager/StatusTransformer.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/manager/JspHelper.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log(sm.getString("managerServlet.objectNameFail", name), e); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.storeConfig", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.save[" + path + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.check[" + displayPath + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Exception e) { log("managerServlet.check[" + displayPath + "]", e); writer.println(smClient.getString("managerServlet.exception", e.toString())); return; }
// in java/org/apache/catalina/manager/util/SessionUtils.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); // stay silent }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { if ( x instanceof ChannelException ) throw (ChannelException)x; throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch (Exception sx) { log.error("Unable to deserialize message:"+msg,sx); return; }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { //this could be the channel listener throwing an exception, we should log it //as a warning. if ( log.isWarnEnabled() ) log.warn("Error receiving message:",x); throw new RemoteProcessException("Exception:"+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { log.error("Unable to find rpc channel, failed to send NoRpcChannelReply.",x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch (Exception x) { throw new ChannelException("Unable to add MessageDispatchInterceptor to interceptor chain.",x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { log.error("Unable to send heartbeat through Tribes interceptor stack. Will try to sleep again.",x); }
// in java/org/apache/catalina/tribes/group/RpcChannel.java
catch ( Exception x ) { if (excallback != null && !asyncReply) { excallback.replyFailed(rmsg.message, reply, sender, x); } else { log.error("Unable to send back reply in RpcChannel.",x); } }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( Exception x ) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( Exception x ) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpPingInterceptor.java
catch ( Exception x ) { log.warn("Unable to send ping from TCP ping thread.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( Exception x ) { log.warn("Unable to perform heartbeat on the TcpFailureDetector.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch (Exception x ) { log.error("Unable to perform failure detection check, assuming member down.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( Exception ignore ){}
// in java/org/apache/catalina/tribes/group/interceptors/TwoPhaseCommitInterceptor.java
catch ( Exception x ) { log.warn("Unable to perform heartbeat on the TwoPhaseCommit interceptor.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( Exception x ){ log.error("Unable to perform heartbeat.",x); }
// in java/org/apache/catalina/tribes/group/interceptors/FragmentationInterceptor.java
catch ( Exception x ) { if ( log.isErrorEnabled() ) { log.error("Unable to perform heartbeat clean up in the frag interceptor",x); } }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
catch ( Exception ex ) { log.error("Unable to report back completed message.",ex); }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
catch ( Exception x ) { ChannelException cx = null; if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException(x); if ( log.isDebugEnabled() ) log.debug("Error while processing async message.",x); try { if (link.getHandler() != null) link.getHandler().handleError(cx, new UniqueId(msg.getUniqueId())); } catch ( Exception ex ) { log.error("Unable to report back error message.",ex); } }
// in java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
catch ( Exception ex ) { log.error("Unable to report back error message.",ex); }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch (Exception x) { if (tryRepFirst) return findExternalClass(name); else return findReplicationClass(name); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { if (log.isDebugEnabled()) { log.debug("Failed to close socket", x); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.error("Unable to run replication listener.", x); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch ( Exception x ) { if ( doListen() ) throw x; }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch ( Exception x ) { log.error("Unable to service bio socket", x); }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close socket", e); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close reader", e); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch ( Exception x ) { if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(Constants.FAIL_ACK_COMMAND); log.error("Error thrown from messageDataReceived.",x); }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close socket", e); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close reader", e); } }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
catch (Exception x) { if (cx == null) cx = new ChannelException(x); cx.addFaultyMember(destination[i],x); }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
catch (Exception x ) { if ( cx== null ) cx = new ChannelException(x); cx.addFaultyMember(destination[i],x); }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
catch ( Exception e ) { if ( x == null ) x = new ChannelException(e); x.addFaultyMember(mbr,e); }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
catch (Exception x){/* Ignore */}
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
catch ( Exception e){/* Ignore */}
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
catch ( Exception x){}
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
catch ( Exception x){}
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
catch ( Exception x){}
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
catch ( Exception x){}
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
catch ( Exception x ) { log.error("Unable to disconnect NioSender. msg="+x.getMessage()); if ( log.isDebugEnabled() ) log.debug("Unable to disconnect NioSender. msg="+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x ) { if (log.isTraceEnabled()) log.trace("Error sending message", x); int faulty = (cx == null)?0:cx.getFaultyMembers().length; if ( cx == null ) { if ( x instanceof ChannelException ) cx = (ChannelException)x; else cx = new ChannelException("Parallel NIO send failed.", x); } else { if (x instanceof ChannelException) cx.addFaultyMember( ( (ChannelException) x).getFaultyMembers()); } //count down the remaining on an error if (faulty<cx.getFaultyMembers().length) remaining -= (cx.getFaultyMembers().length-faulty); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x ) { try { this.disconnect(); } catch (Exception e) {/*Ignore*/} if ( x instanceof ChannelException ) throw (ChannelException)x; else throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception e) {/*Ignore*/}
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( Exception ignore){ state.setFailing(); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( Exception e ) { if ( x == null ) x = new ChannelException(e); x.addFaultyMember(mbr,e); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x){/*Ignore*/}
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( Exception e){/*Ignore*/}
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to close selector", e); } }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( Exception x ) { log.warn("Error during keepalive test for sender:"+sender,x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception e){/*Ignore*/}
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (Exception e) { //this is common, since the sockets on the other //end expire after a certain time. if ( e instanceof CancelledKeyException ) { //do nothing } else if ( e instanceof IOException ) { //dont spew out stack traces for IO exceptions unless debug is enabled. if (log.isDebugEnabled()) log.debug ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"].", e); else log.warn ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"]."); } else if ( log.isErrorEnabled() ) { //this is a real error, log it. log.error("Exception caught in TcpReplicationThread.drainChannel.",e); } cancelKey(key); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( Exception e ) { log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch (Exception x) { log.error("Error registering key for read:"+key,x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch ( Exception x ) { log.error("",x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception e) { if (log.isDebugEnabled()) log.debug("", e); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception iox) { if (log.isDebugEnabled()) log.debug("Unable to close datagram channel.",iox); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.error("Unable to close cluster receiver selector.", x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.error("Unable to run replication listener.", x); }
// in java/org/apache/catalina/tribes/transport/PooledSender.java
catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "PooledSender.senderDisconnectFail"), e); } }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( Exception ignore){}
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (Exception x) { log.error("Unable to apply diff to key:" + entry.getKey(), x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( Exception x ) { log.error("Unable to send AbstractReplicatedMap.ping message",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (Exception x) { log.error("Unable to replicate out data for a LazyReplicatedMap.get operation", x); return null; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( Exception ignore) { ignore.printStackTrace(); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( Exception x ) { log.error("Deserialization error of the MapMessage.key",x); return null; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( Exception x ) { log.error("Deserialization error of the MapMessage.value",x); return null; }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x ) { log.error("Unable to parse mcastTTL="+properties.getProperty("mcastTTL"),x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x ) { log.error("Unable to parse mcastSoTimeout="+properties.getProperty("mcastSoTimeout"),x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x) { log.error("Unable to stop the mcast service, level:"+svc+".",x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch (Exception x) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x ) { log.error("Unable to send payload update.",x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( Exception x ) { log.error("Unable to send domain update.",x); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception ignore){}
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception ignore){}
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (Exception x) { log.error("Unable to process member disappeared message.", x); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception x ) { if (x instanceof InterruptedException) interrupted(); else { if (errorCounter==0 && doRunReceiver) log.warn("Error receiving mcast package. Sleeping 500ms",x); else if (log.isDebugEnabled()) log.debug("Error receiving mcast package"+(doRunReceiver?". Sleeping 500ms":"."),x); if (doRunReceiver) { try { Thread.sleep(500); } catch ( Exception ignore ){} if ( (++errorCounter)>=recoveryCounter ) { errorCounter=0; RecoveryThread.recover(McastServiceImpl.this); } } } }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception ignore ){}
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception x ) { if (errorCounter==0) log.warn("Unable to send mcast message.",x); else log.debug("Unable to send mcast message.",x); if ( (++errorCounter)>=recoveryCounter ) { errorCounter=0; RecoveryThread.recover(McastServiceImpl.this); } }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch ( Exception ignore ) {}
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (Exception x) { log.warn("Recovery thread failed to stop membership service.", x); return false; }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (Exception x) { log.warn("Recovery thread failed to start membership service.", x); return false; }
// in java/org/apache/catalina/session/StoreBase.java
catch (Exception e) { manager.getContainer().getLogger().error("Session: "+keys[i]+"; ", e); try { remove(keys[i]); } catch (IOException e2) { manager.getContainer().getLogger().error("Error removing key", e2); } }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionCreated", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent( "afterSessionDestroyed", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/session/StandardSession.java
catch (Exception e) { manager.getContainer().getLogger().error( sm.getString("standardSession.logoutfail"), e); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { if (unbound != null) { context.fireContainerEvent( "afterSessionAttributeReplaced", listener); } else { context.fireContainerEvent("afterSessionAttributeAdded", listener); } } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionAttributeRemoved", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Exception e) { // Ignore }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (Exception e) { container.getLogger().warn( sm.getString("cometConnectionManagerValve.event"), e); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (Exception e) { req.getWrapper().getParent().getLogger().warn(sm.getString( "cometConnectionManagerValve.listenerEvent"), e); }
// in java/org/apache/catalina/valves/PersistentValve.java
catch (Exception e) { container.getLogger().error("deserializeError"); }
// in java/org/apache/catalina/valves/PersistentValve.java
catch (Exception ex) { hsess = null; }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", environment.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", resource.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", resourceLink.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", environment.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", resource.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", resourceLink.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", cr.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", ce.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", crl.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", crl.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", ce.getName()), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", cr.getName()), e); }
// in java/org/apache/catalina/ha/context/ReplicatedContext.java
catch ( Exception x ) { log.error("Unable to start ReplicatedContext",x); throw new LifecycleException("Failed to start ReplicatedContext",x); }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
catch (Exception x) { log.warn("Unable to load meta data for class:"+clazz.getName()); return false; }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
catch ( Exception x ) { log.warn("Unable to register default cluster implementation with JMX",x); return false; }
// in java/org/apache/catalina/ha/jmx/ClusterJmxHelper.java
catch ( Exception x ) { log.warn("Unable to unregister default cluster implementation with JMX",x); return false; }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (Exception e) { throw new Exception("bad ProxyList"); }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (Exception ex) { log.error("Unable to connect to proxy: " + ex); close(i); }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (Exception ex) { log.error("Unable to send collected load information to proxy: " + ex); close(i); }
// in java/org/apache/catalina/ha/backend/HeartbeatListener.java
catch (Exception ex) { log.error("Unable to initialize info collection: " + ex); coll = null; return; }
// in java/org/apache/catalina/ha/backend/HeartbeatListener.java
catch (Exception ex) { log.error("Unable to initialize Sender: " + ex); sender = null; return; }
// in java/org/apache/catalina/ha/backend/HeartbeatListener.java
catch (Exception ex) { log.error("Unable to collect load information: " + ex); coll = null; return; }
// in java/org/apache/catalina/ha/backend/HeartbeatListener.java
catch (Exception ex) { log.error("Unable to send colllected load information: " + ex); }
// in java/org/apache/catalina/ha/backend/MultiCastSender.java
catch (Exception ex) { log.error("Unable to use multicast: " + ex); s = null; return -1; }
// in java/org/apache/catalina/ha/backend/MultiCastSender.java
catch (Exception ex) { log.error("Unable to send colllected load information: " + ex); s.close(); s = null; return -1; }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
catch ( Exception x ) { log.error("Unable to remove element:",x); info = new AttributeInfo(type, action, name, value); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
catch ( Exception x ) { log.error("Unable to remove element",x); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
catch ( Exception x ) { log.error("Unable to remove element",x); info = new AttributeInfo(); }
// in java/org/apache/catalina/ha/session/BackupManager.java
catch ( Exception x ) { log.error(sm.getString("backupManager.startUnable", getName()),x); throw new LifecycleException(sm.getString("backupManager.startFailed", getName()),x); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Exception sleep) { // }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Exception sleep) { }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Exception x) { log.error(sm.getString("deltaManager.receiveMessage.error",getName()), x); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Exception sleep) { }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
catch (Exception ignore) { }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
catch (Exception ignore) { }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception e) { log.error(sm.getString("farmWarDeployer.mbeanNameFail", engine.getName(), hostname),e); return; }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception ex) { log.error(ex); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception ex) { log.error(ex); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception ex) { log.error(sm.getString("farmWarDeployer.removeFailLocal", contextName), ex); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception x) { log.error(sm.getString("farmWarDeployer.modRemoveFail"), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception x) { log.error(sm.getString("farmWarDeployer.modInstallFail"), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (Exception x) { log.error(sm.getString("farmWarDeployer.removeLocalFail"), x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to clone cluster manager, defaulting to org.apache.catalina.ha.session.DeltaManager", x); manager = new org.apache.catalina.ha.session.DeltaManager(); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to start cluster.", x); throw new LifecycleException(x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to stop cluster valve.", x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to send message through cluster sender.", x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to connect to replication system.", x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable remove cluster node from replication system.", x); }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
catch (Exception x) { // FIXME we have a lot of sends, but the trouble with one node stops the correct replication to other nodes! log.error(sm.getString("ReplicationValve.send.failure"), x); }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
catch ( Exception x ) { log.error(sm.getString("ReplicationValve.send.invalid.failure",invalidIds[i]),x); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { log.error(sm.getString( "coyoteConnector.protocolHandlerInstantiationFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { log.error(sm.getString ("coyoteConnector.protocolHandlerPauseFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { log.error(sm.getString ("coyoteConnector.protocolHandlerResumeFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerInitializationFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { String errPrefix = ""; if(this.service != null) { errPrefix += "service.getName(): \"" + this.service.getName() + "\"; "; } throw new LifecycleException (errPrefix + " " + sm.getString ("coyoteConnector.protocolHandlerStartFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerStopFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerDestroyFailed"), e); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch (Exception ex) { log.info(sm.getString("applicationFilterConfig.jmxRegisterFail", getFilterClass(), getFilterName()), ex); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
catch(Exception ex) { log.error(sm.getString( "applicationFilterConfig.jmxUnregisterFail", getFilterClass(), getFilterName()), ex); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Exception e) { // Should never happen log(sm.getString("applicationContext.mapping.error"), e); return (null); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Exception e) { // Unexpected log(sm.getString("applicationContext.lookup.error", path, getContextPath()), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Exception e) { // Unexpected log(sm.getString("applicationContext.lookup.error", path, getContextPath()), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.error(sm.getString("containerBase.threadedStartFailed"), e); fail = true; }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.error(sm.getString("containerBase.threadedStopFailed"), e); fail = true; }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.cluster", cluster), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.loader", loader), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.manager", manager), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.realm", realm), e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.valve", current), e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (Exception x) { //log.error("Async.dispatch",x); throw new RuntimeException(x); }
// in java/org/apache/catalina/core/ApplicationFilterFactory.java
catch (Exception e) { // Note: The try catch is there because getFilter has a lot of // declared exceptions. However, the filter is allocated much // earlier Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/ApplicationFilterFactory.java
catch (Exception e) { // Note: The try catch is there because getFilter has a lot of // declared exceptions. However, the filter is allocated much // earlier }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ handleException(ex); return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (Exception e) { logger.warn(sm.getString("naming.jmxRegistrationFailed", e)); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.startFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.pauseFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.stopFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { String message = sm.getString( "standardService.connector.initFailed", connector); log.error(message, e); if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) throw new LifecycleException(message); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { log.error(sm.getString( "standardService.connector.destroyfailed", connector), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Exception ex) { log.error("standardContext.clusterFail", ex); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch(Exception e) { log.error("Error manager.start()", e); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch( Exception ex ) { log.error( "Error reseting context " + this + " " + ex, ex ); }
// in java/org/apache/catalina/core/ApplicationPart.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch( Exception ex ) { log.info("Error registering JSP monitoring with jmx " + instance); }
// in java/org/apache/catalina/core/StandardEngine.java
catch(Exception ex) { log.warn(sm.getString("standardEngine.jvmRouteFail")); }
// in java/org/apache/catalina/core/ThreadLocalLeakPreventionListener.java
catch (Exception e) { String msg = sm.getString( "threadLocalLeakPreventionListener.lifecycleEvent.error", event); log.error(msg, e); }
// in java/org/apache/catalina/core/ThreadLocalLeakPreventionListener.java
catch (Exception e) { String msg = sm.getString( "threadLocalLeakPreventionListener.containerEvent.error", event); log.error(msg, e); }
// in java/org/apache/catalina/util/SchemaResolver.java
catch (Exception e) { throw new SAXException(e); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (Exception e) { log.error(sm.getString("sessionIdGenerator.random", secureRandomClass), e); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (Exception e) { log.warn(sm.getString("lifecycleMBeanBase.registerFail", obj, name), e); }
// in java/org/apache/catalina/util/URLEncoder.java
catch (Exception e) { e.printStackTrace(); writer = new OutputStreamWriter(buf); }
// in java/org/apache/catalina/security/SecurityConfig.java
catch (java.lang.Exception ex){ if (log.isDebugEnabled()){ log.debug("Unable to load properties using CatalinaProperties", ex); } }
// in java/javax/el/BeanELResolver.java
catch (Exception e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (Exception e) { throw new ELException(e); }
137
            
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JspException(e.getMessage(), t); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException ("error in invoking method", ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (Exception e) { if (writer != null) { try { writer.close(); writer = null; } catch (Exception e1) { // do nothing } } // Remove the generated .java file File file = new File(javaFileName); if (file.exists()) { if (!file.delete()) { log.warn(Localizer.getMessage( "jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath())); } } throw e; }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage( "jsp.error.internal.tldinit", ex.getMessage()), ex); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { throw new SAXException( Localizer.getMessage("jsp.error.loadclass.taghandler", handlerClassName, qName), e); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { throw new SAXException(e); }
// in java/org/apache/jasper/compiler/TagPluginManager.java
catch (Exception e) { throw new JasperException(e); }
// in java/org/apache/jasper/compiler/JspConfig.java
catch (Exception ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JasperException(t); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (Exception ex) { JasperException je = new JasperException( Localizer.getMessage("jsp.error.unable.compile"), ex); // Cache compilation exception jsw.setCompilationException(je); throw je; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); }
// in java/org/apache/jasper/JspC.java
catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); }
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
catch (Exception e) { throw new ServiceException(e); }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (Exception e) { if (e instanceof InvocationTargetException) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } } NamingException ex = new NamingException ("Error while reading Wsdl File"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
catch (Exception x) { if (x instanceof InvocationTargetException) { Throwable cause = x.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } if (cause instanceof Exception) { x = (Exception) cause; } } if (x instanceof NamingException) throw (NamingException)x; else { NamingException nx = new NamingException(x.getMessage()); nx.initCause(x); throw nx; } }
// in java/org/apache/naming/factory/ResourceFactory.java
catch (Exception e) { if (e instanceof NamingException) throw (NamingException) e; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/factory/ResourceFactory.java
catch (Exception e) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (Exception e) { NamingException ne = new NamingException(e.getMessage()); ne.initCause(e); throw ne; }
// in java/org/apache/naming/NamingContext.java
catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); }
// in java/org/apache/naming/resources/WARDirContext.java
catch (Exception e) { throw new IllegalArgumentException (sm.getString("warResources.invalidWar", e.getMessage())); }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (Exception e) { throw new IllegalArgumentException(sm.getString( "resources.invalidCache", cacheClassName), e); }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.initError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.startError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.pauseError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.resumeError", getName()), ex); throw ex; }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.stopError", getName()), ex); throw ex; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/util/net/URL.java
catch (Exception e) { throw new MalformedURLException(e.toString()); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
catch (Exception cx) { IOException x = new IOException(cx); throw x; }
// in java/org/apache/tomcat/util/net/SSLImplementation.java
catch (Exception e) { if (logger.isDebugEnabled()) logger .debug("Error loading SSL Implementation " + className, e); throw new ClassNotFoundException( "Error loading SSL Implementation " + className + " :" + e.toString()); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Exception e) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw e; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception e) { if( e instanceof IOException ) throw (IOException)e; throw new IOException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (Exception e) { throw new MBeanException (e, "Cannot instantiate ModelMBean of class " + getClassName()); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsSerSource.java
catch( Exception ex ) { log.error( "Error reading descriptors " + source + " " + ex.toString(), ex); throw ex; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java
catch (Exception e) { log.error("Error digesting Registry data", e); throw e; }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Exception t ) { if( failFirst ) throw t; log.info("Error initializing " + current + " " + t.toString()); }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Exception ex) { log.error("Error registering " + oname, ex ); throw ex; }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Finish event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Body event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("End event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { log.error("Begin event threw exception", e); throw createSAXException(e); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Exception e) { throw createSAXException(e); }
// in java/org/apache/el/lang/ExpressionBuilder.java
catch (Exception e) { throw new ELException( MessageFactory.get("error.parseFail", expr), e); }
// in java/org/apache/el/lang/ExpressionBuilder.java
catch (Exception e) { if (e instanceof ELException) { throw (ELException) e; } else { throw (new ELException(e)); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); }
// in java/org/apache/catalina/realm/MemoryRealm.java
catch (Exception e) { throw new LifecycleException (sm.getString("memoryRealm.readXml"), e); }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating group [" + groupname + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating role [" + rolename + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating user [" + username + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying group [" + groupname + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying role [" + rolename + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying user [" + username + "] MBean"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException(e); } else { handleErrorOutput(e.getMessage()); } }
// in java/org/apache/catalina/ant/ValidatorTask.java
catch (Exception e) { if (isFailOnError()) { throw new BuildException("Validation failure", e); } else { handleErrorOutput("Validation failure: " + e); } }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
catch (Exception e) { throw new ServletException(e); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { if ( x instanceof ChannelException ) throw (ChannelException)x; throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { //this could be the channel listener throwing an exception, we should log it //as a warning. if ( log.isWarnEnabled() ) log.warn("Error receiving message:",x); throw new RemoteProcessException("Exception:"+x.getMessage(),x); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch (Exception x) { throw new ChannelException("Unable to add MessageDispatchInterceptor to interceptor chain.",x); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( Exception x ) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
catch ( Exception x ) { throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch ( Exception x ) { if ( doListen() ) throw x; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x ) { try { this.disconnect(); } catch (Exception e) {/*Ignore*/} if ( x instanceof ChannelException ) throw (ChannelException)x; else throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch (Exception x) { throw new ChannelException(x); }
// in java/org/apache/catalina/ha/context/ReplicatedContext.java
catch ( Exception x ) { log.error("Unable to start ReplicatedContext",x); throw new LifecycleException("Failed to start ReplicatedContext",x); }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (Exception e) { throw new Exception("bad ProxyList"); }
// in java/org/apache/catalina/ha/session/BackupManager.java
catch ( Exception x ) { log.error(sm.getString("backupManager.startUnable", getName()),x); throw new LifecycleException(sm.getString("backupManager.startFailed", getName()),x); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to start cluster.", x); throw new LifecycleException(x); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerInitializationFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { String errPrefix = ""; if(this.service != null) { errPrefix += "service.getName(): \"" + this.service.getName() + "\"; "; } throw new LifecycleException (errPrefix + " " + sm.getString ("coyoteConnector.protocolHandlerStartFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerStopFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerDestroyFailed"), e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (Exception x) { //log.error("Async.dispatch",x); throw new RuntimeException(x); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { String message = sm.getString( "standardService.connector.initFailed", connector); log.error(message, e); if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) throw new LifecycleException(message); }
// in java/org/apache/catalina/core/ApplicationPart.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/catalina/util/SchemaResolver.java
catch (Exception e) { throw new SAXException(e); }
// in java/javax/el/BeanELResolver.java
catch (Exception e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (Exception e) { throw new ELException(e); }
8
unknown (Lib) FailedLoginException 0 0 0 1
            
// in java/org/apache/catalina/realm/JAASRealm.java
catch (FailedLoginException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.failedLogin", username)); return (null); }
0 0
unknown (Lib) FileNotFoundException 13
            
// in java/org/apache/jasper/compiler/JspUtil.java
public static InputStream getInputStream(String fname, JarFile jarFile, JspCompilationContext ctxt) throws IOException { InputStream in = null; if (jarFile != null) { String jarEntryName = fname.substring(1, fname.length()); ZipEntry jarEntry = jarFile.getEntry(jarEntryName); if (jarEntry == null) { throw new FileNotFoundException(Localizer.getMessage( "jsp.error.file.not.found", fname)); } in = jarFile.getInputStream(jarEntry); } else { in = ctxt.getResourceAsStream(fname); } if (in == null) { throw new FileNotFoundException(Localizer.getMessage( "jsp.error.file.not.found", fname)); } return in; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public Class<?> loadTagFile() throws JasperException { try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; ctxt.compile(); } } else { if (compileException != null) { throw compileException; } } if (reload) { tagHandlerClass = ctxt.load(); reload = false; } } catch (FileNotFoundException ex) { throw new JasperException(ex); } return tagHandlerClass; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile) throws ServletException, IOException, FileNotFoundException { Servlet servlet; try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if ((available > 0L) && (available < Long.MAX_VALUE)) { if (available > System.currentTimeMillis()) { response.setDateHeader("Retry-After", available); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, Localizer.getMessage("jsp.error.unavailable")); return; } // Wait period has expired. Reset. available = 0; } /* * (1) Compile */ if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; // The following sets reload to true, if necessary ctxt.compile(); } } else { if (compileException != null) { // Throw cached compilation exception throw compileException; } } /* * (2) (Re)load servlet class file */ servlet = getServlet(); // If a page is to be precompiled only, return. if (precompile) { return; } } catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; } catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } try { /* * (3) Handle limitation of number of loaded Jsps */ if (unloadAllowed) { synchronized(this) { if (unloadByCount) { if (unloadHandle == null) { unloadHandle = ctxt.getRuntimeContext().push(this); } else if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { ctxt.getRuntimeContext().makeYoungest(unloadHandle); lastUsageTime = System.currentTimeMillis(); } } else { if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { lastUsageTime = System.currentTimeMillis(); } } } } /* * (4) Service request */ if (servlet instanceof SingleThreadModel) { // sync on the wrapper so that the freshness // of the page is determined right before servicing synchronized (this) { servlet.service(request, response); } } else { servlet.service(request, response); } } catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); } catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } }
// in java/org/apache/jasper/JspCompilationContext.java
public void compile() throws JasperException, FileNotFoundException { createCompiler(); if (jspCompiler.isOutDated()) { if (isRemoved()) { throw new FileNotFoundException(jspUri); } try { jspCompiler.removeGeneratedFiles(); jspLoader = null; jspCompiler.compile(); jsw.setReload(true); jsw.setCompilationException(null); } catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; } catch (FileNotFoundException fnfe) { // Re-throw to let caller handle this - will result in a 404 throw fnfe; } catch (Exception ex) { JasperException je = new JasperException( Localizer.getMessage("jsp.error.unable.compile"), ex); // Cache compilation exception jsw.setCompilationException(je); throw je; } } }
// in java/org/apache/naming/resources/DirContextURLConnection.java
Override public Object getContent() throws IOException { if (!connected) connect(); if (resource != null) return getInputStream(); if (collection != null) return collection; if (object != null) return object; throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); }
// in java/org/apache/naming/resources/DirContextURLConnection.java
Override public InputStream getInputStream() throws IOException { if (!connected) connect(); if (resource == null) { throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); } // Reopen resource try { resource = (Resource) context.lookup( URLDecoder.decode(getURL().getFile(), "UTF-8")); } catch (NamingException e) { // Ignore } return (resource.streamContent()); }
// in java/org/apache/naming/resources/DirContextURLConnection.java
public Enumeration<String> list() throws IOException { if (!connected) { connect(); } if ((resource == null) && (collection == null)) { throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); } Vector<String> result = new Vector<String>(); if (collection != null) { try { String file = getURL().getFile(); // This will be of the form /<hostname>/<contextpath>/file name // if <contextpath> is not empty otherwise this will be of the // form /<hostname>/file name // Strip off the hostname and the contextpath (note that context // path may contain '/' int start; if (context instanceof ProxyDirContext) { String cp = ((ProxyDirContext)context).getContextPath(); String h = ((ProxyDirContext)context).getHostName(); if ("".equals(cp)) { start = h.length() + 2; } else { start = h.length() + cp.length() + 2; } } else { start = file.indexOf('/', file.indexOf('/', 1) + 1); } NamingEnumeration<NameClassPair> enumeration = context.list(file.substring(start)); while (enumeration.hasMoreElements()) { NameClassPair ncp = enumeration.nextElement(); result.addElement( URLEncoder.encode(ncp.getName(), "UTF-8")); } } catch (NamingException e) { // Unexpected exception throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); } } return result.elements(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void forceDelete(File file) throws IOException { if (file.isDirectory()) { deleteDirectory(file); } else { boolean filePresent = file.exists(); if (!file.delete()) { if (!filePresent){ throw new FileNotFoundException("File does not exist: " + file); } String message = "Unable to delete file: " + file; throw new IOException(message); } } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException { boolean serveContent = content; // Identify the requested resource path String path = getRelativePath(request); if (debug > 0) { if (serveContent) log("DefaultServlet.serveResource: Serving resource '" + path + "' headers and data"); else log("DefaultServlet.serveResource: Serving resource '" + path + "' headers only"); } CacheEntry cacheEntry = resources.lookupCache(path); if (!cacheEntry.exists) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } else { // We're included // SRV.9.3 says we must throw a FNFE throw new FileNotFoundException( sm.getString("defaultServlet.missingResource", requestUri)); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } // If the resource is not a collection, and the resource path // ends with "/" or "\", return NOT FOUND if (cacheEntry.context == null) { if (path.endsWith("/") || (path.endsWith("\\"))) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } } boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST; // Check if the conditions specified in the optional If headers are // satisfied. if (cacheEntry.context == null) { // Checking If headers boolean included = (request.getAttribute( RequestDispatcher.INCLUDE_CONTEXT_PATH) != null); if (!included && !isError && !checkIfHeaders(request, response, cacheEntry.attributes)) { return; } } // Find content type. String contentType = cacheEntry.attributes.getMimeType(); if (contentType == null) { contentType = getServletContext().getMimeType(cacheEntry.name); cacheEntry.attributes.setMimeType(contentType); } ArrayList<Range> ranges = null; long contentLength = -1L; if (cacheEntry.context != null) { // Skip directory listings if we have been configured to // suppress them if (!listings) { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); return; } contentType = "text/html;charset=UTF-8"; } else { if (!isError) { if (useAcceptRanges) { // Accept ranges header response.setHeader("Accept-Ranges", "bytes"); } // Parse range specifier ranges = parseRange(request, response, cacheEntry.attributes); // ETag header response.setHeader("ETag", cacheEntry.attributes.getETag()); // Last-Modified header response.setHeader("Last-Modified", cacheEntry.attributes.getLastModifiedHttp()); } // Get content length contentLength = cacheEntry.attributes.getContentLength(); // Special case for zero length files, which would cause a // (silent) ISE when setting the output buffer size if (contentLength == 0L) { serveContent = false; } } ServletOutputStream ostream = null; PrintWriter writer = null; if (serveContent) { // Trying to retrieve the servlet output stream try { ostream = response.getOutputStream(); } catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } } } // Check to see if a Filter, Valve of wrapper has written some content. // If it has, disable range requests and setting of a content length // since neither can be done reliably. ServletResponse r = response; long contentWritten = 0; while (r instanceof ServletResponseWrapper) { r = ((ServletResponseWrapper) r).getResponse(); } if (r instanceof ResponseFacade) { contentWritten = ((ResponseFacade) r).getContentWritten(); } if (contentWritten > 0) { ranges = FULL; } if ( (cacheEntry.context != null) || isError || ( ((ranges == null) || (ranges.isEmpty())) && (request.getHeader("Range") == null) ) || (ranges == FULL) ) { // Set the appropriate output headers if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if ((cacheEntry.resource != null) && (contentLength >= 0) && (!serveContent || ostream != null)) { if (debug > 0) log("DefaultServlet.serveFile: contentLength=" + contentLength); // Don't set a content length if something else has already // written to the response. if (contentWritten == 0) { if (contentLength < Integer.MAX_VALUE) { response.setContentLength((int) contentLength); } else { // Set the content-length as String to be able to use a // long response.setHeader("content-length", "" + contentLength); } } } InputStream renderResult = null; if (cacheEntry.context != null) { if (serveContent) { // Serve the directory browser renderResult = render(getPathPrefix(request), cacheEntry); } } // Copy the input stream to our output stream (if requested) if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, contentLength, null)) copy(cacheEntry, renderResult, ostream); } else { copy(cacheEntry, renderResult, writer); } } } else { if ((ranges == null) || (ranges.isEmpty())) return; // Partial content response. response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); if (ranges.size() == 1) { Range range = ranges.get(0); response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; if (length < Integer.MAX_VALUE) { response.setContentLength((int) length); } else { // Set the content-length as String to be able to use a long response.setHeader("content-length", "" + length); } if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, range.end - range.start + 1, range)) copy(cacheEntry, ostream, range); } else { // we should not get here throw new IllegalStateException(); } } } else { response.setContentType("multipart/byteranges; boundary=" + mimeSeparation); if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { copy(cacheEntry, ostream, ranges.iterator(), contentType); } else { // we should not get here throw new IllegalStateException(); } } } } }
1
            
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException e) { // Unexpected exception throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); }
18
            
// in java/org/apache/jasper/compiler/Compiler.java
private ServletWriter setupContextWriter(String javaFileName) throws FileNotFoundException, JasperException { ServletWriter writer; // Setup the ServletWriter String javaEncoding = ctxt.getOptions().getJavaEncoding(); OutputStreamWriter osw = null; try { osw = new OutputStreamWriter( new FileOutputStream(javaFileName), javaEncoding); } catch (UnsupportedEncodingException ex) { errDispatcher.jspError("jsp.error.needAlternateJavaEncoding", javaEncoding); } writer = new ServletWriter(new PrintWriter(osw)); ctxt.setWriter(writer); return writer; }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile() throws FileNotFoundException, JasperException, Exception { compile(true); }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile(boolean compileClass) throws FileNotFoundException, JasperException, Exception { compile(compileClass, false); }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile(boolean compileClass, boolean jspcMode) throws FileNotFoundException, JasperException, Exception { if (errDispatcher == null) { this.errDispatcher = new ErrorDispatcher(jspcMode); } try { String[] smap = generateJava(); File javaFile = new File(ctxt.getServletJavaFileName()); Long jspLastModified = ctxt.getLastModified(ctxt.getJspFile()); javaFile.setLastModified(jspLastModified.longValue()); if (compileClass) { generateClass(smap); // Fix for bugzilla 41606 // Set JspServletWrapper.servletClassLastModifiedTime after successful compile String targetFileName = ctxt.getClassFileName(); if (targetFileName != null) { File targetFile = new File(targetFileName); if (targetFile.exists()) { targetFile.setLastModified(jspLastModified.longValue()); if (jsw != null) { jsw.setServletClassLastModifiedTime( jspLastModified.longValue()); } } } } } finally { if (tfp != null && ctxt.isPrototypeMode()) { tfp.removeProtoTypeFiles(null); } // Make sure these object which are only used during the // generation and compilation of the JSP page get // dereferenced so that they can be GC'd and reduce the // memory footprint. tfp = null; errDispatcher = null; pageInfo = null; // Only get rid of the pageNodes if in production. // In development mode, they are used for detailed // error messages. // http://issues.apache.org/bugzilla/show_bug.cgi?id=37062 if (!this.options.getDevelopment()) { pageNodes = null; } if (ctxt.getWriter() != null) { ctxt.getWriter().close(); ctxt.setWriter(null); } } }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parse(String inFileName) throws FileNotFoundException, JasperException, IOException { // If we're parsing a packaged tag file or a resource included by it // (using an include directive), ctxt.getTagFileJar() returns the // JAR file from which to read the tag file or included resource, // respectively. isTagFile = ctxt.isTagFile(); directiveOnly = false; return doParse(inFileName, null, ctxt.getTagFileJarResource()); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parseDirectives(String inFileName) throws FileNotFoundException, JasperException, IOException { // If we're parsing a packaged tag file or a resource included by it // (using an include directive), ctxt.getTagFileJar() returns the // JAR file from which to read the tag file or included resource, // respectively. isTagFile = ctxt.isTagFile(); directiveOnly = true; return doParse(inFileName, null, ctxt.getTagFileJarResource()); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parse(String inFileName, Node parent, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { // For files that are statically included, isTagfile and directiveOnly // remain unchanged. return doParse(inFileName, parent, jarResource); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parseTagFileDirectives(String inFileName, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { boolean isTagFileSave = isTagFile; boolean directiveOnlySave = directiveOnly; isTagFile = true; directiveOnly = true; Node.Nodes page = doParse(inFileName, null, jarResource); directiveOnly = directiveOnlySave; isTagFile = isTagFileSave; return page; }
// in java/org/apache/jasper/compiler/ParserController.java
private Node.Nodes doParse(String inFileName, Node parent, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { Node.Nodes parsedPage = null; isEncodingSpecifiedInProlog = false; isBomPresent = false; isDefaultPageEncoding = false; JarFile jarFile = (jarResource == null) ? null : jarResource.getJarFile(); String absFileName = resolveFileName(inFileName); String jspConfigPageEnc = getJspConfigPageEncoding(absFileName); // Figure out what type of JSP document and encoding type we are // dealing with determineSyntaxAndEncoding(absFileName, jarFile, jspConfigPageEnc); if (parent != null) { // Included resource, add to dependent list if (jarFile == null) { compiler.getPageInfo().addDependant(absFileName, ctxt.getLastModified(absFileName)); } else { String entry = absFileName.substring(1); compiler.getPageInfo().addDependant( jarResource.getEntry(entry).toString(), Long.valueOf(jarFile.getEntry(entry).getTime())); } } if ((isXml && isEncodingSpecifiedInProlog) || isBomPresent) { /* * Make sure the encoding explicitly specified in the XML * prolog (if any) matches that in the JSP config element * (if any), treating "UTF-16", "UTF-16BE", and "UTF-16LE" as * identical. */ if (jspConfigPageEnc != null && !jspConfigPageEnc.equals(sourceEnc) && (!jspConfigPageEnc.startsWith("UTF-16") || !sourceEnc.startsWith("UTF-16"))) { err.jspError("jsp.error.prolog_config_encoding_mismatch", sourceEnc, jspConfigPageEnc); } } // Dispatch to the appropriate parser if (isXml) { // JSP document (XML syntax) // InputStream for jspx page is created and properly closed in // JspDocumentParser. parsedPage = JspDocumentParser.parse(this, absFileName, jarFile, parent, isTagFile, directiveOnly, sourceEnc, jspConfigPageEnc, isEncodingSpecifiedInProlog, isBomPresent); } else { // Standard syntax InputStreamReader inStreamReader = null; try { inStreamReader = JspUtil.getReader(absFileName, sourceEnc, jarFile, ctxt, err, skip); JspReader jspReader = new JspReader(ctxt, absFileName, sourceEnc, inStreamReader, err); parsedPage = Parser.parse(this, jspReader, parent, isTagFile, directiveOnly, jarResource, sourceEnc, jspConfigPageEnc, isDefaultPageEncoding, isBomPresent); } finally { if (inStreamReader != null) { try { inStreamReader.close(); } catch (Exception any) { } } } } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } baseDirStack.pop(); return parsedPage; }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
private InputStream getResourceAsStream(String uri) throws FileNotFoundException { // Is uri absolute? if (uri.startsWith("file:")) { return new FileInputStream(new File(uri.substring(5))); } else { try { // see if file exists on the filesystem String real = ctxt.getRealPath(uri); if (real == null) { return ctxt.getResourceAsStream(uri); } else { return new FileInputStream(real); } } catch (FileNotFoundException ex) { // if file not found on filesystem, get the resource through // the context return ctxt.getResourceAsStream(uri); } } }
// in java/org/apache/jasper/compiler/JDTCompiler.java
Override protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception { long t1 = 0; if (log.isDebugEnabled()) { t1 = System.currentTimeMillis(); } final String sourceFile = ctxt.getServletJavaFileName(); final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath(); String packageName = ctxt.getServletPackageName(); final String targetClassName = ((packageName.length() != 0) ? (packageName + ".") : "") + ctxt.getServletClassName(); final ClassLoader classLoader = ctxt.getJspLoader(); String[] fileNames = new String[] {sourceFile}; String[] classNames = new String[] {targetClassName}; final ArrayList<JavacErrorDetail> problemList = new ArrayList<JavacErrorDetail>(); class CompilationUnit implements ICompilationUnit { private final String className; private final String sourceFile; CompilationUnit(String sourceFile, String className) { this.className = className; this.sourceFile = sourceFile; } @Override public char[] getFileName() { return sourceFile.toCharArray(); } @Override public char[] getContents() { char[] result = null; FileInputStream is = null; InputStreamReader isr = null; Reader reader = null; try { is = new FileInputStream(sourceFile); isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding()); reader = new BufferedReader(isr); char[] chars = new char[8192]; StringBuilder buf = new StringBuilder(); int count; while ((count = reader.read(chars, 0, chars.length)) > 0) { buf.append(chars, 0, count); } result = new char[buf.length()]; buf.getChars(0, result.length, result, 0); } catch (IOException e) { log.error("Compilation error", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) {/*Ignore*/} } if (isr != null) { try { isr.close(); } catch (IOException ioe) {/*Ignore*/} } if (is != null) { try { is.close(); } catch (IOException exc) {/*Ignore*/} } } return result; } @Override public char[] getMainTypeName() { int dot = className.lastIndexOf('.'); if (dot > 0) { return className.substring(dot + 1).toCharArray(); } return className.toCharArray(); } @Override public char[][] getPackageName() { StringTokenizer izer = new StringTokenizer(className, "."); char[][] result = new char[izer.countTokens()-1][]; for (int i = 0; i < result.length; i++) { String tok = izer.nextToken(); result[i] = tok.toCharArray(); } return result; } @SuppressWarnings("unused") // New method added to interface in // later JDT versions public boolean ignoreOptionalProblems() { return false; } }
// in java/org/apache/jasper/compiler/AntCompiler.java
Override protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception { long t1 = 0; if (log.isDebugEnabled()) { t1 = System.currentTimeMillis(); } String javaEncoding = ctxt.getOptions().getJavaEncoding(); String javaFileName = ctxt.getServletJavaFileName(); String classpath = ctxt.getClassPath(); String sep = System.getProperty("path.separator"); StringBuilder errorReport = new StringBuilder(); StringBuilder info=new StringBuilder(); info.append("Compile: javaFileName=" + javaFileName + "\n" ); info.append(" classpath=" + classpath + "\n" ); // Start capturing the System.err output for this thread SystemLogHandler.setThread(); // Initializing javac task getProject(); Javac javac = (Javac) project.createTask("javac"); // Initializing classpath Path path = new Path(project); path.setPath(System.getProperty("java.class.path")); info.append(" cp=" + System.getProperty("java.class.path") + "\n"); StringTokenizer tokenizer = new StringTokenizer(classpath, sep); while (tokenizer.hasMoreElements()) { String pathElement = tokenizer.nextToken(); File repository = new File(pathElement); path.setLocation(repository); info.append(" cp=" + repository + "\n"); } if( log.isDebugEnabled() ) log.debug( "Using classpath: " + System.getProperty("java.class.path") + sep + classpath); // Initializing sourcepath Path srcPath = new Path(project); srcPath.setLocation(options.getScratchDir()); info.append(" work dir=" + options.getScratchDir() + "\n"); // Initialize and set java extensions String exts = System.getProperty("java.ext.dirs"); if (exts != null) { Path extdirs = new Path(project); extdirs.setPath(exts); javac.setExtdirs(extdirs); info.append(" extension dir=" + exts + "\n"); } // Add endorsed directories if any are specified and we're forking // See Bugzilla 31257 if(ctxt.getOptions().getFork()) { String endorsed = System.getProperty("java.endorsed.dirs"); if(endorsed != null) { Javac.ImplementationSpecificArgument endorsedArg = javac.createCompilerArg(); endorsedArg.setLine("-J-Djava.endorsed.dirs=" + quotePathList(endorsed)); info.append(" endorsed dir=" + quotePathList(endorsed) + "\n"); } else { info.append(" no endorsed dirs specified\n"); } } // Configure the compiler object javac.setEncoding(javaEncoding); javac.setClasspath(path); javac.setDebug(ctxt.getOptions().getClassDebugInfo()); javac.setSrcdir(srcPath); javac.setTempdir(options.getScratchDir()); javac.setOptimize(! ctxt.getOptions().getClassDebugInfo() ); javac.setFork(ctxt.getOptions().getFork()); info.append(" srcDir=" + srcPath + "\n" ); // Set the Java compiler to use if (options.getCompiler() != null) { javac.setCompiler(options.getCompiler()); info.append(" compiler=" + options.getCompiler() + "\n"); } if (options.getCompilerTargetVM() != null) { javac.setTarget(options.getCompilerTargetVM()); info.append(" compilerTargetVM=" + options.getCompilerTargetVM() + "\n"); } if (options.getCompilerSourceVM() != null) { javac.setSource(options.getCompilerSourceVM()); info.append(" compilerSourceVM=" + options.getCompilerSourceVM() + "\n"); } // Build includes path PatternSet.NameEntry includes = javac.createInclude(); includes.setName(ctxt.getJavaPath()); info.append(" include="+ ctxt.getJavaPath() + "\n" ); BuildException be = null; try { if (ctxt.getOptions().getFork()) { javac.execute(); } else { synchronized(javacLock) { javac.execute(); } } } catch (BuildException e) { be = e; log.error(Localizer.getMessage("jsp.error.javac"), e); log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString()); } errorReport.append(logger.getReport()); // Stop capturing the System.err output for this thread String errorCapture = SystemLogHandler.unsetThread(); if (errorCapture != null) { errorReport.append(Constants.NEWLINE); errorReport.append(errorCapture); } if (!ctxt.keepGenerated()) { File javaFile = new File(javaFileName); javaFile.delete(); } if (be != null) { String errorReportString = errorReport.toString(); log.error(Localizer.getMessage("jsp.error.compilation", javaFileName, errorReportString)); JavacErrorDetail[] javacErrors = ErrorDispatcher.parseJavacErrors( errorReportString, javaFileName, pageNodes); if (javacErrors != null) { errDispatcher.javacError(javacErrors); } else { errDispatcher.javacError(errorReportString, be); } } if( log.isDebugEnabled() ) { long t2 = System.currentTimeMillis(); log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2-t1) + "ms"); } logger = null; project = null; if (ctxt.isPrototypeMode()) { return; } // JSR45 Support if (! options.isSmapSuppressed()) { SmapUtil.installSmap(smap); } }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile) throws ServletException, IOException, FileNotFoundException { Servlet servlet; try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if ((available > 0L) && (available < Long.MAX_VALUE)) { if (available > System.currentTimeMillis()) { response.setDateHeader("Retry-After", available); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, Localizer.getMessage("jsp.error.unavailable")); return; } // Wait period has expired. Reset. available = 0; } /* * (1) Compile */ if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; // The following sets reload to true, if necessary ctxt.compile(); } } else { if (compileException != null) { // Throw cached compilation exception throw compileException; } } /* * (2) (Re)load servlet class file */ servlet = getServlet(); // If a page is to be precompiled only, return. if (precompile) { return; } } catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; } catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } try { /* * (3) Handle limitation of number of loaded Jsps */ if (unloadAllowed) { synchronized(this) { if (unloadByCount) { if (unloadHandle == null) { unloadHandle = ctxt.getRuntimeContext().push(this); } else if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { ctxt.getRuntimeContext().makeYoungest(unloadHandle); lastUsageTime = System.currentTimeMillis(); } } else { if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { lastUsageTime = System.currentTimeMillis(); } } } } /* * (4) Service request */ if (servlet instanceof SingleThreadModel) { // sync on the wrapper so that the freshness // of the page is determined right before servicing synchronized (this) { servlet.service(request, response); } } else { servlet.service(request, response); } } catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); } catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } }
// in java/org/apache/jasper/JspCompilationContext.java
public void compile() throws JasperException, FileNotFoundException { createCompiler(); if (jspCompiler.isOutDated()) { if (isRemoved()) { throw new FileNotFoundException(jspUri); } try { jspCompiler.removeGeneratedFiles(); jspLoader = null; jspCompiler.compile(); jsw.setReload(true); jsw.setCompilationException(null); } catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; } catch (FileNotFoundException fnfe) { // Re-throw to let caller handle this - will result in a 404 throw fnfe; } catch (Exception ex) { JasperException je = new JasperException( Localizer.getMessage("jsp.error.unable.compile"), ex); // Cache compilation exception jsw.setCompilationException(je); throw je; } } }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public static FileMessageFactory getInstance(File f, boolean openForWrite) throws FileNotFoundException, IOException { return new FileMessageFactory(f, openForWrite); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
public synchronized FileMessageFactory getFactory(FileMessage msg) throws java.io.FileNotFoundException, java.io.IOException { File writeToFile = new File(getTempDir(), msg.getFileName()); FileMessageFactory factory = fileFactories.get(msg.getFileName()); if (factory == null) { factory = FileMessageFactory.getInstance(writeToFile, true); fileFactories.put(msg.getFileName(), factory); } return factory; }
16
            
// in java/org/apache/jasper/compiler/ParserController.java
catch (FileNotFoundException ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (FileNotFoundException ex) { // if file not found on filesystem, get the resource through // the context return ctxt.getResourceAsStream(uri); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (FileNotFoundException ex) { err.jspError(mark, "jsp.error.file.not.found", tldName); }
// in java/org/apache/jasper/compiler/Parser.java
catch (FileNotFoundException ex) { err.jspError(start, "jsp.error.file.not.found", file); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
catch (FileNotFoundException e) { err.jspError("jsp.error.file.not.found", path); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (FileNotFoundException fnfe) { throw new SAXParseException( Localizer.getMessage("jsp.error.file.not.found", fname), locator, fnfe); }
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch (FileNotFoundException ex) { ctxt.incrementRemoved(); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (FileNotFoundException ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (FileNotFoundException fnfe) { handleMissingResource(request, response, jspUri); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (FileNotFoundException fnfe) { // Re-throw to let caller handle this - will result in a 404 throw fnfe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (FileNotFoundException fnfe) { log.error(sm.getString("jsse.keystore_load_failed", type, path, fnfe.getMessage()), fnfe); throw fnfe; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (FileNotFoundException e) { log.error(sm.getString("contextConfig.altDDNotFound", altDDName)); }
// in java/org/apache/catalina/session/StandardManager.java
catch (FileNotFoundException e) { if (log.isDebugEnabled()) log.debug("No persisted data file found"); return; }
// in java/org/apache/catalina/session/FileStore.java
catch (FileNotFoundException e) { if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug("No persisted data file found"); return (null); }
// in java/javax/el/ExpressionFactory.java
catch (FileNotFoundException e) { // Should not happen - ignore it if it does }
6
            
// in java/org/apache/jasper/compiler/ParserController.java
catch (FileNotFoundException ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (FileNotFoundException fnfe) { throw new SAXParseException( Localizer.getMessage("jsp.error.file.not.found", fname), locator, fnfe); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (FileNotFoundException ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (FileNotFoundException fnfe) { // Re-throw to let caller handle this - will result in a 404 throw fnfe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (FileNotFoundException fnfe) { log.error(sm.getString("jsse.keystore_load_failed", type, path, fnfe.getMessage()), fnfe); throw fnfe; }
0
checked (Domain) FileSizeLimitExceededException
public static class FileSizeLimitExceededException
            extends SizeException {
        /** The exceptions UID, for serializing an instance.
         */
        private static final long serialVersionUID = 8150776562029630058L;

        /**
         * File name of the item, which caused the exception.
         */
        private String fileName;

        /**
         * Field name of the item, which caused the exception.
         */
        private String fieldName;

        /**
         * Constructs a <code>SizeExceededException</code> with
         * the specified detail message, and actual and permitted sizes.
         *
         * @param message   The detail message.
         * @param actual    The actual request size.
         * @param permitted The maximum permitted request size.
         */
        public FileSizeLimitExceededException(String message, long actual,
                long permitted) {
            super(message, actual, permitted);
        }

        /**
         * Returns the file name of the item, which caused the
         * exception.
         * @return File name, if known, or null.
         */
        public String getFileName() {
            return fileName;
        }

        /**
         * Sets the file name of the item, which caused the
         * exception.
         */
        public void setFileName(String pFileName) {
            fileName = pFileName;
        }

        /**
         * Returns the field name of the item, which caused the
         * exception.
         * @return Field name, if known, or null.
         */
        public String getFieldName() {
            return fieldName;
        }

        /**
         * Sets the field name of the item, which caused the
         * exception.
         */
        public void setFieldName(String pFieldName) {
            fieldName = pFieldName;
        }
    }
0 0 0 0 0 0
checked (Domain) FileUploadException
public class FileUploadException extends Exception {
    /**
     * Serial version UID, being used, if the exception
     * is serialized.
     */
    private static final long serialVersionUID = 8881893724388807504L;
    /**
     * The exceptions cause. We overwrite the cause of
     * the super class, which isn't available in Java 1.3.
     */
    private final Throwable cause;

    /**
     * Constructs a new <code>FileUploadException</code> without message.
     */
    public FileUploadException() {
        this(null, null);
    }

    /**
     * Constructs a new <code>FileUploadException</code> with specified detail
     * message.
     *
     * @param msg the error message.
     */
    public FileUploadException(final String msg) {
        this(msg, null);
    }

    /**
     * Creates a new <code>FileUploadException</code> with the given
     * detail message and cause.
     * @param msg The exceptions detail message.
     * @param cause The exceptions cause.
     */
    public FileUploadException(String msg, Throwable cause) {
        super(msg);
        this.cause = cause;
    }

    /**
     * Prints this throwable and its backtrace to the specified print stream.
     *
     * @param stream <code>PrintStream</code> to use for output
     */
    @Override
    public void printStackTrace(PrintStream stream) {
        super.printStackTrace(stream);
        if (cause != null) {
            stream.println("Caused by:");
            cause.printStackTrace(stream);
        }
    }

    /**
     * Prints this throwable and its backtrace to the specified
     * print writer.
     *
     * @param writer <code>PrintWriter</code> to use for output
     */
    @Override
    public void printStackTrace(PrintWriter writer) {
        super.printStackTrace(writer);
        if (cause != null) {
            writer.println("Caused by:");
            cause.printStackTrace(writer);
        }
    }

    @Override
    public Throwable getCause() {
        return cause;
    }
}
3
            
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
Override public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { // Save the length of the file size = outputFile.length(); /* * The uploaded file is being stored on disk * in a temporary location so move it to the * desired file. */ if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream( new FileInputStream(outputFile)); out = new BufferedOutputStream( new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } if (out != null) { try { out.close(); } catch (IOException e) { // ignore } } } } } else { /* * For whatever reason we cannot write the * file to disk. */ throw new FileUploadException( "Cannot write uploaded file to disk!"); } } }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
public List<FileItem> parseRequest(RequestContext ctx) throws FileUploadException { List<FileItem> items = new ArrayList<FileItem>(); boolean successful = false; try { FileItemIterator iter = getItemIterator(ctx); FileItemFactory fac = getFileItemFactory(); if (fac == null) { throw new NullPointerException( "No FileItemFactory has been set."); } while (iter.hasNext()) { final FileItemStream item = iter.next(); // Don't use getName() here to prevent an InvalidFileNameException. final String fileName = ((org.apache.tomcat.util.http.fileupload.FileUploadBase.FileItemIteratorImpl.FileItemStreamImpl) item).name; FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), fileName); items.add(fileItem); try { Streams.copy(item.openStream(), fileItem.getOutputStream(), true); } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); } if (fileItem instanceof FileItemHeadersSupport) { final FileItemHeaders fih = item.getHeaders(); ((FileItemHeadersSupport) fileItem).setHeaders(fih); } } successful = true; return items; } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new FileUploadException(e.getMessage(), e); } finally { if (!successful) { for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) { FileItem fileItem = iterator.next(); try { fileItem.delete(); } catch (Exception e) { // ignore it } } } } }
1
            
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new FileUploadException(e.getMessage(), e); }
7
            
// in java/org/apache/tomcat/util/http/fileupload/servlet/ServletFileUpload.java
public List<FileItem> parseRequest(HttpServletRequest request) throws FileUploadException { return parseRequest(new ServletRequestContext(request)); }
// in java/org/apache/tomcat/util/http/fileupload/servlet/ServletFileUpload.java
public FileItemIterator getItemIterator(HttpServletRequest request) throws FileUploadException, IOException { return super.getItemIterator(new ServletRequestContext(request)); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
public FileItemIterator getItemIterator(RequestContext ctx) throws FileUploadException, IOException { return new FileItemIteratorImpl(ctx); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
public List<FileItem> parseRequest(RequestContext ctx) throws FileUploadException { List<FileItem> items = new ArrayList<FileItem>(); boolean successful = false; try { FileItemIterator iter = getItemIterator(ctx); FileItemFactory fac = getFileItemFactory(); if (fac == null) { throw new NullPointerException( "No FileItemFactory has been set."); } while (iter.hasNext()) { final FileItemStream item = iter.next(); // Don't use getName() here to prevent an InvalidFileNameException. final String fileName = ((org.apache.tomcat.util.http.fileupload.FileUploadBase.FileItemIteratorImpl.FileItemStreamImpl) item).name; FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), fileName); items.add(fileItem); try { Streams.copy(item.openStream(), fileItem.getOutputStream(), true); } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); } if (fileItem instanceof FileItemHeadersSupport) { final FileItemHeaders fih = item.getHeaders(); ((FileItemHeadersSupport) fileItem).setHeaders(fih); } } successful = true; return items; } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new FileUploadException(e.getMessage(), e); } finally { if (!successful) { for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) { FileItem fileItem = iterator.next(); try { fileItem.delete(); } catch (Exception e) { // ignore it } } } } }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public boolean hasNext() throws FileUploadException, IOException { if (eof) { return false; } if (itemValid) { return true; } return findNextItem(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public FileItemStream next() throws FileUploadException, IOException { if (eof || (!itemValid && !hasNext())) { throw new NoSuchElementException(); } itemValid = false; return currentItem; }
1
            
// in java/org/apache/catalina/connector/Request.java
catch (FileUploadException e) { partsParseException = new IOException(e); }
0 0
checked (Domain) FileUploadIOException
public static class FileUploadIOException extends IOException {
        /** The exceptions UID, for serializing an instance.
         */
        private static final long serialVersionUID = -7047616958165584154L;
        /** The exceptions cause; we overwrite the parent
         * classes field, which is available since Java
         * 1.4 only.
         */
        private final FileUploadException cause;

        /**
         * Creates a <code>FileUploadIOException</code> with the
         * given cause.
         * @param pCause The exceptions cause, if any, or null.
         */
        public FileUploadIOException(FileUploadException pCause) {
            // We're not doing super(pCause) cause of 1.3 compatibility.
            cause = pCause;
        }

        /**
         * Returns the exceptions cause.
         * @return The exceptions cause, if any, or null.
         */
        @Override
        public Throwable getCause() {
            return cause;
        }
    }
3
            
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override protected void raiseError(long pSizeMax, long pCount) throws IOException { itemStream.close(true); FileSizeLimitExceededException e = new FileSizeLimitExceededException( "The field " + fieldName + " exceeds its maximum permitted " + " size of " + pSizeMax + " bytes.", pCount, pSizeMax); e.setFieldName(fieldName); e.setFileName(name); throw new FileUploadIOException(e); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override protected void raiseError(long pSizeMax, long pCount) throws IOException { FileUploadException ex = new SizeLimitExceededException( "the request was rejected because" + " its size (" + pCount + ") exceeds the configured maximum" + " (" + pSizeMax + ")", pCount, pSizeMax); throw new FileUploadIOException(ex); }
0 0 2
            
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); }
2
            
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); }
0
unknown (Lib) GSSException 0 0 1
            
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { // Have we already authenticated someone? Principal principal = request.getUserPrincipal(); String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (log.isDebugEnabled()) { log.debug("Already authenticated '" + principal.getName() + "'"); } // Associate the session with any existing SSO session if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return true; } // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) { log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); } /* Try to reauthenticate using data cached by SSO. If this fails, either the original SSO logon was of DIGEST or SSL (which we can't reauthenticate ourselves because there is no cached username and password), or the realm denied the user's reauthentication for some reason. In either case we have to prompt the user for a logon */ if (reauthenticateFromSSO(ssoId, request)) { return true; } } MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders() .getValue("authorization"); if (authorization == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("authenticator.noAuthHeader")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } authorization.toBytes(); ByteChunk authorizationBC = authorization.getByteChunk(); if (!authorizationBC.startsWithIgnoreCase("negotiate ", 0)) { if (log.isDebugEnabled()) { log.debug(sm.getString( "spnegoAuthenticator.authHeaderNotNego")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } authorizationBC.setOffset(authorizationBC.getOffset() + 10); // FIXME: Add trimming // authorizationBC.trim(); ByteChunk decoded = new ByteChunk(); Base64.decode(authorizationBC, decoded); if (decoded.getLength() == 0) { if (log.isDebugEnabled()) { log.debug(sm.getString( "spnegoAuthenticator.authHeaderNoToken")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } LoginContext lc = null; GSSContext gssContext = null; byte[] outToken = null; try { try { lc = new LoginContext(getLoginConfigName()); lc.login(); } catch (LoginException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; } // Assume the GSSContext is stateless // TODO: Confirm this assumption final GSSManager manager = GSSManager.getInstance(); final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() { @Override public GSSCredential run() throws GSSException { return manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME, new Oid("1.3.6.1.5.5.2"), GSSCredential.ACCEPT_ONLY); } }; gssContext = manager.createContext(Subject.doAs(lc.getSubject(), action)); outToken = gssContext.acceptSecContext(decoded.getBytes(), decoded.getOffset(), decoded.getLength()); if (outToken == null) { if (log.isDebugEnabled()) { log.debug(sm.getString( "spnegoAuthenticator.ticketValidateFail")); } // Start again response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } principal = context.getRealm().authenticate(gssContext, isStoreDelegatedCredential()); } catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail", e)); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } catch (PrivilegedActionException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail", e)); response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } finally { if (gssContext != null) { try { gssContext.dispose(); } catch (GSSException e) { // Ignore } } if (lc != null) { try { lc.logout(); } catch (LoginException e) { // Ignore } } } // Send response token on success and failure response.setHeader("WWW-Authenticate", "Negotiate " + Base64.encode(outToken)); if (principal != null) { register(request, response, principal, Constants.SPNEGO_METHOD, principal.getName(), null); return true; } response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
Override public GSSCredential run() throws GSSException { return manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME, new Oid("1.3.6.1.5.5.2"), GSSCredential.ACCEPT_ONLY); }
6
            
// in java/org/apache/catalina/realm/CombinedRealm.java
catch (GSSException e) { log.warn(sm.getString("realmBase.gssNameFail"), e); return null; }
// in java/org/apache/catalina/realm/LockOutRealm.java
catch (GSSException e) { log.warn(sm.getString("realmBase.gssNameFail"), e); return null; }
// in java/org/apache/catalina/realm/RealmBase.java
catch (GSSException e) { log.warn(sm.getString("realmBase.gssNameFail"), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "realmBase.delegatedCredentialFail", name), e); } }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail", e)); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (GSSException e) { // Ignore }
0 0
checked (Lib) IOException 205
            
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void clear() throws IOException { if (writer != null) { throw new IOException(); } else { nextChar = 0; if (LIMIT_BUFFER && (cb.length > Constants.DEFAULT_TAG_BUFFER_SIZE)) { cb = new char[Constants.DEFAULT_TAG_BUFFER_SIZE]; bufferSize = cb.length; } } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
private void ensureOpen() throws IOException { if (closed) throw new IOException("Stream closed"); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public final void clear() throws IOException { if ((bufferSize == 0) && (out != null)) // clear() is illegal after any unbuffered output (JSP.5.5) throw new IllegalStateException( getLocalizeMessage("jsp.error.ise_on_clear")); if (flushed) throw new IOException( getLocalizeMessage("jsp.error.attempt_to_clear_flushed_buffer")); ensureOpen(); nextChar = 0; }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
private final void bufferOverflow() throws IOException { throw new IOException(getLocalizeMessage("jsp.error.overflow")); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
private void ensureOpen() throws IOException { if (response == null || closed) throw new IOException("Stream closed"); }
// in java/org/apache/jasper/compiler/SmapUtil.java
static void install(File classFile, byte[] smap) throws IOException { File tmpFile = new File(classFile.getPath() + "tmp"); new SDEInstaller(classFile, smap, tmpFile); if (!classFile.delete()) { throw new IOException("classFile.delete() failed"); } if (!tmpFile.renameTo(classFile)) { throw new IOException("tmpFile.renameTo(classFile) failed"); } }
// in java/org/apache/jasper/compiler/SmapUtil.java
static byte[] readWhole(File input) throws IOException { FileInputStream inStream = new FileInputStream(input); int len = (int)input.length(); byte[] bytes = new byte[len]; if (inStream.read(bytes, 0, len) != len) { throw new IOException("expected size: " + len); } inStream.close(); return bytes; }
// in java/org/apache/jasper/compiler/SmapUtil.java
int copyConstantPool(int constantPoolCount) throws UnsupportedEncodingException, IOException { int sdeIndex = -1; // copy const pool index zero not in class file for (int i = 1; i < constantPoolCount; ++i) { int tag = readU1(); writeU1(tag); switch (tag) { case 7 : // Class case 8 : // String if (log.isDebugEnabled()) log.debug(i + " copying 2 bytes"); copy(2); break; case 9 : // Field case 10 : // Method case 11 : // InterfaceMethod case 3 : // Integer case 4 : // Float case 12 : // NameAndType if (log.isDebugEnabled()) log.debug(i + " copying 4 bytes"); copy(4); break; case 5 : // Long case 6 : // Double if (log.isDebugEnabled()) log.debug(i + " copying 8 bytes"); copy(8); i++; break; case 1 : // Utf8 int len = readU2(); writeU2(len); byte[] utf8 = readBytes(len); String str = new String(utf8, "UTF-8"); if (log.isDebugEnabled()) log.debug(i + " read class attr -- '" + str + "'"); if (str.equals(nameSDE)) { sdeIndex = i; } writeBytes(utf8); break; default : throw new IOException("unexpected tag: " + tag); } } return sdeIndex; }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private void tldScanStream(String resourcePath, String entryName, InputStream stream) throws IOException { try { // Parse the tag library descriptor at the specified resource path String uri = null; TreeNode tld = new ParserUtils().parseXMLDocument(resourcePath, stream); TreeNode uriNode = tld.findChild("uri"); if (uriNode != null) { String body = uriNode.getBody(); if (body != null) uri = body; } // Add implicit map entry only if its uri is not already // present in the map if (uri != null && mappings.get(uri) == null) { TldLocation location; if (entryName == null) { location = new TldLocation(resourcePath); } else { location = new TldLocation(entryName, resourcePath); } mappings.put(uri, location); } } catch (JasperException e) { // Hack - makes exception handling simpler throw new IOException(e); } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void createInitialReader() throws IOException, JasperException { // wrap this stream in RewindableInputStream stream = new RewindableInputStream(stream); // perform auto-detect of encoding if necessary if (encoding == null) { // read first four bytes and determine encoding final byte[] b4 = new byte[4]; int count = 0; for (; count<4; count++ ) { b4[count] = (byte)stream.read(); } if (count == 4) { Object [] encodingDesc = getEncodingName(b4, count); encoding = (String)(encodingDesc[0]); isBigEndian = (Boolean)(encodingDesc[1]); if (encodingDesc.length > 3) { isBomPresent = ((Boolean)(encodingDesc[2])).booleanValue(); skip = ((Integer)(encodingDesc[3])).intValue(); } else { isBomPresent = true; skip = ((Integer)(encodingDesc[2])).intValue(); } stream.reset(); // Special case UTF-8 files with BOM created by Microsoft // tools. It's more efficient to consume the BOM than make // the reader perform extra checks. -Ac if (count > 2 && encoding.equals("UTF-8")) { int b0 = b4[0] & 0xFF; int b1 = b4[1] & 0xFF; int b2 = b4[2] & 0xFF; if (b0 == 0xEF && b1 == 0xBB && b2 == 0xBF) { // ignore first three bytes... long skipped = stream.skip(3); if (skipped != 3) { throw new IOException(Localizer.getMessage( "xmlParser.skipBomFail")); } } } reader = createReader(stream, encoding, isBigEndian); } else { reader = createReader(stream, encoding, isBigEndian); } } }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public void mark(int readAheadLimit) throws IOException { throw new IOException( Localizer.getMessage("jsp.error.xml.operationNotSupported", "mark()", "UTF-8")); }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public int read() throws IOException { int b0 = fInputStream.read(); if (b0 > 0x80) { throw new IOException(Localizer.getMessage("jsp.error.xml.invalidASCII", Integer.toString(b0))); } return b0; }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public int read(char ch[], int offset, int length) throws IOException { if (length > fBuffer.length) { length = fBuffer.length; } int count = fInputStream.read(fBuffer, 0, length); for (int i = 0; i < count; i++) { int b0 = (0xff & fBuffer[i]); // Convert to unsigned if (b0 > 0x80) { throw new IOException(Localizer.getMessage("jsp.error.xml.invalidASCII", Integer.toString(b0))); } ch[offset + i] = (char)b0; } return count; }
// in java/org/apache/naming/resources/WARDirContext.java
Override public InputStream streamContent() throws IOException { try { if (binaryContent == null) { InputStream is = base.getInputStream(entry); inputStream = is; return is; } } catch (ZipException e) { throw new IOException(e.getMessage(), e); } return super.streamContent(); }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
Override protected void output(byte[] src, int offset, int length) throws IOException { outputBuffer.put(src, offset, length); long socketRef = socket.getSocket().longValue(); if (outputBuffer.position() > 0) { if ((socketRef != 0) && Socket.sendbb(socketRef, 0, outputBuffer.position()) < 0) { throw new IOException(sm.getString("ajpprocessor.failedsend")); } outputBuffer.clear(); } }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
protected boolean read(int n) throws IOException { if (inputBuffer.capacity() - inputBuffer.limit() <= n - inputBuffer.remaining()) { inputBuffer.compact(); inputBuffer.limit(inputBuffer.position()); inputBuffer.position(0); } int nRead; while (inputBuffer.remaining() < n) { nRead = Socket.recvbb (socket.getSocket().longValue(), inputBuffer.limit(), inputBuffer.capacity() - inputBuffer.limit()); if (nRead > 0) { inputBuffer.limit(inputBuffer.limit() + nRead); } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } } return true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
protected boolean readt(int n, boolean useAvailableData) throws IOException { if (useAvailableData && inputBuffer.remaining() == 0) { return false; } if (inputBuffer.capacity() - inputBuffer.limit() <= n - inputBuffer.remaining()) { inputBuffer.compact(); inputBuffer.limit(inputBuffer.position()); inputBuffer.position(0); } int nRead; while (inputBuffer.remaining() < n) { nRead = Socket.recvbb (socket.getSocket().longValue(), inputBuffer.limit(), inputBuffer.capacity() - inputBuffer.limit()); if (nRead > 0) { inputBuffer.limit(inputBuffer.limit() + nRead); } else { if ((-nRead) == Status.ETIMEDOUT || (-nRead) == Status.TIMEUP) { return false; } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } } } return true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
Override protected void output(byte[] src, int offset, int length) throws IOException { ByteBuffer writeBuffer = socket.getBufHandler() .getWriteBuffer(); writeBuffer.put(src, offset, length); writeBuffer.flip(); NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled"); long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { pool.write(writeBuffer, socket, selector, writeTimeout, true); }finally { if ( selector != null ) pool.put(selector); } writeBuffer.clear(); }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
protected int read(byte[] buf, int pos, int n, boolean blockFirstRead) throws IOException { int read = 0; int res = 0; boolean block = blockFirstRead; while (read < n) { res = readSocket(buf, read + pos, n, block); if (res > 0) { read += res; } else if (res == 0 && !block) { break; } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } block = true; } return read; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
private int readSocket(byte[] buf, int pos, int n, boolean block) throws IOException { int nRead = 0; socket.getBufHandler().getReadBuffer().clear(); socket.getBufHandler().getReadBuffer().limit(n); if ( block ) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled."); nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout()); } catch ( EOFException eof ) { nRead = -1; } finally { if ( selector != null ) pool.put(selector); } } else { nRead = socket.read(socket.getBufHandler().getReadBuffer()); } if (nRead > 0) { socket.getBufHandler().getReadBuffer().flip(); socket.getBufHandler().getReadBuffer().limit(nRead); socket.getBufHandler().getReadBuffer().get(buf, pos, nRead); return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("iib.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
protected int readMessage(AjpMessage message, boolean blockFirstRead) throws IOException { byte[] buf = message.getBuffer(); int headerLength = message.getHeaderLength(); int bytesRead = read(buf, 0, headerLength, blockFirstRead); if (bytesRead == 0) { return 0; } int messageLength = message.processHeader(true); if (messageLength < 0) { // Invalid AJP header signature throw new IOException(sm.getString("ajpmessage.invalidLength", Integer.valueOf(messageLength))); } else if (messageLength == 0) { // Zero length message. return bytesRead; } else { if (messageLength > buf.length) { // Message too long for the buffer // Need to trigger a 400 response throw new IllegalArgumentException(sm.getString( "ajpprocessor.header.tooLong", Integer.valueOf(messageLength), Integer.valueOf(buf.length))); } bytesRead += read(buf, headerLength, messageLength, true); return bytesRead; } }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public SocketState event(SocketStatus status) throws IOException { // Should never reach this code but in case we do... throw new IOException( sm.getString("ajpprocessor.comet.notsupported")); }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public SocketState upgradeDispatch() throws IOException { // Should never reach this code but in case we do... throw new IOException( sm.getString("ajpprocessor.httpupgrade.notsupported")); }
// in java/org/apache/coyote/ajp/AjpProcessor.java
protected boolean read(byte[] buf, int pos, int n) throws IOException { int read = 0; int res = 0; while (read < n) { res = input.read(buf, read + pos, n - read); if (res > 0) { read += res; } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } } return true; }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
private int readSocket(boolean timeout, boolean block) throws IOException { int nRead = 0; socket.getBufHandler().getReadBuffer().clear(); if ( block ) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled."); nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout()); } catch ( EOFException eof ) { nRead = -1; } finally { if ( selector != null ) pool.put(selector); } } else { nRead = socket.read(socket.getBufHandler().getReadBuffer()); } if (nRead > 0) { socket.getBufHandler().getReadBuffer().flip(); socket.getBufHandler().getReadBuffer().limit(nRead); expand(nRead + pos); socket.getBufHandler().getReadBuffer().get(buf, pos, nRead); lastValid = pos + nRead; return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("iib.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
Override public void flush() throws IOException { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) nioChannel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled"); } long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { do { if (nioChannel.flush(true, selector, writeTimeout)) { break; } } while (true); } finally { if (selector != null) { pool.put(selector); } } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
private int readSocket(boolean block, byte[] bytes, int offset, int len) throws IOException { int nRead = 0; nioChannel.getBufHandler().getReadBuffer().clear(); nioChannel.getBufHandler().getReadBuffer().limit(len); if (block) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) nioChannel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled."); } nRead = pool.read(nioChannel.getBufHandler().getReadBuffer(), nioChannel, selector, att.getTimeout()); } catch (EOFException eof) { nRead = -1; } finally { if (selector != null) { pool.put(selector); } } } else { nRead = nioChannel.read(nioChannel.getBufHandler().getReadBuffer()); } if (nRead > 0) { nioChannel.getBufHandler().getReadBuffer().flip(); nioChannel.getBufHandler().getReadBuffer().limit(nRead); nioChannel.getBufHandler().getReadBuffer().get(bytes, offset, nRead); return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("nio.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
private synchronized int writeToSocket(byte[] bytes, int off, int len) throws IOException { nioChannel.getBufHandler().getWriteBuffer().clear(); nioChannel.getBufHandler().getWriteBuffer().put(bytes, off, len); nioChannel.getBufHandler().getWriteBuffer().flip(); int written = 0; NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) nioChannel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled"); } long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { written = pool.write(nioChannel.getBufHandler().getWriteBuffer(), nioChannel, selector, writeTimeout, true); } finally { if (selector != null) { pool.put(selector); } } return written; }
// in java/org/apache/coyote/http11/upgrade/UpgradeAprProcessor.java
Override public int read(boolean block, byte[] bytes, int off, int len) throws IOException { if (!block) { Socket.optSet(socket, Socket.APR_SO_NONBLOCK, -1); } try { int result = Socket.recv(socket, bytes, off, len); if (result > 0) { return result; } else if (-result == Status.EAGAIN) { return 0; } else { throw new IOException(sm.getString("apr.error", Integer.valueOf(-result))); } } finally { if (!block) { Socket.optSet(socket, Socket.APR_SO_NONBLOCK, 0); } } }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
Override public int doRead(ByteChunk chunk, Request req) throws IOException { if (endChunk) return -1; if(needCRLFParse) { needCRLFParse = false; parseCRLF(); } if (remaining <= 0) { if (!parseChunkHeader()) { throw new IOException("Invalid chunk header"); } if (endChunk) { parseEndChunk(); return -1; } } int result = 0; if (pos >= lastValid) { readBytes(); } if (remaining > (lastValid - pos)) { result = lastValid - pos; remaining = remaining - result; chunk.setBytes(buf, pos, result); pos = lastValid; } else { result = remaining; chunk.setBytes(buf, pos, remaining); pos = pos + remaining; remaining = 0; //we need a CRLF if ((pos+1) >= lastValid) { //if we call parseCRLF we overrun the buffer here //so we defer it to the next call BZ 11117 needCRLFParse = true; } else { parseCRLF(); //parse the CRLF immediately } } return result; }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
protected boolean parseCRLF() throws IOException { boolean eol = false; boolean crfound = false; while (!eol) { if (pos >= lastValid) { if (readBytes() <= 0) throw new IOException("Invalid CRLF"); } if (buf[pos] == Constants.CR) { if (crfound) throw new IOException("Invalid CRLF, two CR characters encountered."); crfound = true; } else if (buf[pos] == Constants.LF) { if (!crfound) throw new IOException("Invalid CRLF, no CR character encountered."); eol = true; } else { throw new IOException("Invalid CRLF"); } pos++; } return true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
Override public SocketState upgradeDispatch() throws IOException { // Should never reach this code but in case we do... // TODO throw new IOException( sm.getString("TODO")); }
// in java/org/apache/coyote/http11/Http11Processor.java
Override public SocketState event(SocketStatus status) throws IOException { // Should never reach this code but in case we do... throw new IOException( sm.getString("http11processor.comet.notsupported")); }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
Override public void sendAck() throws IOException { if (!committed) { if (Socket.send(socket, Constants.ACK_BYTES, 0, Constants.ACK_BYTES.length) < 0) throw new IOException(sm.getString("iib.failedwrite")); } }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
private void flushBuffer() throws IOException { if (bbuf.position() > 0) { if (Socket.sendbb(socket, 0, bbuf.position()) < 0) { throw new IOException(); } bbuf.clear(); } }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
protected boolean fill() throws IOException { int nRead = 0; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.EAGAIN) { return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } else { if (buf.length - end < 4500) { // In this case, the request header was really large, so we allocate a // brand new one; the old one will get GCed when subsequent requests // clear all references buf = new byte[buf.length]; end = 0; } pos = end; lastValid = pos; bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.ETIMEDOUT || (-nRead) == Status.TIMEUP) { throw new SocketTimeoutException(sm.getString("iib.failedread")); } else if (nRead == 0) { // APR_STATUS_IS_EOF, since native 1.1.22 return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } return (nRead > 0); }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
private synchronized int writeToSocket(ByteBuffer bytebuffer, boolean block, boolean flip) throws IOException { if ( flip ) bytebuffer.flip(); int written = 0; NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled"); long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { written = pool.write(bytebuffer, socket, selector, writeTimeout, block); //make sure we are flushed do { if (socket.flush(true,selector,writeTimeout)) break; }while ( true ); }finally { if ( selector != null ) pool.put(selector); } if ( block ) bytebuffer.clear(); //only clear return written; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
Override public SocketState process(SocketWrapper<Object> socket) throws IOException { throw new IOException("Unimplemented"); }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
public void onSynStream(SpdyStream str) throws IOException { this.spdyStream = str; SpdyFrame frame = str.reqFrame; // We need to make a copy - the frame buffer will be reused. // We use the 'wrap' methods of MimeHeaders - which should be // lighter on mem in some cases. RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); // Request received. MimeHeaders mimeHeaders = request.getMimeHeaders(); for (int i = 0; i < frame.nvCount; i++) { int nameLen = frame.read16(); if (nameLen > frame.remaining()) { throw new IOException("Name too long"); } keyBuffer.setBytes(frame.data, frame.off, nameLen); if (keyBuffer.equals("method")) { frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } request.method().setBytes(frame.data, frame.off, valueLen); frame.advance(valueLen); } else if (keyBuffer.equals("url")) { frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } request.requestURI().setBytes(frame.data, frame.off, valueLen); if (SpdyContext.debug) { System.err.println("URL= " + request.requestURI()); } frame.advance(valueLen); } else if (keyBuffer.equals("version")) { frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } frame.advance(valueLen); } else { MessageBytes value = mimeHeaders.addValue(frame.data, frame.off, nameLen); frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } value.setBytes(frame.data, frame.off, valueLen); frame.advance(valueLen); } } onRequest(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public void listen(final int port) throws IOException { if (acceptor != null) { throw new IOException("Already accepting on " + acceptor.port); } if (sslMode && certFile == null) { throw new IOException("Missing certificates for server"); } if (sslMode || !nonBlockingAccept) { acceptorDispatch = new AcceptorDispatchThread(port); acceptorDispatch.setName("AprAcceptorDispatch-" + port); acceptorDispatch.start(); } acceptor = new AcceptorThread(port); acceptor.prepare(); acceptor.setName("AprAcceptor-" + port); acceptor.start(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
protected void connectBlocking(AprSocket apr) throws IOException { try { if (!running) { throw new IOException("Stopped"); } HostInfo hi = apr.getHost(); long clientSockP; synchronized (pollers) { long socketpool = Pool.create(getRootPool()); int family = Socket.APR_INET; clientSockP = Socket.create(family, Socket.SOCK_STREAM, Socket.APR_PROTO_TCP, socketpool); // or rootPool ? } Socket.timeoutSet(clientSockP, connectTimeout * 1000); if (OS.IS_UNIX) { Socket.optSet(clientSockP, Socket.APR_SO_REUSEADDR, 1); } Socket.optSet(clientSockP, Socket.APR_SO_KEEPALIVE, 1); // Blocking // TODO: use socket pool // TODO: cache it ( and TTL ) in hi long inetAddress = Address.info(hi.host, Socket.APR_INET, hi.port, 0, rootPool); // this may take a long time - stop/destroy must wait // at least connect timeout int rc = Socket.connect(clientSockP, inetAddress); if (rc != 0) { synchronized (pollers) { Socket.close(clientSockP); Socket.destroy(clientSockP); } /////Pool.destroy(socketpool); throw new IOException("Socket.connect(): " + rc + " " + Error.strerror(rc) + " " + connectTimeout); } if (!running) { throw new IOException("Stopped"); } connectionsCount.incrementAndGet(); if (tcpNoDelay) { Socket.optSet(clientSockP, Socket.APR_TCP_NODELAY, 1); } Socket.timeoutSet(clientSockP, defaultTimeout * 1000); apr.socket = clientSockP; apr.afterConnect(); } catch (IOException e) { apr.reset(); throw e; } catch (Throwable e) { apr.reset(); e.printStackTrace(); throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
long getSslCtx() throws Exception { if (sslCtx == 0) { synchronized (AprSocketContext.class) { boolean serverMode = acceptor != null; sslCtx = SSLContext.make(getRootPool(), sslProtocol, serverMode ? SSL.SSL_MODE_SERVER : SSL.SSL_MODE_CLIENT); // SSL.SSL_OP_NO_SSLv3 int opts = SSL.SSL_OP_NO_SSLv2 | SSL.SSL_OP_SINGLE_DH_USE; if (!USE_TICKETS || serverMode && ticketKey == null) { opts |= SSL.SSL_OP_NO_TICKET; } SSLContext.setOptions(sslCtx, opts); // Set revocation // SSLContext.setCARevocation(sslContext, SSLCARevocationFile, SSLCARevocationPath); // Client certificate verification - maybe make it option try { SSLContext.setCipherSuite(sslCtx, SSLCipherSuite); if (serverMode) { if (ticketKey != null) { //SSLExt.setTicketKeys(sslCtx, ticketKey, ticketKey.length); } if (certFile != null) { boolean rc = SSLContext.setCertificate(sslCtx, certFile, keyFile, null, SSL.SSL_AIDX_DSA); if (!rc) { throw new IOException("Can't set keys"); } } SSLContext.setVerify(sslCtx, SSL.SSL_CVERIFY_NONE, 10); if (spdyNPN != null) { SSLExt.setNPN(sslCtx, spdyNPN, spdyNPN.length); } } else { if (tlsCertVerifier != null) { // NONE ? SSLContext.setVerify(sslCtx, SSL.SSL_CVERIFY_NONE, 10); } else { SSLContext.setCACertificate(sslCtx, "/etc/ssl/certs/ca-certificates.crt", "/etc/ssl/certs"); SSLContext.setVerify(sslCtx, SSL.SSL_CVERIFY_REQUIRE, 10); } if (spdyNPN != null) { SSLExt.setNPN(sslCtx, spdyNPN, spdyNPN.length); } } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } long mode = SSLExt.sslCtxSetMode(sslCtx, SSLExt.SSL_MODE_ENABLE_PARTIAL_WRITE | SSLExt.SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); // TODO: try release buffers } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
void prepare() throws IOException { try { // Create the pool for the server socket serverSockPool = Pool.create(getRootPool()); int family = Socket.APR_INET; inetAddress = Address.info(addressStr, family, port, 0, serverSockPool); // Create the APR server socket serverSock = Socket.create(family, Socket.SOCK_STREAM, Socket.APR_PROTO_TCP, serverSockPool); if (OS.IS_UNIX) { Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Deal with the firewalls that tend to drop the inactive sockets Socket.optSet(serverSock, Socket.APR_SO_KEEPALIVE, 1); // Bind the server socket int ret = Socket.bind(serverSock, inetAddress); if (ret != 0) { throw new IOException("Socket.bind " + ret + " " + Error.strerror(ret) + " port=" + port); } // Start listening on the server socket ret = Socket.listen(serverSock, backlog ); if (ret != 0) { throw new IOException("endpoint.init.listen" + ret + " " + Error.strerror(ret)); } if (OS.IS_WIN32 || OS.IS_WIN64) { // On Windows set the reuseaddr flag after the bind/listen Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Sendfile usage on systems which don't support it cause major problems if (useSendfile && !Library.APR_HAS_SENDFILE) { useSendfile = false; } // Delay accepting of new connections until data is available // Only Linux kernels 2.4 + have that implemented // on other platforms this call is noop and will return APR_ENOTIMPL. if (deferAccept) { if (Socket.optSet(serverSock, Socket.APR_TCP_DEFER_ACCEPT, 1) == Status.APR_ENOTIMPL) { deferAccept = false; } } } catch (Throwable t) { throw new IOException(t); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
private void pollAdd(AprSocket up, int req) throws IOException { boolean failed = false; int rv; synchronized (channels) { if (up.isClosed()) { return; } rv = Poll.add(serverPollset, up.socket, req); if (rv != Status.APR_SUCCESS) { up.poller = null; keepAliveCount.decrementAndGet(); failed = true; } else { polledCount.incrementAndGet(); channels.put(up.socket, up); up.setStatus(AprSocket.POLL); } } if (failed) { up.reset(); throw new IOException("poll add error " + rv + " " + up + " " + Error.strerror(rv)); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int write(byte[] data, int off, int len, long to) throws IOException { long max = System.currentTimeMillis() + to; while (true) { int rc = writeInternal(data, off, len); if (rc < 0) { throw new IOException("Write error " + rc); } else if (rc == 0) { // need poll out - do we need to update polling ? context.findPollerAndAdd(this); } else { return rc; } try { long waitTime = max - System.currentTimeMillis(); if (waitTime <= 0) { return 0; } wait(waitTime); } catch (InterruptedException e) { return 0; } } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int write(byte[] data, int off, int len) throws IOException { // In SSL mode, read/write can't be called at the same time. int rc = writeInternal(data, off, len); if (rc < 0) { throw new IOException("Write error " + rc); } else if (rc == 0) { // need poll out - do we need to update polling ? synchronized (this) { context.findPollerAndAdd(this); } } return rc; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private int writeInternal(byte[] data, int off, int len) throws IOException { int rt = 0; int sent = 0; synchronized(this) { if ((status & CLOSED) != 0 || socket == 0 || !context.running) { throw new IOException("Closed"); } if ((status & WRITING) != 0) { throw new IOException("Write from 2 threads not allowed"); } status |= WRITING; while (len > 0) { sent = Socket.send(socket, data, off, len); if (sent <= 0) { break; } off += sent; len -= sent; } status &= ~WRITING; } if (context.rawDataHandler != null) { context.rawData(this, false, data, off, sent, len, false); } if (sent <= 0) { if (sent == -Status.TIMEUP || sent == -Status.EAGAIN || sent == 0) { setStatus(POLLOUT); updatePolling(); return rt; } if (context.debug) { log.warning("apr.send(): Failed to send, closing " + sent); } reset(); throw new IOException("Error sending " + sent + " " + Error.strerror(-sent)); } else { off += sent; len -= sent; rt += sent; return sent; } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private int processReadResult(byte[] data, int off, int len, int read) throws IOException { if (context.rawDataHandler != null) { context.rawData(this, true, data, off, read, len, false); } if (read > 0) { return read; } if (read == 0 || read == -Status.TIMEUP || read == -Status.ETIMEDOUT || read == -Status.EAGAIN) { read = 0; setStatus(POLLIN); updatePolling(); return 0; } if (read == -Status.APR_EOF || read == -1) { close(); return -1; } // abrupt close reset(); throw new IOException("apr.read(): " + read + " " + Error.strerror(-read)); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int readNB(byte[] data, int off, int len) throws IOException { int read; synchronized(this) { if ((status & CLOSED) != 0 || socket == 0 || !context.running) { return -1; } if ((status & READING) != 0) { throw new IOException("Read from 2 threads not allowed"); } status |= READING; read = Socket.recv(socket, data, off, len); status &= ~READING; } return processReadResult(data, off, len, read); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public long getIOTimeout() throws IOException { if (socket != 0 && context.running) { try { return Socket.timeoutGet(socket) / 1000; } catch (Exception e) { throw new IOException(e); } } else { throw new IOException("Socket is closed"); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public byte[][] getPeerCert(boolean check) throws IOException { getHost(); if (hostInfo.certs != null && hostInfo.certs != NO_CERTS && !check) { return hostInfo.certs; } if (!checkBitAndSocket(SSL_ATTACHED)) { return NO_CERTS; } try { int certLength = SSLSocket.getInfoI(socket, SSL.SSL_INFO_CLIENT_CERT_CHAIN); // TODO: if resumed, old certs are good. // If not - warn if certs changed, remember first cert, etc. if (certLength <= 0) { // Can also happen on session resume - keep the old if (hostInfo.certs == null) { hostInfo.certs = NO_CERTS; } return hostInfo.certs; } hostInfo.certs = new byte[certLength + 1][]; hostInfo.certs[0] = SSLSocket.getInfoB(socket, SSL.SSL_INFO_CLIENT_CERT); for (int i = 0; i < certLength; i++) { hostInfo.certs[i + 1] = SSLSocket.getInfoB(socket, SSL.SSL_INFO_CLIENT_CERT_CHAIN + i); } return hostInfo.certs; } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public X509Certificate[] getPeerX509Cert() throws IOException { byte[][] certs = getPeerCert(false); X509Certificate[] xcerts = new X509Certificate[certs.length]; if (certs.length == 0) { return xcerts; } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (int i = 0; i < certs.length; i++) { if (certs[i] != null) { ByteArrayInputStream bis = new ByteArrayInputStream( certs[i]); xcerts[i] = (X509Certificate) cf.generateCertificate(bis); bis.close(); } } } catch (CertificateException ex) { throw new IOException(ex); } return xcerts; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getCipherSuite() throws IOException { if (checkBitAndSocket(SSL_ATTACHED)) { return null; } try { return SSLSocket.getInfoS(socket, SSL.SSL_INFO_CIPHER); } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int getKeySize() throws IOException { if (checkBitAndSocket(SSL_ATTACHED)) { return -1; } try { return SSLSocket.getInfoI(socket, SSL.SSL_INFO_CIPHER_USEKEYSIZE); } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int getRemotePort() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_REMOTE, socket); Sockaddr addr = Address.getInfo(sa); return addr.port; } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getRemoteAddress() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_REMOTE, socket); return Address.getip(sa); } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getRemoteHostname() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_REMOTE, socket); String remoteHost = Address.getnameinfo(sa, 0); if (remoteHost == null) { remoteHost = Address.getip(sa); } return remoteHost; } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int getLocalPort() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_LOCAL, socket); Sockaddr addr = Address.getInfo(sa); return addr.port; } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getLocalAddress() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_LOCAL, socket); return Address.getip(sa); } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getLocalHostname() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_LOCAL, socket); return Address.getnameinfo(sa, 0); } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
void notifyIO() throws IOException { long t0 = System.currentTimeMillis(); try { if (handler != null) { handler.process(this, true, false, false); } } catch (Throwable t) { throw new IOException(t); } finally { long t1 = System.currentTimeMillis(); t1 -= t0; if (t1 > context.maxHandlerTime.get()) { context.maxHandlerTime.set(t1); } context.totalHandlerTime.addAndGet(t1); context.handlerCount.incrementAndGet(); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public void blockingStartTLS() throws IOException { synchronized(this) { if (socket == 0 || !context.running) { return; } if ((status & SSL_ATTACHED) != 0) { return; } status |= SSL_ATTACHED; } try { if (context.debug) { log.info(this + " StartSSL"); } AprSocketContext aprCon = context; SSLSocket.attach(aprCon.getSslCtx(), socket); if (context.debugSSL) { SSLExt.debug(socket); } if (!getContext().isServer()) { if (context.USE_TICKETS && hostInfo.ticketLen > 0) { SSLExt.setTicket(socket, hostInfo.ticket, hostInfo.ticketLen); } else if (hostInfo.sessDer != null) { SSLExt.setSessionData(socket, hostInfo.sessDer, hostInfo.sessDer.length); } } SSLExt.sslSetMode(socket, SSLExt.SSL_MODE_ENABLE_PARTIAL_WRITE | SSLExt.SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); int rc = SSLSocket.handshake(socket); // At this point we have the session ID, remote certs, etc // we can lookup host info if (hostInfo == null) { hostInfo = new HostInfo(); } if (rc != Status.APR_SUCCESS) { throw new IOException(this + " Handshake failed " + rc + " " + Error.strerror(rc) + " SSLL " + SSL.getLastError()); } else { // SUCCESS handshakeDone(); } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private void handshakeDone() throws IOException { getHost(); if (socket == 0 || !context.running) { throw new IOException("Socket closed"); } if (context.USE_TICKETS && ! context.isServer()) { if (hostInfo.ticket == null) { hostInfo.ticket = new byte[2048]; } int ticketLen = SSLExt.getTicket(socket, hostInfo.ticket); if (ticketLen > 0) { hostInfo.ticketLen = ticketLen; if (context.debug) { log.info("Received ticket: " + ticketLen); } } } // TODO: if the ticket, session id or session changed - callback to // save the session again try { hostInfo.sessDer = SSLExt.getSessionData(socket); getPeerCert(true); hostInfo.sessionId = SSLSocket.getInfoS(socket, SSL.SSL_INFO_SESSION_ID); } catch (Exception e) { throw new IOException(e); } hostInfo.npn = new byte[32]; hostInfo.npnLen = SSLExt.getNPN(socket, hostInfo.npn); // If custom verification is used - should check the certificates if (context.tlsCertVerifier != null) { context.tlsCertVerifier.handshakeDone(this); } }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public SpdyFrame getDataFrame(long to) throws IOException { while (true) { SpdyFrame res = getFrame(to); if (res == null || res.isData()) { return res; } if (res.type == SpdyConnection.TYPE_RST_STREAM) { throw new IOException("Reset"); } } }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public SpdyConnection getConnection(String host, int port) throws IOException { SpdyConnectionAprSocket spdy = new SpdyConnectionAprSocket(ctx); AprSocket ch = con.socket(host, port, ctx.tls); spdy.setSocket(ch); ch.connect(); ch.setHandler(new SpdySocketHandler(spdy)); // need to consume the input to receive more read events int rc = spdy.processInput(); if (rc == SpdyConnection.CLOSE) { ch.close(); throw new IOException("Error connecting"); } return spdy; }
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
Override public synchronized void decompress(SpdyFrame frame, int start) throws IOException { // stream id ( 4 ) + unused ( 2 ) // nvCount is compressed in impl - spec is different init(); if (decompressBuffer == null) { decompressBuffer = new byte[frame.data.length]; } // will read from dec buffer to frame.data decMax = frame.endData; decOff = start; int off = start; zipIn.setInput(frame.data, start, decMax - start); while (true) { int rd; try { rd = zipIn.inflate(decompressBuffer, off, decompressBuffer.length - off); if (rd == 0 && zipIn.needsDictionary()) { zipIn.setDictionary(SPDY_DICT); continue; } } catch (DataFormatException e) { throw new IOException(e); } if (rd == 0) { break; } if (rd == -1) { break; } off += rd; byte[] b = new byte[decompressBuffer.length * 2]; System.arraycopy(decompressBuffer, 0, b, 0, off); decompressBuffer = b; } byte[] tmpBuf = decompressBuffer; decompressBuffer = frame.data; frame.data = tmpBuf; frame.off = start; frame.endData = off; }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
protected Socket getSocket(String host, int port) throws IOException { try { if (ctx.tls) { SSLContext sslCtx = SSLContext.getDefault(); SSLSocket socket = (SSLSocket) sslCtx.getSocketFactory().createSocket(host, port); //socket.setEnabledProtocols(new String[] {"TLS1"}); socket.startHandshake(); return socket; } else { return new Socket(host, port); } } catch (NoSuchAlgorithmException e) { throw new IOException(e); } }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int handshake(boolean read, boolean write) throws IOException { if ( handshakeComplete ) return 0; //we have done our initial handshake if (!flush(netOutBuffer)) return SelectionKey.OP_WRITE; //we still have data to write SSLEngineResult handshake = null; while (!handshakeComplete) { switch ( handshakeStatus ) { case NOT_HANDSHAKING: { //should never happen throw new IOException("NOT_HANDSHAKING during handshake"); } case FINISHED: { //we are complete if we have delivered the last package handshakeComplete = !netOutBuffer.hasRemaining(); //return 0 if we are complete, otherwise we still have data to write return handshakeComplete?0:SelectionKey.OP_WRITE; } case NEED_WRAP: { //perform the wrap function handshake = handshakeWrap(write); if ( handshake.getStatus() == Status.OK ){ if (handshakeStatus == HandshakeStatus.NEED_TASK) handshakeStatus = tasks(); } else { //wrap should always work with our buffers throw new IOException("Unexpected status:" + handshake.getStatus() + " during handshake WRAP."); } if ( handshakeStatus != HandshakeStatus.NEED_UNWRAP || (!flush(netOutBuffer)) ) { //should actually return OP_READ if we have NEED_UNWRAP return SelectionKey.OP_WRITE; } //fall down to NEED_UNWRAP on the same call, will result in a //BUFFER_UNDERFLOW if it needs data } //$FALL-THROUGH$ case NEED_UNWRAP: { //perform the unwrap function handshake = handshakeUnwrap(read); if ( handshake.getStatus() == Status.OK ) { if (handshakeStatus == HandshakeStatus.NEED_TASK) handshakeStatus = tasks(); } else if ( handshake.getStatus() == Status.BUFFER_UNDERFLOW ){ //read more data, reregister for OP_READ return SelectionKey.OP_READ; } else { throw new IOException("Invalid handshake status:"+handshakeStatus+" during handshake UNWRAP."); }//switch break; } case NEED_TASK: { handshakeStatus = tasks(); break; } default: throw new IllegalStateException("Invalid handshake status:"+handshakeStatus); }//switch }//while //return 0 if we are complete, otherwise reregister for any activity that //would cause this method to be called again. return handshakeComplete?0:(SelectionKey.OP_WRITE|SelectionKey.OP_READ); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
protected SSLEngineResult handshakeUnwrap(boolean doread) throws IOException { if (netInBuffer.position() == netInBuffer.limit()) { //clear the buffer if we have emptied it out on data netInBuffer.clear(); } if ( doread ) { //if we have data to read, read it int read = sc.read(netInBuffer); if (read == -1) throw new IOException("EOF encountered during handshake."); } SSLEngineResult result; boolean cont = false; //loop while we can perform pure SSLEngine data do { //prepare the buffer with the incoming data netInBuffer.flip(); //call unwrap result = sslEngine.unwrap(netInBuffer, bufHandler.getReadBuffer()); //compact the buffer, this is an optional method, wonder what would happen if we didn't netInBuffer.compact(); //read in the status handshakeStatus = result.getHandshakeStatus(); if ( result.getStatus() == SSLEngineResult.Status.OK && result.getHandshakeStatus() == HandshakeStatus.NEED_TASK ) { //execute tasks if we need to handshakeStatus = tasks(); } //perform another unwrap? cont = result.getStatus() == SSLEngineResult.Status.OK && handshakeStatus == HandshakeStatus.NEED_UNWRAP; }while ( cont ); return result; }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public void close() throws IOException { if (closing) return; closing = true; sslEngine.closeOutbound(); if (!flush(netOutBuffer)) { throw new IOException("Remaining data in the network buffer, can't send SSL close message, force a close with close(true) instead"); } //prep the buffer for the close message netOutBuffer.clear(); //perform the close, since we called sslEngine.closeOutbound SSLEngineResult handshake = sslEngine.wrap(getEmptyBuf(), netOutBuffer); //we should be in a close state if (handshake.getStatus() != SSLEngineResult.Status.CLOSED) { throw new IOException("Invalid close state, will not send network data."); } //prepare the buffer for writing netOutBuffer.flip(); //if there is data to be written flush(netOutBuffer); //is the channel closed? closed = (!netOutBuffer.hasRemaining() && (handshake.getHandshakeStatus() != HandshakeStatus.NEED_WRAP)); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int read(ByteBuffer dst) throws IOException { //if we want to take advantage of the expand function, make sure we only use the ApplicationBufferHandler's buffers if ( dst != bufHandler.getReadBuffer() ) throw new IllegalArgumentException("You can only read using the application read buffer provided by the handler."); //are we in the middle of closing or closed? if ( closing || closed) return -1; //did we finish our handshake? if (!handshakeComplete) throw new IllegalStateException("Handshake incomplete, you must complete handshake before reading data."); //read from the network int netread = sc.read(netInBuffer); //did we reach EOF? if so send EOF up one layer. if (netread == -1) return -1; //the data read int read = 0; //the SSL engine result SSLEngineResult unwrap; do { //prepare the buffer netInBuffer.flip(); //unwrap the data unwrap = sslEngine.unwrap(netInBuffer, dst); //compact the buffer netInBuffer.compact(); if ( unwrap.getStatus()==Status.OK || unwrap.getStatus()==Status.BUFFER_UNDERFLOW ) { //we did receive some data, add it to our total read += unwrap.bytesProduced(); //perform any tasks if needed if (unwrap.getHandshakeStatus() == HandshakeStatus.NEED_TASK) tasks(); //if we need more network data, then bail out for now. if ( unwrap.getStatus() == Status.BUFFER_UNDERFLOW ) break; }else if ( unwrap.getStatus()==Status.BUFFER_OVERFLOW && read>0 ) { //buffer overflow can happen, if we have read data, then //empty out the dst buffer before we do another read break; }else { //here we should trap BUFFER_OVERFLOW and call expand on the buffer //for now, throw an exception, as we initialized the buffers //in the constructor throw new IOException("Unable to unwrap data, invalid status: " + unwrap.getStatus()); } } while ( (netInBuffer.position() != 0)); //continue to unwrapping as long as the input buffer has stuff return (read); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int write(ByteBuffer src) throws IOException { if ( src == this.netOutBuffer ) { //we can get here through a recursive call //by using the NioBlockingSelector int written = sc.write(src); return written; } else { //make sure we can handle expand, and that we only use on buffer if ( (!this.isSendFile()) && (src != bufHandler.getWriteBuffer()) ) throw new IllegalArgumentException("You can only write using the application write buffer provided by the handler."); //are we closing or closed? if ( closing || closed) throw new IOException("Channel is in closing state."); //the number of bytes written int written = 0; if (!flush(netOutBuffer)) { //we haven't emptied out the buffer yet return written; } /* * The data buffer is empty, we can reuse the entire buffer. */ netOutBuffer.clear(); SSLEngineResult result = sslEngine.wrap(src, netOutBuffer); written = result.bytesConsumed(); netOutBuffer.flip(); if (result.getStatus() == Status.OK) { if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) tasks(); } else { throw new IOException("Unable to wrap data, invalid engine state: " +result.getStatus()); } //force a flush flush(netOutBuffer); return written; } }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int write(ByteBuffer buf, NioChannel socket, long writeTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int written = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) && buf.hasRemaining()) { if (keycount > 0) { //only write if we were registered for a write int cnt = socket.write(buf); //write the data if (cnt == -1) throw new EOFException(); written += cnt; if (cnt > 0) { time = System.currentTimeMillis(); //reset our timeout timer continue; //we successfully wrote, try again without a selector } } try { if ( att.getWriteLatch()==null || att.getWriteLatch().getCount()==0) att.startWriteLatch(1); poller.add(att,SelectionKey.OP_WRITE,reference); if (writeTimeout < 0) { att.awaitWriteLatch(Long.MAX_VALUE,TimeUnit.MILLISECONDS); } else { att.awaitWriteLatch(writeTimeout,TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getWriteLatch()!=null && att.getWriteLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetWriteLatch(); } if (writeTimeout > 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= writeTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_WRITE); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return written; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int read(ByteBuffer buf, NioChannel socket, long readTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int read = 0; boolean timedout = false; int keycount = 1; //assume we can read long time = System.currentTimeMillis(); //start the timeout timer try { while(!timedout) { if (keycount > 0) { //only read if we were registered for a read read = socket.read(buf); if (read == -1) throw new EOFException(); if (read > 0) break; } try { if ( att.getReadLatch()==null || att.getReadLatch().getCount()==0) att.startReadLatch(1); poller.add(att,SelectionKey.OP_READ, reference); if (readTimeout < 0) { att.awaitReadLatch(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } else { att.awaitReadLatch(readTimeout, TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getReadLatch()!=null && att.getReadLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetReadLatch(); } if (readTimeout >= 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= readTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_READ); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return read; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
public boolean processSendfile(SelectionKey sk, KeyAttachment attachment, boolean reg, boolean event) { NioChannel sc = null; try { unreg(sk, attachment, sk.readyOps()); SendfileData sd = attachment.getSendfileData(); if ( sd.fchannel == null ) { File f = new File(sd.fileName); if ( !f.exists() ) { cancelledKey(sk,SocketStatus.ERROR); return false; } sd.fchannel = new FileInputStream(f).getChannel(); } sc = attachment.getChannel(); sc.setSendFile(true); WritableByteChannel wc = ((sc instanceof SecureNioChannel)?sc:sc.getIOChannel()); if (sc.getOutboundRemaining()>0) { if (sc.flushOutbound()) { attachment.access(); } } else { long written = sd.fchannel.transferTo(sd.pos,sd.length,wc); if ( written > 0 ) { sd.pos += written; sd.length -= written; attachment.access(); } else { // Unusual not to be able to transfer any bytes // Check the length was set correctly if (sd.fchannel.size() <= sd.pos) { throw new IOException("Sendfile configured to " + "send more data than was available"); } } } if ( sd.length <= 0 && sc.getOutboundRemaining()<=0) { if (log.isDebugEnabled()) { log.debug("Send file complete for:"+sd.fileName); } attachment.setSendfileData(null); try { sd.fchannel.close(); } catch (Exception ignore) { } if ( sd.keepAlive ) { if (reg) { if (log.isDebugEnabled()) { log.debug("Connection is keep alive, registering back for OP_READ"); } if (event) { this.add(attachment.getChannel(),SelectionKey.OP_READ); } else { reg(sk,attachment,SelectionKey.OP_READ); } } } else { if (log.isDebugEnabled()) { log.debug("Send file connection is being closed"); } cancelledKey(sk,SocketStatus.STOP); return false; } } else if ( attachment.interestOps() == 0 && reg ) { if (log.isDebugEnabled()) { log.debug("OP_WRITE for sendilfe:"+sd.fileName); } if (event) { add(attachment.getChannel(),SelectionKey.OP_WRITE); } else { reg(sk,attachment,SelectionKey.OP_WRITE); } } }catch ( IOException x ) { if ( log.isDebugEnabled() ) log.debug("Unable to complete sendfile request:", x); cancelledKey(sk,SocketStatus.ERROR); return false; }catch ( Throwable t ) { log.error("",t); cancelledKey(sk, SocketStatus.ERROR); return false; }finally { if (sc!=null) sc.setSendFile(false); } return true; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public void handshake(Socket sock) throws IOException { // We do getSession instead of startHandshake() so we can call this multiple times SSLSession session = ((SSLSocket)sock).getSession(); if (session.getCipherSuite().equals("SSL_NULL_WITH_NULL_NULL")) throw new IOException("SSL handshake failed. Ciper suite in SSL Session is SSL_NULL_WITH_NULL_NULL"); if (!allowUnsafeLegacyRenegotiation && !RFC_5746_SUPPORTED) { // Prevent further handshakes by removing all cipher suites ((SSLSocket) sock).setEnabledCipherSuites(new String[0]); } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
private KeyStore getStore(String type, String provider, String path, String pass) throws IOException { KeyStore ks = null; InputStream istream = null; try { if (provider == null) { ks = KeyStore.getInstance(type); } else { ks = KeyStore.getInstance(type, provider); } if(!("PKCS11".equalsIgnoreCase(type) || "".equalsIgnoreCase(path))) { File keyStoreFile = new File(path); if (!keyStoreFile.isAbsolute()) { keyStoreFile = new File(System.getProperty( Constants.CATALINA_BASE_PROP), path); } istream = new FileInputStream(keyStoreFile); } char[] storePass = null; if (pass != null && !"".equals(pass)) { storePass = pass.toCharArray(); } ks.load(istream, storePass); } catch (FileNotFoundException fnfe) { log.error(sm.getString("jsse.keystore_load_failed", type, path, fnfe.getMessage()), fnfe); throw fnfe; } catch (IOException ioe) { // May be expected when working with a trust store // Re-throw. Caller will catch and log as required throw ioe; } catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); } finally { if (istream != null) { try { istream.close(); } catch (IOException ioe) { // Do nothing } } } return ks; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
void init() throws IOException { try { String clientAuthStr = endpoint.getClientAuth(); if("true".equalsIgnoreCase(clientAuthStr) || "yes".equalsIgnoreCase(clientAuthStr)) { requireClientAuth = true; } else if("want".equalsIgnoreCase(clientAuthStr)) { wantClientAuth = true; } SSLContext context = createSSLContext(); context.init(getKeyManagers(), getTrustManagers(), null); // Configure SSL session cache SSLSessionContext sessionContext = context.getServerSessionContext(); if (sessionContext != null) { configureSessionContext(sessionContext); } // create proxy sslProxy = context.getServerSocketFactory(); // Determine which cipher suites to enable String requestedCiphers = endpoint.getCiphers(); enabledCiphers = getEnabledCiphers(requestedCiphers, sslProxy.getSupportedCipherSuites()); allowUnsafeLegacyRenegotiation = "true".equals( endpoint.getAllowUnsafeLegacyRenegotiation()); // Check the SSL config is OK checkConfig(); } catch(Exception e) { if( e instanceof IOException ) throw (IOException)e; throw new IOException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected KeyManager[] getKeyManagers(String keystoreType, String keystoreProvider, String algorithm, String keyAlias) throws Exception { KeyManager[] kms = null; String keystorePass = getKeystorePassword(); KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass); if (keyAlias != null && !ks.isKeyEntry(keyAlias)) { throw new IOException( sm.getString("jsse.alias_no_key_entry", keyAlias)); } KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); String keyPass = endpoint.getKeyPass(); if (keyPass == null) { keyPass = keystorePass; } kmf.init(ks, keyPass.toCharArray()); kms = kmf.getKeyManagers(); if (keyAlias != null) { String alias = keyAlias; if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) { alias = alias.toLowerCase(Locale.ENGLISH); } for(int i=0; i<kms.length; i++) { kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias); } } return kms; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public byte readByte() throws IOException { // Buffer depleted ? if (head == tail) { head = 0; // Refill. tail = input.read(buffer, head, bufSize); if (tail == -1) { // No more data available. throw new IOException("No more data is available"); } if (notifier != null) { notifier.noteBytesRead(tail); } } return buffer[head++]; }
// in java/org/apache/tomcat/util/http/fileupload/DeferredFileOutputStream.java
public void writeTo(OutputStream out) throws IOException { // we may only need to check if this is closed if we are working with a file // but we should force the habit of closing wether we are working with // a file or memory. if (!closed) { throw new IOException("Stream not closed"); } if(isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } }
// in java/org/apache/tomcat/util/http/fileupload/FileDeleteStrategy.java
public void delete(File fileToDelete) throws IOException { if (fileToDelete.exists() && doDelete(fileToDelete) == false) { throw new IOException("Deletion failed: " + fileToDelete); } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void deleteDirectory(File directory) throws IOException { if (!directory.exists()) { return; } cleanDirectory(directory); if (!directory.delete()) { String message = "Unable to delete directory " + directory + "."; throw new IOException(message); } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void cleanDirectory(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (int i = 0; i < files.length; i++) { File file = files[i]; try { forceDelete(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void forceDelete(File file) throws IOException { if (file.isDirectory()) { deleteDirectory(file); } else { boolean filePresent = file.exists(); if (!file.delete()) { if (!filePresent){ throw new FileNotFoundException("File does not exist: " + file); } String message = "Unable to delete file: " + file; throw new IOException(message); } } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
private static void cleanDirectoryOnExit(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (int i = 0; i < files.length; i++) { File file = files[i]; try { forceDeleteOnExit(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
Override public final void close() throws IOException { // shouldn't be called - we filter it out in writer throw new IOException("close() called - shouldn't happen "); }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public void flushBuffer() throws IOException { //assert out!=null if( out==null ) { throw new IOException( "Buffer overflow, no sink " + limit + " " + buff.length ); } out.realWriteChars( buff, start, end - start ); end=start; }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void close() throws IOException { // shouldn't be called - we filter it out in writer throw new IOException("close() called - shouldn't happen "); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void write(int i) throws IOException { throw new IOException("write( int ) called - shouldn't happen "); }
// in java/org/apache/tomcat/util/buf/ByteChunk.java
public void flushBuffer() throws IOException { //assert out!=null if( out==null ) { throw new IOException( "Buffer overflow, no sink " + limit + " " + buff.length ); } out.realWriteBytes( buff, start, end-start ); end=start; }
// in java/org/apache/el/parser/SimpleCharStream.java
protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
// in java/org/apache/catalina/startup/ContextConfig.java
protected ServletContainerInitializer getServletContainerInitializer( InputStream is) throws IOException { String className = null; if (is != null) { String line = null; try { BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); line = br.readLine(); if (line != null && line.trim().length() > 0) { className = line.trim(); } } catch (UnsupportedEncodingException e) { // Should never happen with UTF-8 // If it does - ignore & return null } } ServletContainerInitializer sci = null; try { Class<?> clazz = Class.forName(className,true, context.getLoader().getClassLoader()); sci = (ServletContainerInitializer) clazz.newInstance(); } catch (ClassNotFoundException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); } catch (InstantiationException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); } catch (IllegalAccessException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); } return sci; }
// in java/org/apache/catalina/startup/TldConfig.java
private XmlErrorHandler tldScanStream(InputStream resourceStream) throws IOException { InputSource source = new InputSource(resourceStream); XmlErrorHandler result = new XmlErrorHandler(); synchronized (tldDigester) { try { tldDigester.setErrorHandler(result); tldDigester.push(this); tldDigester.parse(source); } catch (SAXException s) { // Hack - makes exception handling simpler throw new IOException(s); } finally { tldDigester.reset(); } return result; } }
// in java/org/apache/catalina/startup/ExpandWar.java
public static String expand(Host host, URL war, String pathname) throws IOException { // Make sure that there is no such directory already existing File docBase = new File(host.getAppBaseFile(), pathname); if (docBase.exists()) { // War file is already installed return (docBase.getAbsolutePath()); } // Create the new document base directory docBase.mkdir(); // Expand the WAR into the new document base directory String canonicalDocBasePrefix = docBase.getCanonicalPath(); if (!canonicalDocBasePrefix.endsWith(File.separator)) { canonicalDocBasePrefix += File.separator; } JarURLConnection juc = (JarURLConnection) war.openConnection(); juc.setUseCaches(false); JarFile jarFile = null; InputStream input = null; boolean success = false; try { jarFile = juc.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String name = jarEntry.getName(); File expandedFile = new File(docBase, name); if (!expandedFile.getCanonicalPath().startsWith( canonicalDocBasePrefix)) { // Trying to expand outside the docBase // Throw an exception to stop the deployment throw new IllegalArgumentException( sm.getString("expandWar.illegalPath",war, name, expandedFile.getCanonicalPath(), canonicalDocBasePrefix)); } int last = name.lastIndexOf('/'); if (last >= 0) { File parent = new File(docBase, name.substring(0, last)); if (!parent.mkdirs() && !parent.isDirectory()) { throw new IOException( sm.getString("expandWar.createFailed", parent)); } } if (name.endsWith("/")) { continue; } input = jarFile.getInputStream(jarEntry); if(null == input) throw new ZipException(sm.getString("expandWar.missingJarEntry", jarEntry.getName())); // Bugzilla 33636 expand(input, expandedFile); long lastModified = jarEntry.getTime(); if ((lastModified != -1) && (lastModified != 0)) { expandedFile.setLastModified(lastModified); } input.close(); input = null; } success = true; } catch (IOException e) { throw e; } finally { if (!success) { // If something went wrong, delete expanded dir to keep things // clean deleteDir(docBase); } if (input != null) { try { input.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } input = null; } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } } // Return the absolute path to our new document base directory return (docBase.getAbsolutePath()); }
// in java/org/apache/catalina/loader/WebappLoader.java
private void setRepositories() throws IOException { if (!(container instanceof Context)) return; ServletContext servletContext = ((Context) container).getServletContext(); if (servletContext == null) return; loaderRepositories=new ArrayList<String>(); // Loading the work directory File workDir = (File) servletContext.getAttribute(ServletContext.TEMPDIR); if (workDir == null) { log.info("No work dir for " + servletContext); } if( log.isDebugEnabled() && workDir != null) log.debug(sm.getString("webappLoader.deploy", workDir.getAbsolutePath())); classLoader.setWorkDir(workDir); DirContext resources = container.getResources(); // Setting up the class repository (/WEB-INF/classes), if it exists String classesPath = "/WEB-INF/classes"; DirContext classes = null; try { Object object = resources.lookup(classesPath); if (object instanceof DirContext) { classes = (DirContext) object; } } catch(NamingException e) { // Silent catch: it's valid that no /WEB-INF/classes collection // exists } if (classes != null) { File classRepository = null; String absoluteClassesPath = servletContext.getRealPath(classesPath); if (absoluteClassesPath != null) { classRepository = new File(absoluteClassesPath); } else { classRepository = new File(workDir, classesPath); if (!classRepository.mkdirs() && !classRepository.isDirectory()) { throw new IOException( sm.getString("webappLoader.mkdirFailure")); } if (!copyDir(classes, classRepository)) { throw new IOException( sm.getString("webappLoader.copyFailure")); } } if(log.isDebugEnabled()) log.debug(sm.getString("webappLoader.classDeploy", classesPath, classRepository.getAbsolutePath())); // Adding the repository to the class loader classLoader.addRepository(classesPath + "/", classRepository); loaderRepositories.add(classesPath + "/" ); } // Setting up the JAR repository (/WEB-INF/lib), if it exists String libPath = "/WEB-INF/lib"; classLoader.setJarPath(libPath); DirContext libDir = null; // Looking up directory /WEB-INF/lib in the context try { Object object = resources.lookup(libPath); if (object instanceof DirContext) libDir = (DirContext) object; } catch(NamingException e) { // Silent catch: it's valid that no /WEB-INF/lib collection // exists } if (libDir != null) { boolean copyJars = false; String absoluteLibPath = servletContext.getRealPath(libPath); File destDir = null; if (absoluteLibPath != null) { destDir = new File(absoluteLibPath); } else { copyJars = true; destDir = new File(workDir, libPath); if (!destDir.mkdirs() && !destDir.isDirectory()) { throw new IOException( sm.getString("webappLoader.mkdirFailure")); } } // Looking up directory /WEB-INF/lib in the context NamingEnumeration<NameClassPair> enumeration = null; try { enumeration = libDir.list(""); } catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", libPath)); ioe.initCause(e); throw ioe; } while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String filename = libPath + "/" + ncPair.getName(); if (!filename.endsWith(".jar")) continue; // Copy JAR in the work directory, always (the JAR file // would get locked otherwise, which would make it // impossible to update it or remove it at runtime) File destFile = new File(destDir, ncPair.getName()); if( log.isDebugEnabled()) log.debug(sm.getString("webappLoader.jarDeploy", filename, destFile.getAbsolutePath())); // Bug 45403 - Explicitly call lookup() on the name to check // that the resource is readable. We cannot use resources // returned by listBindings(), because that lists all of them, // but does not perform the necessary checks on each. Object obj = null; try { obj = libDir.lookup(ncPair.getName()); } catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", filename)); ioe.initCause(e); throw ioe; } if (!(obj instanceof Resource)) continue; Resource jarResource = (Resource) obj; if (copyJars) { if (!copy(jarResource.streamContent(), new FileOutputStream(destFile))) { throw new IOException( sm.getString("webappLoader.copyFailure")); } } try { JarFile jarFile = new JarFile(destFile); classLoader.addJar(filename, jarFile, destFile); } catch (Exception ex) { // Catch the exception if there is an empty jar file // Should ignore and continue loading other jar files // in the dir } loaderRepositories.add( filename ); } } }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
Override public void save() throws Exception { if (getReadonly()) { log.error(sm.getString("memoryUserDatabase.readOnly")); return; } if (!isWriteable()) { log.warn(sm.getString("memoryUserDatabase.notPersistable")); return; } // Write out contents to a temporary file File fileNew = new File(pathnameNew); if (!fileNew.isAbsolute()) { fileNew = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathnameNew); } PrintWriter writer = null; try { // Configure our PrintWriter FileOutputStream fos = new FileOutputStream(fileNew); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF8"); writer = new PrintWriter(osw); // Print the file prolog writer.println("<?xml version='1.0' encoding='utf-8'?>"); writer.println("<tomcat-users>"); // Print entries for each defined role, group, and user Iterator<?> values = null; values = getRoles(); while (values.hasNext()) { writer.print(" "); writer.println(values.next()); } values = getGroups(); while (values.hasNext()) { writer.print(" "); writer.println(values.next()); } values = getUsers(); while (values.hasNext()) { writer.print(" "); writer.println(((MemoryUser) values.next()).toXml()); } // Print the file epilog writer.println("</tomcat-users>"); // Check for errors that occurred while printing if (writer.checkError()) { writer.close(); fileNew.delete(); throw new IOException (sm.getString("memoryUserDatabase.writeException", fileNew.getAbsolutePath())); } writer.close(); } catch (IOException e) { if (writer != null) { writer.close(); } fileNew.delete(); throw e; } // Perform the required renames to permanently save this file File fileOld = new File(pathnameOld); if (!fileOld.isAbsolute()) { fileOld = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathnameOld); } fileOld.delete(); File fileOrig = new File(pathname); if (!fileOrig.isAbsolute()) { fileOrig = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathname); } if (fileOrig.exists()) { fileOld.delete(); if (!fileOrig.renameTo(fileOld)) { throw new IOException (sm.getString("memoryUserDatabase.renameOld", fileOld.getAbsolutePath())); } } if (!fileNew.renameTo(fileOrig)) { if (fileOld.exists()) { fileOld.renameTo(fileOrig); } throw new IOException (sm.getString("memoryUserDatabase.renameNew", fileOrig.getAbsolutePath())); } fileOld.delete(); }
// in java/org/apache/catalina/websocket/MessageInbound.java
private void resizeByteBuffer() throws IOException { int maxSize = getByteBufferMaxSize(); if (bb.limit() >= maxSize) { throw new IOException(sm.getString("message.bufferTooSmall")); } long newSize = bb.limit() * 2; if (newSize > maxSize) { newSize = maxSize; } // Cast is safe. newSize < maxSize and maxSize is an int ByteBuffer newBuffer = ByteBuffer.allocate((int) newSize); bb.rewind(); newBuffer.put(bb); bb = newBuffer; }
// in java/org/apache/catalina/websocket/MessageInbound.java
private void resizeCharBuffer() throws IOException { int maxSize = getCharBufferMaxSize(); if (cb.limit() >= maxSize) { throw new IOException(sm.getString("message.bufferTooSmall")); } long newSize = cb.limit() * 2; if (newSize > maxSize) { newSize = maxSize; } // Cast is safe. newSize < maxSize and maxSize is an int CharBuffer newBuffer = CharBuffer.allocate((int) newSize); cb.rewind(); newBuffer.put(cb); cb = newBuffer; }
// in java/org/apache/catalina/websocket/WsInputStream.java
private void makePayloadDataAvailable() throws IOException { if (error != null) { throw new IOException(error); } while (remaining == 0 && !frame.getFin()) { // Need more data - process next frame nextFrame(true); while (frame.isControl()) { if (frame.getOpCode() == Constants.OPCODE_PING) { outbound.pong(frame.getPayLoad()); } else if (frame.getOpCode() == Constants.OPCODE_PONG) { // NO-OP. Swallow it. } else if (frame.getOpCode() == Constants.OPCODE_CLOSE) { outbound.close(frame); } else{ throw new IOException(sm.getString("is.unknownOpCode", Byte.valueOf(frame.getOpCode()))); } nextFrame(true); } if (frame.getOpCode() != Constants.OPCODE_CONTINUATION) { error = sm.getString("is.notContinuation", Byte.valueOf(frame.getOpCode())); throw new IOException(error); } } }
// in java/org/apache/catalina/websocket/WsFrame.java
private int blockingRead(UpgradeProcessor<?> processor) throws IOException { int result = processor.read(); if (result == -1) { throw new IOException(sm.getString("frame.eos")); } return result; }
// in java/org/apache/catalina/websocket/WsFrame.java
private void blockingRead(UpgradeProcessor<?> processor, byte[] bytes) throws IOException { int read = 0; int last = 0; while (read < bytes.length) { last = processor.read(true, bytes, read, bytes.length - read); if (last == -1) { throw new IOException(sm.getString("frame.eos")); } read += last; } }
// in java/org/apache/catalina/websocket/WsFrame.java
private void blockingRead(UpgradeProcessor<?> processor, ByteBuffer bb) throws IOException { int last = 0; while (bb.hasRemaining()) { last = processor.read(); if (last == -1) { throw new IOException(sm.getString("frame.eos")); } bb.put((byte) (last ^ mask[bb.position() % 4])); } bb.flip(); }
// in java/org/apache/catalina/websocket/WsFrame.java
public static WsFrame nextFrame(UpgradeProcessor<?> processor, boolean block) throws IOException { byte[] first = new byte[1]; int read = processor.read(block, first, 0, 1); if (read == 1) { return new WsFrame(first[0], processor); } else if (read == 0) { return null; } else if (read == -1) { throw new EOFException(sm.getString("frame.readEos")); } else { throw new IOException( sm.getString("frame.readFailed", Integer.valueOf(read))); } }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeBinaryData(int b) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (bb.position() == bb.capacity()) { doFlush(false); } if (text == null) { text = Boolean.FALSE; } else if (text == Boolean.TRUE) { // Flush the character data flush(); text = Boolean.FALSE; } bb.put((byte) (b & 0xFF)); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeTextData(char c) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (cb.position() == cb.capacity()) { doFlush(false); } if (text == null) { text = Boolean.TRUE; } else if (text == Boolean.FALSE) { // Flush the binary data flush(); text = Boolean.TRUE; } cb.append(c); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeBinaryMessage(ByteBuffer msgBb) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (text != null) { // Empty the buffer flush(); } text = Boolean.FALSE; doWriteBytes(msgBb, true); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeTextMessage(CharBuffer msgCb) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (text != null) { // Empty the buffer flush(); } text = Boolean.TRUE; doWriteText(msgCb, true); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void flush() throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } doFlush(true); }
// in java/org/apache/catalina/websocket/WsOutbound.java
protected void close(WsFrame frame) throws IOException { if (frame.getPayLoadLength() > 0) { // Must be status (2 bytes) plus optional message if (frame.getPayLoadLength() == 1) { throw new IOException(); } int status = (frame.getPayLoad().get() & 0xFF) << 8; status += frame.getPayLoad().get() & 0xFF; if (validateCloseStatus(status)) { // Echo the status back to the client close(status, frame.getPayLoad()); } else { // Invalid close code close(Constants.STATUS_PROTOCOL_ERROR, null); } } else { // No status close(0, null); } }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void pong(ByteBuffer data) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } doFlush(true); upgradeOutbound.write(0x8A); if (data == null) { upgradeOutbound.write(0); } else { upgradeOutbound.write(data.limit() - data.position()); upgradeOutbound.write(data.array(), data.position(), data.limit() - data.position()); } upgradeOutbound.flush(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
protected void uploadWar(PrintWriter writer, HttpServletRequest request, File war, StringManager smClient) throws IOException { if (war.exists() && !war.delete()) { String msg = smClient.getString("managerServlet.deleteFail", war); throw new IOException(msg); } ServletInputStream istream = null; BufferedOutputStream ostream = null; try { istream = request.getInputStream(); ostream = new BufferedOutputStream(new FileOutputStream(war), 1024); byte buffer[] = new byte[1024]; while (true) { int n = istream.read(buffer); if (n < 0) { break; } ostream.write(buffer, 0, n); } ostream.flush(); ostream.close(); ostream = null; istream.close(); istream = null; } catch (IOException e) { if (war.exists() && !war.delete()) { writer.println( smClient.getString("managerServlet.deleteFail", war)); } throw e; } finally { if (ostream != null) { try { ostream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } ostream = null; } if (istream != null) { try { istream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } istream = null; } } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
protected void waitForAck() throws java.io.IOException { try { boolean ackReceived = false; boolean failAckReceived = false; ackbuf.clear(); int bytesRead = 0; int i = soIn.read(); while ((i != -1) && (bytesRead < Constants.ACK_COMMAND.length)) { bytesRead++; byte d = (byte)i; ackbuf.append(d); if (ackbuf.doesPackageExist() ) { byte[] ackcmd = ackbuf.extractDataPackage(true).getBytes(); ackReceived = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.ACK_DATA); failAckReceived = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA); ackReceived = ackReceived || failAckReceived; break; } i = soIn.read(); } if (!ackReceived) { if (i == -1) throw new IOException(sm.getString("IDataSender.ack.eof",getAddress(), new Integer(socket.getLocalPort()))); else throw new IOException(sm.getString("IDataSender.ack.wrong",getAddress(), new Integer(socket.getLocalPort()))); } else if ( failAckReceived && getThrowOnFailedAck()) { throw new RemoteProcessException("Received a failed ack:org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA"); } } catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; } finally { ackbuf.clear(); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
Override public void start() throws IOException { super.start(); try { setPool(new RxTaskPool(getMaxThreads(),getMinThreads(),this)); } catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } try { getBind(); bind(); Thread t = new Thread(this, "BioReceiver"); t.setDaemon(true); t.start(); } catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
public boolean process(SelectionKey key, boolean waitForAck) throws IOException { int ops = key.readyOps(); key.interestOps(key.interestOps() & ~ops); //in case disconnect has been called if ((!isConnected()) && (!connecting)) throw new IOException("Sender has been disconnected, can't selection key."); if ( !key.isValid() ) throw new IOException("Key is not valid, it must have been cancelled."); if ( key.isConnectable() ) { if ( socketChannel.finishConnect() ) { completeConnect(); if ( current != null ) key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); return false; } else { //wait for the connection to finish key.interestOps(key.interestOps() | SelectionKey.OP_CONNECT); return false; }//end if } else if ( key.isWritable() ) { boolean writecomplete = write(); if ( writecomplete ) { //we are completed, should we read an ack? if ( waitForAck ) { //register to read the ack key.interestOps(key.interestOps() | SelectionKey.OP_READ); } else { //if not, we are ready, setMessage will reregister us for another write interest //do a health check, we have no way of verify a disconnected //socket since we don't register for OP_READ on waitForAck=false read();//this causes overhead setRequestCount(getRequestCount()+1); return true; } } else { //we are not complete, lets write some more key.interestOps(key.interestOps()|SelectionKey.OP_WRITE); }//end if } else if ( key.isReadable() ) { boolean readcomplete = read(); if ( readcomplete ) { setRequestCount(getRequestCount()+1); return true; } else { key.interestOps(key.interestOps() | SelectionKey.OP_READ); }//end if } else { //unknown state, should never happen log.warn("Data is in unknown state. readyOps="+ops); throw new IOException("Data is in unknown state. readyOps="+ops); }//end if return false; }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
protected boolean read() throws IOException { //if there is no message here, we are done if ( current == null ) return true; int read = isUdpBased()?dataChannel.read(readbuf) : socketChannel.read(readbuf); //end of stream if ( read == -1 ) throw new IOException("Unable to receive an ack message. EOF on socket channel has been reached."); //no data read else if ( read == 0 ) return false; readbuf.flip(); ackbuf.append(readbuf,read); readbuf.clear(); if (ackbuf.doesPackageExist() ) { byte[] ackcmd = ackbuf.extractDataPackage(true).getBytes(); boolean ack = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.ACK_DATA); boolean fack = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA); if ( fack && getThrowOnFailedAck() ) throw new RemoteProcessException("Received a failed ack:org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA"); return ack || fack; } else { return false; } }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
protected boolean write() throws IOException { if ( (!isConnected()) || (this.socketChannel==null && this.dataChannel==null)) { throw new IOException("NioSender is not connected, this should not occur."); } if ( current != null ) { if ( remaining > 0 ) { //we have written everything, or we are starting a new package //protect against buffer overwrite int byteswritten = isUdpBased()?dataChannel.write(writebuf) : socketChannel.write(writebuf); if (byteswritten == -1 ) throw new EOFException(); remaining -= byteswritten; //if the entire message was written from the buffer //reset the position counter if ( remaining < 0 ) { remaining = 0; } } return (remaining==0); } //no message to send, we can consider that complete return true; }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
Override public synchronized void connect() throws IOException { if ( connecting || isConnected()) return; connecting = true; if ( isConnected() ) throw new IOException("NioSender is already in connected state."); if ( readbuf == null ) { readbuf = getReadBuffer(); } else { readbuf.clear(); } if ( writebuf == null ) { writebuf = getWriteBuffer(); } else { writebuf.clear(); } if (isUdpBased()) { InetSocketAddress daddr = new InetSocketAddress(getAddress(),getUdpPort()); if ( dataChannel != null ) throw new IOException("Datagram channel has already been established. Connection might be in progress."); dataChannel = DatagramChannel.open(); dataChannel.configureBlocking(false); dataChannel.connect(daddr); completeConnect(); dataChannel.register(getSelector(),SelectionKey.OP_WRITE, this); } else { InetSocketAddress addr = new InetSocketAddress(getAddress(),getPort()); if ( socketChannel != null ) throw new IOException("Socket channel has already been established. Connection might be in progress."); socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); if ( socketChannel.connect(addr) ) { completeConnect(); socketChannel.register(getSelector(), SelectionKey.OP_WRITE, this); } else { socketChannel.register(getSelector(), SelectionKey.OP_CONNECT, this); } } }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
Override public void start() throws IOException { super.start(); try { setPool(new RxTaskPool(getMaxThreads(),getMinThreads(),this)); } catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } try { getBind(); bind(); Thread t = new Thread(this, "NioReceiver"); t.setDaemon(true); t.start(); } catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } }
// in java/org/apache/catalina/session/FileStore.java
private File directory() throws IOException { if (this.directory == null) { return (null); } if (this.directoryFile != null) { // NOTE: Race condition is harmless, so do not synchronize return (this.directoryFile); } File file = new File(this.directory); if (!file.isAbsolute()) { Container container = manager.getContainer(); if (container instanceof Context) { ServletContext servletContext = ((Context) container).getServletContext(); File work = (File) servletContext.getAttribute(ServletContext.TEMPDIR); file = new File(work, this.directory); } else { throw new IllegalArgumentException ("Parent Container is not a Context"); } } if (!file.exists() || !file.isDirectory()) { if (!file.delete() && file.exists()) { throw new IOException( sm.getString("fileStore.deleteFailed", file)); } if (!file.mkdirs() && !file.isDirectory()) { throw new IOException( sm.getString("fileStore.createFailed", file)); } } this.directoryFile = file; return (file); }
// in java/org/apache/catalina/servlets/CGIServlet.java
protected void run() throws IOException { /* * REMIND: this method feels too big; should it be re-written? */ if (!isReady()) { throw new IOException(this.getClass().getName() + ": not ready to run."); } if (debug >= 1 ) { log("runCGI(envp=[" + env + "], command=" + command + ")"); } if ((command.indexOf(File.separator + "." + File.separator) >= 0) || (command.indexOf(File.separator + "..") >= 0) || (command.indexOf(".." + File.separator) >= 0)) { throw new IOException(this.getClass().getName() + "Illegal Character in CGI command " + "path ('.' or '..') detected. Not " + "running CGI [" + command + "]."); } /* original content/structure of this section taken from * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4216884 * with major modifications by Martin Dengler */ Runtime rt = null; BufferedReader cgiHeaderReader = null; InputStream cgiOutput = null; BufferedReader commandsStdErr = null; Thread errReaderThread = null; BufferedOutputStream commandsStdIn = null; Process proc = null; int bufRead = -1; List<String> cmdAndArgs = new ArrayList<String>(); if (cgiExecutable.length() != 0) { cmdAndArgs.add(cgiExecutable); } if (cgiExecutableArgs != null) { cmdAndArgs.addAll(cgiExecutableArgs); } cmdAndArgs.add(command); cmdAndArgs.addAll(params); try { rt = Runtime.getRuntime(); proc = rt.exec( cmdAndArgs.toArray(new String[cmdAndArgs.size()]), hashToStringArray(env), wd); String sContentLength = env.get("CONTENT_LENGTH"); if(!"".equals(sContentLength)) { commandsStdIn = new BufferedOutputStream(proc.getOutputStream()); IOTools.flow(stdin, commandsStdIn); commandsStdIn.flush(); commandsStdIn.close(); } /* we want to wait for the process to exit, Process.waitFor() * is useless in our situation; see * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4223650 */ boolean isRunning = true; commandsStdErr = new BufferedReader (new InputStreamReader(proc.getErrorStream())); final BufferedReader stdErrRdr = commandsStdErr ; errReaderThread = new Thread() { @Override public void run () { sendToLog(stdErrRdr) ; } }; errReaderThread.start(); InputStream cgiHeaderStream = new HTTPHeaderInputStream(proc.getInputStream()); cgiHeaderReader = new BufferedReader(new InputStreamReader(cgiHeaderStream)); while (isRunning) { try { //set headers String line = null; while (((line = cgiHeaderReader.readLine()) != null) && !("".equals(line))) { if (debug >= 2) { log("runCGI: addHeader(\"" + line + "\")"); } if (line.startsWith("HTTP")) { response.setStatus(getSCFromHttpStatusLine(line)); } else if (line.indexOf(":") >= 0) { String header = line.substring(0, line.indexOf(":")).trim(); String value = line.substring(line.indexOf(":") + 1).trim(); if (header.equalsIgnoreCase("status")) { response.setStatus(getSCFromCGIStatusHeader(value)); } else { response.addHeader(header , value); } } else { log("runCGI: bad header line \"" + line + "\""); } } //write output byte[] bBuf = new byte[2048]; OutputStream out = response.getOutputStream(); cgiOutput = proc.getInputStream(); try { while ((bufRead = cgiOutput.read(bBuf)) != -1) { if (debug >= 4) { log("runCGI: output " + bufRead + " bytes of data"); } out.write(bBuf, 0, bufRead); } } finally { // Attempt to consume any leftover byte if something bad happens, // such as a socket disconnect on the servlet side; otherwise, the // external process could hang if (bufRead != -1) { while ((bufRead = cgiOutput.read(bBuf)) != -1) { // NOOP - just read the data } } } proc.exitValue(); // Throws exception if alive isRunning = false; } catch (IllegalThreadStateException e) { try { Thread.sleep(500); } catch (InterruptedException ignored) { // Ignore } } } //replacement for Process.waitFor() } catch (IOException e){ log ("Caught exception " + e); throw e; } finally{ // Close the header reader if (cgiHeaderReader != null) { try { cgiHeaderReader.close(); } catch (IOException ioe) { log ("Exception closing header reader " + ioe); } } // Close the output stream if used if (cgiOutput != null) { try { cgiOutput.close(); } catch (IOException ioe) { log ("Exception closing output stream " + ioe); } } // Make sure the error stream reader has finished if (errReaderThread != null) { try { errReaderThread.join(stderrTimeout); } catch (InterruptedException e) { log ("Interupted waiting for stderr reader thread"); } } if (debug > 4) { log ("Running finally block"); } if (proc != null){ proc.destroy(); proc = null; } } }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected String getAbsolutePath(String path) throws IOException { String pathWithoutContext = SSIServletRequestUtil.getRelativePath(req); String prefix = getPathWithoutFileName(pathWithoutContext); if (prefix == null) { throw new IOException("Couldn't remove filename from path: " + pathWithoutContext); } String fullPath = prefix + path; String retVal = RequestUtil.normalize(fullPath); if (retVal == null) { throw new IOException("Normalization yielded null on path: " + fullPath); } return retVal; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected ServletContextAndPath getServletContextAndPathFromNonVirtualPath( String nonVirtualPath) throws IOException { if (nonVirtualPath.startsWith("/") || nonVirtualPath.startsWith("\\")) { throw new IOException("A non-virtual path can't be absolute: " + nonVirtualPath); } if (nonVirtualPath.indexOf("../") >= 0) { throw new IOException("A non-virtual path can't contain '../' : " + nonVirtualPath); } String path = getAbsolutePath(nonVirtualPath); ServletContextAndPath csAndP = new ServletContextAndPath( context, path); return csAndP; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected ServletContextAndPath getServletContextAndPathFromVirtualPath( String virtualPath) throws IOException { if (!virtualPath.startsWith("/") && !virtualPath.startsWith("\\")) { return new ServletContextAndPath(context, getAbsolutePath(virtualPath)); } String normalized = RequestUtil.normalize(virtualPath); if (isVirtualWebappRelative) { return new ServletContextAndPath(context, normalized); } ServletContext normContext = context.getContext(normalized); if (normContext == null) { throw new IOException("Couldn't get context for path: " + normalized); } //If it's the root context, then there is no context element // to remove, // ie: // '/file1.shtml' vs '/appName1/file1.shtml' if (!isRootContext(normContext)) { String noContext = getPathWithoutContext( normContext.getContextPath(), normalized); if (noContext == null) { throw new IOException( "Couldn't remove context from path: " + normalized); } return new ServletContextAndPath(normContext, noContext); } return new ServletContextAndPath(normContext, normalized); }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected URLConnection getURLConnection(String originalPath, boolean virtual) throws IOException { ServletContextAndPath csAndP = getServletContextAndPath(originalPath, virtual); ServletContext context = csAndP.getServletContext(); String path = csAndP.getPath(); URL url = context.getResource(path); if (url == null) { throw new IOException("Context did not contain resource: " + path); } URLConnection urlConnection = url.openConnection(); return urlConnection; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
Override public String getFileText(String originalPath, boolean virtual) throws IOException { try { ServletContextAndPath csAndP = getServletContextAndPath( originalPath, virtual); ServletContext context = csAndP.getServletContext(); String path = csAndP.getPath(); RequestDispatcher rd = context.getRequestDispatcher(path); if (rd == null) { throw new IOException( "Couldn't get request dispatcher for path: " + path); } ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream(); ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(context, req, res, basos); rd.include(req, responseIncludeWrapper); //We can't assume the included servlet flushed its output responseIncludeWrapper.flushOutputStreamOrWriter(); byte[] bytes = basos.toByteArray(); //Assume platform default encoding unless otherwise specified String retVal; if (inputEncoding == null) { retVal = new String( bytes ); } else { retVal = new String (bytes, B2CConverter.getCharset(inputEncoding)); } //make an assumption that an empty response is a failure. This is // a problem // if a truly empty file //were included, but not sure how else to tell. if (retVal.equals("") && !req.getMethod().equalsIgnoreCase( org.apache.coyote.http11.Constants.HEAD)) { throw new IOException("Couldn't find file: " + path); } return retVal; } catch (ServletException e) { throw new IOException("Couldn't include file: " + originalPath + " because of ServletException: " + e.getMessage()); } }
// in java/org/apache/catalina/connector/Request.java
protected byte[] readChunkedPostBody() throws IOException { ByteChunk body = new ByteChunk(); byte[] buffer = new byte[CACHED_POST_LEN]; int len = 0; while (len > -1) { len = getStream().read(buffer, 0, CACHED_POST_LEN); if (connector.getMaxPostSize() > 0 && (body.getLength() + len) > connector.getMaxPostSize()) { // Too much data checkSwallowInput(); throw new IOException( sm.getString("coyoteRequest.chunkedPostTooLarge")); } if (len > 0) { body.append(buffer, 0, len); } } if (body.getLength() == 0) { return null; } if (body.getLength() < body.getBuffer().length) { int length = body.getLength(); byte[] result = new byte[length]; System.arraycopy(body.getBuffer(), 0, result, 0, length); return result; } return body.getBuffer(); }
// in java/org/apache/catalina/connector/InputBuffer.java
public int readByte() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return bb.substract(); }
// in java/org/apache/catalina/connector/InputBuffer.java
public int read(byte[] b, int off, int len) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return bb.substract(b, off, len); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int read() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return cb.substract(); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int read(char[] cbuf) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return read(cbuf, 0, cbuf.length); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int read(char[] cbuf, int off, int len) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return cb.substract(cbuf, off, len); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public long skip(long n) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } if (n < 0) { throw new IllegalArgumentException(); } long nRead = 0; while (nRead < n) { if (cb.getLength() >= n) { cb.setOffset(cb.getStart() + (int) n); nRead = n; } else { nRead += cb.getLength(); cb.setOffset(cb.getEnd()); int toRead = 0; if (cb.getChars().length < (n - nRead)) { toRead = cb.getChars().length; } else { toRead = (int) (n - nRead); } int nb = realReadChars(cb.getChars(), 0, toRead); if (nb < 0) { break; } } } return nRead; }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public boolean ready() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return (available() > 0); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public void mark(int readAheadLimit) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } if (cb.getLength() <= 0) { cb.setOffset(0); cb.setEnd(0); } else { if ((cb.getBuffer().length > (2 * size)) && (cb.getLength()) < (cb.getStart())) { System.arraycopy(cb.getBuffer(), cb.getStart(), cb.getBuffer(), 0, cb.getLength()); cb.setEnd(cb.getLength()); cb.setOffset(0); } } cb.setLimit(cb.getStart() + readAheadLimit + size); markPos = cb.getStart(); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public void reset() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } if (state == CHAR_STATE) { if (markPos < 0) { cb.recycle(); markPos = -1; throw new IOException(); } else { cb.setOffset(markPos); } } else { bb.recycle(); } }
// in java/org/apache/catalina/core/ApplicationPart.java
Override public void write(String fileName) throws IOException { File file = new File(fileName); if (!file.isAbsolute()) { file = new File(mce.getLocation(), fileName); } try { fileItem.write(file); } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/catalina/util/Conversions.java
public static long byteArrayToLong(byte[] input) throws IOException { if (input.length > 8) { // TODO: Better message throw new IOException(); } int shift = 0; long result = 0; for (int i = input.length - 1; i >= 0; i--) { result = result + ((input[i] & 0xFF) << shift); shift += 8; } return result; }
// in java/javax/servlet/jsp/tagext/BodyContent.java
Override public void flush() throws IOException { throw new IOException("Illegal to flush within a custom tag"); }
// in java/javax/servlet/http/HttpServlet.java
Override public void write(byte buf[], int offset, int len) throws IOException { if (len >= 0) { contentLength += len; } else { // XXX // isn't this really an IllegalArgumentException? String msg = lStrings.getString("err.io.negativelength"); throw new IOException(msg); } }
33
            
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (JasperException e) { // Hack - makes exception handling simpler throw new IOException(e); }
// in java/org/apache/naming/resources/WARDirContext.java
catch (ZipException e) { throw new IOException(e.getMessage(), e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable e) { apr.reset(); e.printStackTrace(); throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable t) { throw new IOException(t); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (CertificateException ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception ex) { throw new IOException(ex); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable t) { throw new IOException(t); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Exception e) { throw new IOException(e); }
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
catch (DataFormatException e) { throw new IOException(e); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (NoSuchAlgorithmException e) { throw new IOException(e); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(Exception e) { if( e instanceof IOException ) throw (IOException)e; throw new IOException(e.getMessage(), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (ClassNotFoundException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (InstantiationException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IllegalAccessException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (SAXException s) { // Hack - makes exception handling simpler throw new IOException(s); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
catch (ServletException e) { throw new IOException("Couldn't include file: " + originalPath + " because of ServletException: " + e.getMessage()); }
// in java/org/apache/catalina/core/ApplicationPart.java
catch (Exception e) { throw new IOException(e); }
1262
            
// in java/org/apache/jasper/tagplugins/jstl/Util.java
Override public void write(int b) throws IOException { bos.write(b); }
// in java/org/apache/jasper/runtime/ServletResponseWrapperInclude.java
Override public PrintWriter getWriter() throws IOException { return printWriter; }
// in java/org/apache/jasper/runtime/ServletResponseWrapperInclude.java
Override public ServletOutputStream getOutputStream() throws IOException { throw new IllegalStateException(); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) throws IOException, IllegalStateException, IllegalArgumentException { }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void forward(String relativeUrlPath) throws ServletException, IOException { invokingJspCtxt.forward(relativeUrlPath); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void include(String relativeUrlPath) throws ServletException, IOException { invokingJspCtxt.include(relativeUrlPath); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void include(String relativeUrlPath, boolean flush) throws ServletException, IOException { invokingJspCtxt.include(relativeUrlPath, false); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void handlePageException(Exception ex) throws IOException, ServletException { // Should never be called since handleException() called with a // Throwable in the generated servlet. handlePageException((Throwable) ex); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void handlePageException(Throwable t) throws IOException, ServletException { invokingJspCtxt.handlePageException(t); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void write(int c) throws IOException { if (writer != null) { writer.write(c); } else { ensureOpen(); if (nextChar >= bufferSize) { reAllocBuff (1); } cb[nextChar++] = (char) c; } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void write(char[] cbuf, int off, int len) throws IOException { if (writer != null) { writer.write(cbuf, off, len); } else { ensureOpen(); if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } if (len >= bufferSize - nextChar) reAllocBuff (len); System.arraycopy(cbuf, off, cb, nextChar, len); nextChar+=len; } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void write(char[] buf) throws IOException { if (writer != null) { writer.write(buf); } else { write(buf, 0, buf.length); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void write(String s, int off, int len) throws IOException { if (writer != null) { writer.write(s, off, len); } else { ensureOpen(); if (len >= bufferSize - nextChar) reAllocBuff(len); s.getChars(off, off + len, cb, nextChar); nextChar += len; } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void write(String s) throws IOException { if (writer != null) { writer.write(s); } else { write(s, 0, s.length()); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void newLine() throws IOException { if (writer != null) { writer.write(LINE_SEPARATOR); } else { write(LINE_SEPARATOR); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(boolean b) throws IOException { if (writer != null) { writer.write(b ? "true" : "false"); } else { write(b ? "true" : "false"); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(char c) throws IOException { if (writer != null) { writer.write(String.valueOf(c)); } else { write(String.valueOf(c)); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(int i) throws IOException { if (writer != null) { writer.write(String.valueOf(i)); } else { write(String.valueOf(i)); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(long l) throws IOException { if (writer != null) { writer.write(String.valueOf(l)); } else { write(String.valueOf(l)); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(float f) throws IOException { if (writer != null) { writer.write(String.valueOf(f)); } else { write(String.valueOf(f)); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(double d) throws IOException { if (writer != null) { writer.write(String.valueOf(d)); } else { write(String.valueOf(d)); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(char[] s) throws IOException { if (writer != null) { writer.write(s); } else { write(s); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(String s) throws IOException { if (s == null) s = "null"; if (writer != null) { writer.write(s); } else { write(s); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void print(Object obj) throws IOException { if (writer != null) { writer.write(String.valueOf(obj)); } else { write(String.valueOf(obj)); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println() throws IOException { newLine(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(boolean x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(char x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(int x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(long x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(float x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(double x) throws IOException{ print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(char x[]) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(String x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void println(Object x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void clear() throws IOException { if (writer != null) { throw new IOException(); } else { nextChar = 0; if (LIMIT_BUFFER && (cb.length > Constants.DEFAULT_TAG_BUFFER_SIZE)) { cb = new char[Constants.DEFAULT_TAG_BUFFER_SIZE]; bufferSize = cb.length; } } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void clearBuffer() throws IOException { if (writer == null) { this.clear(); } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void close() throws IOException { if (writer != null) { writer.close(); } else { closed = true; } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void writeOut(Writer out) throws IOException { if (writer == null) { out.write(cb, 0, nextChar); // Flush not called as the writer passed could be a BodyContent and // it doesn't allow to flush. } }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
private void ensureOpen() throws IOException { if (closed) throw new IOException("Stream closed"); }
// in java/org/apache/jasper/runtime/HttpJspBase.java
Override public final void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { _jspService(request, response); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) throws IOException { _initialize(servlet, request, response, errorPageURL, needsSession, bufferSize, autoFlush); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void include(String relativeUrlPath) throws ServletException, IOException { JspRuntimeLibrary .include(request, response, relativeUrlPath, out, true); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void include(final String relativeUrlPath, final boolean flush) throws ServletException, IOException { if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doInclude(relativeUrlPath, flush); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doInclude(String relativeUrlPath, boolean flush) throws ServletException, IOException { JspRuntimeLibrary.include(request, response, relativeUrlPath, out, flush); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void forward(final String relativeUrlPath) throws ServletException, IOException { if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doForward(relativeUrlPath); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doForward(String relativeUrlPath) throws ServletException, IOException { // JSP.4.5 If the buffer was flushed, throw IllegalStateException try { out.clear(); } catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer .getMessage("jsp.error.attempt_to_clear_flushed_buffer")); ise.initCause(ex); throw ise; } // Make sure that the response object is not the wrapper for include while (response instanceof ServletResponseWrapperInclude) { response = ((ServletResponseWrapperInclude) response).getResponse(); } final String path = getAbsolutePathRelativeToContext(relativeUrlPath); String includeUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); if (includeUri != null) request.removeAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH); try { context.getRequestDispatcher(path).forward(request, response); } finally { if (includeUri != null) request.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH, includeUri); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void handlePageException(Exception ex) throws IOException, ServletException { // Should never be called since handleException() called with a // Throwable in the generated servlet. handlePageException((Throwable) ex); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void handlePageException(final Throwable t) throws IOException, ServletException { if (t == null) throw new NullPointerException("null Throwable"); if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doHandlePageException(t); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doHandlePageException(Throwable t) throws IOException, ServletException { if (errorPageURL != null && !errorPageURL.equals("")) { /* * Set request attributes. Do not set the * javax.servlet.error.exception attribute here (instead, set in the * generated servlet code for the error page) in order to prevent * the ErrorReportValve, which is invoked as part of forwarding the * request to the error page, from throwing it if the response has * not been committed (the response will have been committed if the * error page is a JSP page). */ request.setAttribute(PageContext.EXCEPTION, t); request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, ((HttpServletRequest) request).getRequestURI()); request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, config.getServletName()); try { forward(errorPageURL); } catch (IllegalStateException ise) { include(errorPageURL); } // The error page could be inside an include. Object newException = request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); // t==null means the attribute was not set. if ((newException != null) && (newException == t)) { request.removeAttribute(RequestDispatcher.ERROR_EXCEPTION); } // now clear the error code - to prevent double handling. request.removeAttribute(RequestDispatcher.ERROR_STATUS_CODE); request.removeAttribute(RequestDispatcher.ERROR_REQUEST_URI); request.removeAttribute(RequestDispatcher.ERROR_SERVLET_NAME); request.removeAttribute(PageContext.EXCEPTION); } else { // Otherwise throw the exception wrapped inside a ServletException. // Set the exception as the root cause in the ServletException // to get a stack trace for the real problem if (t instanceof IOException) throw (IOException) t; if (t instanceof ServletException) throw (ServletException) t; if (t instanceof RuntimeException) throw (RuntimeException) t; Throwable rootCause = null; if (t instanceof JspException) { rootCause = ((JspException) t).getCause(); } else if (t instanceof ELException) { rootCause = ((ELException) t).getCause(); } if (rootCause != null) { throw new ServletException(t.getClass().getName() + ": " + t.getMessage(), rootCause); } throw new ServletException(t); } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
protected final void flushBuffer() throws IOException { if (bufferSize == 0) return; flushed = true; ensureOpen(); if (nextChar == 0) return; initOut(); out.write(cb, 0, nextChar); nextChar = 0; }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
private void initOut() throws IOException { if (out == null) { out = response.getWriter(); } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public final void clear() throws IOException { if ((bufferSize == 0) && (out != null)) // clear() is illegal after any unbuffered output (JSP.5.5) throw new IllegalStateException( getLocalizeMessage("jsp.error.ise_on_clear")); if (flushed) throw new IOException( getLocalizeMessage("jsp.error.attempt_to_clear_flushed_buffer")); ensureOpen(); nextChar = 0; }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void clearBuffer() throws IOException { if (bufferSize == 0) throw new IllegalStateException( getLocalizeMessage("jsp.error.ise_on_clear")); ensureOpen(); nextChar = 0; }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
private final void bufferOverflow() throws IOException { throw new IOException(getLocalizeMessage("jsp.error.overflow")); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void flush() throws IOException { flushBuffer(); if (out != null) { out.flush(); } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void close() throws IOException { if (response == null || closed) // multiple calls to close is OK return; flush(); if (out != null) out.close(); out = null; closed = true; }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
private void ensureOpen() throws IOException { if (response == null || closed) throw new IOException("Stream closed"); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void write(int c) throws IOException { ensureOpen(); if (bufferSize == 0) { initOut(); out.write(c); } else { if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); cb[nextChar++] = (char) c; } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void write(char cbuf[], int off, int len) throws IOException { ensureOpen(); if (bufferSize == 0) { initOut(); out.write(cbuf, off, len); return; } if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } if (len >= bufferSize) { /* If the request length exceeds the size of the output buffer, flush the buffer and then write the data directly. In this way buffered streams will cascade harmlessly. */ if (autoFlush) flushBuffer(); else bufferOverflow(); initOut(); out.write(cbuf, off, len); return; } int b = off, t = off + len; while (b < t) { int d = min(bufferSize - nextChar, t - b); System.arraycopy(cbuf, b, cb, nextChar, d); b += d; nextChar += d; if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void write(char buf[]) throws IOException { write(buf, 0, buf.length); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void write(String s, int off, int len) throws IOException { ensureOpen(); if (bufferSize == 0) { initOut(); out.write(s, off, len); return; } int b = off, t = off + len; while (b < t) { int d = min(bufferSize - nextChar, t - b); s.getChars(b, b + d, cb, nextChar); b += d; nextChar += d; if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void write(String s) throws IOException { // Simple fix for Bugzilla 35410 // Calling the other write function so as to init the buffer anyways if(s == null) { write(s, 0, 0); } else { write(s, 0, s.length()); } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void newLine() throws IOException { write(lineSeparator); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(boolean b) throws IOException { write(b ? "true" : "false"); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(char c) throws IOException { write(String.valueOf(c)); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(int i) throws IOException { write(String.valueOf(i)); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(long l) throws IOException { write(String.valueOf(l)); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(float f) throws IOException { write(String.valueOf(f)); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(double d) throws IOException { write(String.valueOf(d)); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(char s[]) throws IOException { write(s); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(String s) throws IOException { if (s == null) { s = "null"; } write(s); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void print(Object obj) throws IOException { write(String.valueOf(obj)); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println() throws IOException { newLine(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(boolean x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(char x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(int x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(long x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(float x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(double x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(char x[]) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(String x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void println(Object x) throws IOException { print(x); println(); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void include(ServletRequest request, ServletResponse response, String relativePath, JspWriter out, boolean flush) throws IOException, ServletException { if (flush && !(out instanceof BodyContent)) out.flush(); // FIXME - It is tempting to use request.getRequestDispatcher() to // resolve a relative path directly, but Catalina currently does not // take into account whether the caller is inside a RequestDispatcher // include or not. Whether Catalina *should* take that into account // is a spec issue currently under review. In the mean time, // replicate Jasper's previous behavior String resourcePath = getContextRelativePath(request, relativePath); RequestDispatcher rd = request.getRequestDispatcher(resourcePath); rd.include(request, new ServletResponseWrapperInclude(response, out)); }
// in java/org/apache/jasper/compiler/JspUtil.java
public static InputStream getInputStream(String fname, JarFile jarFile, JspCompilationContext ctxt) throws IOException { InputStream in = null; if (jarFile != null) { String jarEntryName = fname.substring(1, fname.length()); ZipEntry jarEntry = jarFile.getEntry(jarEntryName); if (jarEntry == null) { throw new FileNotFoundException(Localizer.getMessage( "jsp.error.file.not.found", fname)); } in = jarFile.getInputStream(jarEntry); } else { in = ctxt.getResourceAsStream(fname); } if (in == null) { throw new FileNotFoundException(Localizer.getMessage( "jsp.error.file.not.found", fname)); } return in; }
// in java/org/apache/jasper/compiler/JspUtil.java
static InputStreamReader getReader(String fname, String encoding, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err) throws JasperException, IOException { return getReader(fname, encoding, jarFile, ctxt, err, 0); }
// in java/org/apache/jasper/compiler/JspUtil.java
static InputStreamReader getReader(String fname, String encoding, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err, int skip) throws JasperException, IOException { InputStreamReader reader = null; InputStream in = getInputStream(fname, jarFile, ctxt); for (int i = 0; i < skip; i++) { in.read(); } try { reader = new InputStreamReader(in, encoding); } catch (UnsupportedEncodingException ex) { err.jspError("jsp.error.unsupported.encoding", encoding); } return reader; }
// in java/org/apache/jasper/compiler/SmapUtil.java
public static String[] generateSmap( JspCompilationContext ctxt, Node.Nodes pageNodes) throws IOException { // Scan the nodes for presence of Jasper generated inner classes PreScanVisitor psVisitor = new PreScanVisitor(); try { pageNodes.visit(psVisitor); } catch (JasperException ex) { } HashMap<String, SmapStratum> map = psVisitor.getMap(); // set up our SMAP generator SmapGenerator g = new SmapGenerator(); /** Disable reading of input SMAP because: 1. There is a bug here: getRealPath() is null if .jsp is in a jar Bugzilla 14660. 2. Mappings from other sources into .jsp files are not supported. TODO: fix 1. if 2. is not true. // determine if we have an input SMAP String smapPath = inputSmapPath(ctxt.getRealPath(ctxt.getJspFile())); File inputSmap = new File(smapPath); if (inputSmap.exists()) { byte[] embeddedSmap = null; byte[] subSmap = SDEInstaller.readWhole(inputSmap); String subSmapString = new String(subSmap, SMAP_ENCODING); g.addSmap(subSmapString, "JSP"); } **/ // now, assemble info about our own stratum (JSP) using JspLineMap SmapStratum s = new SmapStratum("JSP"); g.setOutputFileName(unqualify(ctxt.getServletJavaFileName())); // Map out Node.Nodes evaluateNodes(pageNodes, s, map, ctxt.getOptions().getMappedFile()); s.optimizeLineSection(); g.addStratum(s, true); if (ctxt.getOptions().isSmapDumped()) { File outSmap = new File(ctxt.getClassFileName() + ".smap"); PrintWriter so = new PrintWriter( new OutputStreamWriter( new FileOutputStream(outSmap), SMAP_ENCODING)); so.print(g.getString()); so.close(); } String classFileName = ctxt.getClassFileName(); int innerClassCount = map.size(); String [] smapInfo = new String[2 + innerClassCount*2]; smapInfo[0] = classFileName; smapInfo[1] = g.getString(); int count = 2; Iterator<Map.Entry<String,SmapStratum>> iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String,SmapStratum> entry = iter.next(); String innerClass = entry.getKey(); s = entry.getValue(); s.optimizeLineSection(); g = new SmapGenerator(); g.setOutputFileName(unqualify(ctxt.getServletJavaFileName())); g.addStratum(s, true); String innerClassFileName = classFileName.substring(0, classFileName.indexOf(".class")) + '$' + innerClass + ".class"; if (ctxt.getOptions().isSmapDumped()) { File outSmap = new File(innerClassFileName + ".smap"); PrintWriter so = new PrintWriter( new OutputStreamWriter( new FileOutputStream(outSmap), SMAP_ENCODING)); so.print(g.getString()); so.close(); } smapInfo[count] = innerClassFileName; smapInfo[count+1] = g.getString(); count += 2; } return smapInfo; }
// in java/org/apache/jasper/compiler/SmapUtil.java
public static void installSmap(String[] smap) throws IOException { if (smap == null) { return; } for (int i = 0; i < smap.length; i += 2) { File outServlet = new File(smap[i]); SDEInstaller.install(outServlet, smap[i+1].getBytes(Constants.ISO_8859_1)); } }
// in java/org/apache/jasper/compiler/SmapUtil.java
static void install(File classFile, byte[] smap) throws IOException { File tmpFile = new File(classFile.getPath() + "tmp"); new SDEInstaller(classFile, smap, tmpFile); if (!classFile.delete()) { throw new IOException("classFile.delete() failed"); } if (!tmpFile.renameTo(classFile)) { throw new IOException("tmpFile.renameTo(classFile) failed"); } }
// in java/org/apache/jasper/compiler/SmapUtil.java
static byte[] readWhole(File input) throws IOException { FileInputStream inStream = new FileInputStream(input); int len = (int)input.length(); byte[] bytes = new byte[len]; if (inStream.read(bytes, 0, len) != len) { throw new IOException("expected size: " + len); } inStream.close(); return bytes; }
// in java/org/apache/jasper/compiler/SmapUtil.java
void addSDE() throws UnsupportedEncodingException, IOException { copy(4 + 2 + 2); // magic min/maj version int constantPoolCountPos = genPos; int constantPoolCount = readU2(); if (log.isDebugEnabled()) log.debug("constant pool count: " + constantPoolCount); writeU2(constantPoolCount); // copy old constant pool return index of SDE symbol, if found sdeIndex = copyConstantPool(constantPoolCount); if (sdeIndex < 0) { // if "SourceDebugExtension" symbol not there add it writeUtf8ForSDE(); // increment the countantPoolCount sdeIndex = constantPoolCount; ++constantPoolCount; randomAccessWriteU2(constantPoolCountPos, constantPoolCount); if (log.isDebugEnabled()) log.debug("SourceDebugExtension not found, installed at: " + sdeIndex); } else { if (log.isDebugEnabled()) log.debug("SourceDebugExtension found at: " + sdeIndex); } copy(2 + 2 + 2); // access, this, super int interfaceCount = readU2(); writeU2(interfaceCount); if (log.isDebugEnabled()) log.debug("interfaceCount: " + interfaceCount); copy(interfaceCount * 2); copyMembers(); // fields copyMembers(); // methods int attrCountPos = genPos; int attrCount = readU2(); writeU2(attrCount); if (log.isDebugEnabled()) log.debug("class attrCount: " + attrCount); // copy the class attributes, return true if SDE attr found (not copied) if (!copyAttrs(attrCount)) { // we will be adding SDE and it isn't already counted ++attrCount; randomAccessWriteU2(attrCountPos, attrCount); if (log.isDebugEnabled()) log.debug("class attrCount incremented"); } writeAttrForSDE(sdeIndex); }
// in java/org/apache/jasper/compiler/SmapUtil.java
int copyConstantPool(int constantPoolCount) throws UnsupportedEncodingException, IOException { int sdeIndex = -1; // copy const pool index zero not in class file for (int i = 1; i < constantPoolCount; ++i) { int tag = readU1(); writeU1(tag); switch (tag) { case 7 : // Class case 8 : // String if (log.isDebugEnabled()) log.debug(i + " copying 2 bytes"); copy(2); break; case 9 : // Field case 10 : // Method case 11 : // InterfaceMethod case 3 : // Integer case 4 : // Float case 12 : // NameAndType if (log.isDebugEnabled()) log.debug(i + " copying 4 bytes"); copy(4); break; case 5 : // Long case 6 : // Double if (log.isDebugEnabled()) log.debug(i + " copying 8 bytes"); copy(8); i++; break; case 1 : // Utf8 int len = readU2(); writeU2(len); byte[] utf8 = readBytes(len); String str = new String(utf8, "UTF-8"); if (log.isDebugEnabled()) log.debug(i + " read class attr -- '" + str + "'"); if (str.equals(nameSDE)) { sdeIndex = i; } writeBytes(utf8); break; default : throw new IOException("unexpected tag: " + tag); } } return sdeIndex; }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parse(String inFileName) throws FileNotFoundException, JasperException, IOException { // If we're parsing a packaged tag file or a resource included by it // (using an include directive), ctxt.getTagFileJar() returns the // JAR file from which to read the tag file or included resource, // respectively. isTagFile = ctxt.isTagFile(); directiveOnly = false; return doParse(inFileName, null, ctxt.getTagFileJarResource()); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parseDirectives(String inFileName) throws FileNotFoundException, JasperException, IOException { // If we're parsing a packaged tag file or a resource included by it // (using an include directive), ctxt.getTagFileJar() returns the // JAR file from which to read the tag file or included resource, // respectively. isTagFile = ctxt.isTagFile(); directiveOnly = true; return doParse(inFileName, null, ctxt.getTagFileJarResource()); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parse(String inFileName, Node parent, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { // For files that are statically included, isTagfile and directiveOnly // remain unchanged. return doParse(inFileName, parent, jarResource); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parseTagFileDirectives(String inFileName, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { boolean isTagFileSave = isTagFile; boolean directiveOnlySave = directiveOnly; isTagFile = true; directiveOnly = true; Node.Nodes page = doParse(inFileName, null, jarResource); directiveOnly = directiveOnlySave; isTagFile = isTagFileSave; return page; }
// in java/org/apache/jasper/compiler/ParserController.java
private Node.Nodes doParse(String inFileName, Node parent, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { Node.Nodes parsedPage = null; isEncodingSpecifiedInProlog = false; isBomPresent = false; isDefaultPageEncoding = false; JarFile jarFile = (jarResource == null) ? null : jarResource.getJarFile(); String absFileName = resolveFileName(inFileName); String jspConfigPageEnc = getJspConfigPageEncoding(absFileName); // Figure out what type of JSP document and encoding type we are // dealing with determineSyntaxAndEncoding(absFileName, jarFile, jspConfigPageEnc); if (parent != null) { // Included resource, add to dependent list if (jarFile == null) { compiler.getPageInfo().addDependant(absFileName, ctxt.getLastModified(absFileName)); } else { String entry = absFileName.substring(1); compiler.getPageInfo().addDependant( jarResource.getEntry(entry).toString(), Long.valueOf(jarFile.getEntry(entry).getTime())); } } if ((isXml && isEncodingSpecifiedInProlog) || isBomPresent) { /* * Make sure the encoding explicitly specified in the XML * prolog (if any) matches that in the JSP config element * (if any), treating "UTF-16", "UTF-16BE", and "UTF-16LE" as * identical. */ if (jspConfigPageEnc != null && !jspConfigPageEnc.equals(sourceEnc) && (!jspConfigPageEnc.startsWith("UTF-16") || !sourceEnc.startsWith("UTF-16"))) { err.jspError("jsp.error.prolog_config_encoding_mismatch", sourceEnc, jspConfigPageEnc); } } // Dispatch to the appropriate parser if (isXml) { // JSP document (XML syntax) // InputStream for jspx page is created and properly closed in // JspDocumentParser. parsedPage = JspDocumentParser.parse(this, absFileName, jarFile, parent, isTagFile, directiveOnly, sourceEnc, jspConfigPageEnc, isEncodingSpecifiedInProlog, isBomPresent); } else { // Standard syntax InputStreamReader inStreamReader = null; try { inStreamReader = JspUtil.getReader(absFileName, sourceEnc, jarFile, ctxt, err, skip); JspReader jspReader = new JspReader(ctxt, absFileName, sourceEnc, inStreamReader, err); parsedPage = Parser.parse(this, jspReader, parent, isTagFile, directiveOnly, jarResource, sourceEnc, jspConfigPageEnc, isDefaultPageEncoding, isBomPresent); } finally { if (inStreamReader != null) { try { inStreamReader.close(); } catch (Exception any) { } } } } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } baseDirStack.pop(); return parsedPage; }
// in java/org/apache/jasper/compiler/ParserController.java
private void determineSyntaxAndEncoding(String absFileName, JarFile jarFile, String jspConfigPageEnc) throws JasperException, IOException { isXml = false; /* * 'true' if the syntax (XML or standard) of the file is given * from external information: either via a JSP configuration element, * the ".jspx" suffix, or the enclosing file (for included resources) */ boolean isExternal = false; /* * Indicates whether we need to revert from temporary usage of * "ISO-8859-1" back to "UTF-8" */ boolean revert = false; JspConfig jspConfig = ctxt.getOptions().getJspConfig(); JspConfig.JspProperty jspProperty = jspConfig.findJspProperty( absFileName); if (jspProperty.isXml() != null) { // If <is-xml> is specified in a <jsp-property-group>, it is used. isXml = JspUtil.booleanValue(jspProperty.isXml()); isExternal = true; } else if (absFileName.endsWith(".jspx") || absFileName.endsWith(".tagx")) { isXml = true; isExternal = true; } if (isExternal && !isXml) { // JSP (standard) syntax. Use encoding specified in jsp-config // if provided. sourceEnc = jspConfigPageEnc; if (sourceEnc != null) { return; } // We don't know the encoding, so use BOM to determine it sourceEnc = "ISO-8859-1"; } else { // XML syntax or unknown, (auto)detect encoding ... Object[] ret = XMLEncodingDetector.getEncoding(absFileName, jarFile, ctxt, err); sourceEnc = (String) ret[0]; if (((Boolean) ret[1]).booleanValue()) { isEncodingSpecifiedInProlog = true; } if (((Boolean) ret[2]).booleanValue()) { isBomPresent = true; } skip = ((Integer) ret[3]).intValue(); if (!isXml && sourceEnc.equals("UTF-8")) { /* * We don't know if we're dealing with XML or standard syntax. * Therefore, we need to check to see if the page contains * a <jsp:root> element. * * We need to be careful, because the page may be encoded in * ISO-8859-1 (or something entirely different), and may * contain byte sequences that will cause a UTF-8 converter to * throw exceptions. * * It is safe to use a source encoding of ISO-8859-1 in this * case, as there are no invalid byte sequences in ISO-8859-1, * and the byte/character sequences we're looking for (i.e., * <jsp:root>) are identical in either encoding (both UTF-8 * and ISO-8859-1 are extensions of ASCII). */ sourceEnc = "ISO-8859-1"; revert = true; } } if (isXml) { // (This implies 'isExternal' is TRUE.) // We know we're dealing with a JSP document (via JSP config or // ".jspx" suffix), so we're done. return; } /* * At this point, 'isExternal' or 'isXml' is FALSE. * Search for jsp:root action, in order to determine if we're dealing * with XML or standard syntax (unless we already know what we're * dealing with, i.e., when 'isExternal' is TRUE and 'isXml' is FALSE). * No check for XML prolog, since nothing prevents a page from * outputting XML and still using JSP syntax (in this case, the * XML prolog is treated as template text). */ JspReader jspReader = null; try { jspReader = new JspReader(ctxt, absFileName, sourceEnc, jarFile, err); } catch (FileNotFoundException ex) { throw new JasperException(ex); } jspReader.setSingleFile(true); Mark startMark = jspReader.mark(); if (!isExternal) { jspReader.reset(startMark); if (hasJspRoot(jspReader)) { if (revert) { sourceEnc = "UTF-8"; } isXml = true; return; } else { if (revert && isBomPresent) { sourceEnc = "UTF-8"; } isXml = false; } } /* * At this point, we know we're dealing with JSP syntax. * If an XML prolog is provided, it's treated as template text. * Determine the page encoding from the page directive, unless it's * specified via JSP config. */ if (!isBomPresent) { sourceEnc = jspConfigPageEnc; if (sourceEnc == null) { sourceEnc = getPageEncodingForJspSyntax(jspReader, startMark); if (sourceEnc == null) { // Default to "ISO-8859-1" per JSP spec sourceEnc = "ISO-8859-1"; isDefaultPageEncoding = true; } } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
Override public void scan(JarURLConnection urlConn) throws IOException { tldScanJar(urlConn); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
Override public void scan(File file) throws IOException { File metaInf = new File(file, "META-INF"); if (metaInf.isDirectory()) { tldScanDir(metaInf); } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private void tldScanDir(File start) throws IOException { File[] fileList = start.listFiles(); if (fileList != null) { for (int i = 0; i < fileList.length; i++) { // Scan recursively if (fileList[i].isDirectory()) { tldScanDir(fileList[i]); } else if (fileList[i].getAbsolutePath().endsWith(TLD_EXT)) { InputStream stream = null; try { stream = new FileInputStream(fileList[i]); tldScanStream( fileList[i].toURI().toString(), null, stream); } finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } } } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private void tldScanJar(JarURLConnection jarConn) throws IOException { Jar jar = null; InputStream is; boolean foundTld = false; URL resourceURL = jarConn.getJarFileURL(); String resourcePath = resourceURL.toString(); try { jar = JarFactory.newInstance(jarConn.getURL()); jar.nextEntry(); String entryName = jar.getEntryName(); while (entryName != null) { if (entryName.startsWith("META-INF/") && entryName.endsWith(".tld")) { is = null; try { is = jar.getEntryInputStream(); foundTld = true; tldScanStream(resourcePath, entryName, is); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } } } jar.nextEntry(); entryName = jar.getEntryName(); } } finally { if (jar != null) { jar.close(); } } if (!foundTld) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.tldCache.noTldInJar", resourcePath)); } else if (showTldScanWarning) { // Not entirely thread-safe but a few duplicate log messages are // not a huge issue showTldScanWarning = false; log.info(Localizer.getMessage("jsp.tldCache.noTldSummary")); } } }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private void tldScanStream(String resourcePath, String entryName, InputStream stream) throws IOException { try { // Parse the tag library descriptor at the specified resource path String uri = null; TreeNode tld = new ParserUtils().parseXMLDocument(resourcePath, stream); TreeNode uriNode = tld.findChild("uri"); if (uriNode != null) { String body = uriNode.getBody(); if (body != null) uri = body; } // Add implicit map entry only if its uri is not already // present in the map if (uri != null && mappings.get(uri) == null) { TldLocation location; if (entryName == null) { location = new TldLocation(resourcePath); } else { location = new TldLocation(entryName, resourcePath); } mappings.put(uri, location); } } catch (JasperException e) { // Hack - makes exception handling simpler throw new IOException(e); } }
// in java/org/apache/jasper/compiler/JavacErrorDetail.java
private String[] readFile(InputStream s) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(s)); List<String> lines = new ArrayList<String>(); String line; while ( (line = reader.readLine()) != null ) { lines.add(line); } return lines.toArray( new String[lines.size()] ); }
// in java/org/apache/jasper/compiler/JarURLResource.java
Override public JarFile getJarFile() throws IOException { URL jarFileUrl = new URL("jar:" + jarUrl + "!/"); JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection(); conn.setUseCaches(false); conn.connect(); return conn.getJarFile(); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public static JavacErrorDetail[] parseJavacErrors(String errMsg, String fname, Node.Nodes page) throws JasperException, IOException { return parseJavacMessage(errMsg, fname, page); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
private static JavacErrorDetail[] parseJavacMessage( String errMsg, String fname, Node.Nodes page) throws IOException, JasperException { ArrayList<JavacErrorDetail> errors = new ArrayList<JavacErrorDetail>(); StringBuilder errMsgBuf = null; int lineNum = -1; JavacErrorDetail javacError = null; BufferedReader reader = new BufferedReader(new StringReader(errMsg)); /* * Parse compilation errors. Each compilation error consists of a file * path and error line number, followed by a number of lines describing * the error. */ String line = null; while ((line = reader.readLine()) != null) { /* * Error line number is delimited by set of colons. * Ignore colon following drive letter on Windows (fromIndex = 2). * XXX Handle deprecation warnings that don't have line info */ int beginColon = line.indexOf(':', 2); int endColon = line.indexOf(':', beginColon + 1); if ((beginColon >= 0) && (endColon >= 0)) { if (javacError != null) { // add previous error to error vector errors.add(javacError); } String lineNumStr = line.substring(beginColon + 1, endColon); try { lineNum = Integer.parseInt(lineNumStr); } catch (NumberFormatException e) { lineNum = -1; } errMsgBuf = new StringBuilder(); javacError = createJavacError(fname, page, errMsgBuf, lineNum); } // Ignore messages preceding first error if (errMsgBuf != null) { errMsgBuf.append(line); errMsgBuf.append(Constants.NEWLINE); } } // Add last error to error vector if (javacError != null) { errors.add(javacError); } reader.close(); JavacErrorDetail[] errDetails = null; if (errors.size() > 0) { errDetails = new JavacErrorDetail[errors.size()]; errors.toArray(errDetails); } return errDetails; }
// in java/org/apache/jasper/compiler/AntCompiler.java
Override public void write(byte[] b) throws IOException { findStream().write(b); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile) throws ServletException, IOException, FileNotFoundException { Servlet servlet; try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if ((available > 0L) && (available < Long.MAX_VALUE)) { if (available > System.currentTimeMillis()) { response.setDateHeader("Retry-After", available); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, Localizer.getMessage("jsp.error.unavailable")); return; } // Wait period has expired. Reset. available = 0; } /* * (1) Compile */ if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; // The following sets reload to true, if necessary ctxt.compile(); } } else { if (compileException != null) { // Throw cached compilation exception throw compileException; } } /* * (2) (Re)load servlet class file */ servlet = getServlet(); // If a page is to be precompiled only, return. if (precompile) { return; } } catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; } catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } try { /* * (3) Handle limitation of number of loaded Jsps */ if (unloadAllowed) { synchronized(this) { if (unloadByCount) { if (unloadHandle == null) { unloadHandle = ctxt.getRuntimeContext().push(this); } else if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { ctxt.getRuntimeContext().makeYoungest(unloadHandle); lastUsageTime = System.currentTimeMillis(); } } else { if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { lastUsageTime = System.currentTimeMillis(); } } } } /* * (4) Service request */ if (servlet instanceof SingleThreadModel) { // sync on the wrapper so that the freshness // of the page is determined right before servicing synchronized (this) { servlet.service(request, response); } } else { servlet.service(request, response); } } catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); } catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public void init(ServletConfig config) throws ServletException { super.init(config); this.config = config; this.context = config.getServletContext(); // Initialize the JSP Runtime Context // Check for a custom Options implementation String engineOptionsName = config.getInitParameter("engineOptionsClass"); if (engineOptionsName != null) { // Instantiate the indicated Options implementation try { ClassLoader loader = Thread.currentThread() .getContextClassLoader(); Class<?> engineOptionsClass = loader.loadClass(engineOptionsName); Class<?>[] ctorSig = { ServletConfig.class, ServletContext.class }; Constructor<?> ctor = engineOptionsClass.getConstructor(ctorSig); Object[] args = { config, context }; options = (Options) ctor.newInstance(args); } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); // Need to localize this. log.warn("Failed to load engineOptionsClass", e); // Use the default Options implementation options = new EmbeddedServletOptions(config, context); } } else { // Use the default Options implementation options = new EmbeddedServletOptions(config, context); } rctxt = new JspRuntimeContext(context, options); if (config.getInitParameter("jspFile") != null) { jspFile = config.getInitParameter("jspFile"); try { if (null == context.getResource(jspFile)) { throw new ServletException("missing jspFile"); } } catch (MalformedURLException e) { throw new ServletException("Can not locate jsp file", e); } try { if (SecurityUtil.isPackageProtectionEnabled()){ AccessController.doPrivileged(new PrivilegedExceptionAction<Object>(){ @Override public Object run() throws IOException, ServletException { serviceJspFile(null, null, jspFile, true); return null; } }); } else { serviceJspFile(null, null, jspFile, true); } } catch (IOException e) { throw new ServletException("Could not precompile jsp: " + jspFile, e); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ServletException) throw (ServletException)t; throw new ServletException("Could not precompile jsp: " + jspFile, e); } }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public Object run() throws IOException, ServletException { serviceJspFile(null, null, jspFile, true); return null; }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //jspFile may be configured as an init-param for this servlet instance String jspUri = jspFile; if (jspUri == null) { // JSP specified via <jsp-file> in <servlet> declaration and supplied through //custom servlet container code jspUri = (String) request.getAttribute(Constants.JSP_FILE); } if (jspUri == null) { /* * Check to see if the requested JSP has been the target of a * RequestDispatcher.include() */ jspUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); if (jspUri != null) { /* * Requested JSP has been target of * RequestDispatcher.include(). Its path is assembled from the * relevant javax.servlet.include.* request attributes */ String pathInfo = (String) request.getAttribute( RequestDispatcher.INCLUDE_PATH_INFO); if (pathInfo != null) { jspUri += pathInfo; } } else { /* * Requested JSP has not been the target of a * RequestDispatcher.include(). Reconstruct its path from the * request's getServletPath() and getPathInfo() */ jspUri = request.getServletPath(); String pathInfo = request.getPathInfo(); if (pathInfo != null) { jspUri += pathInfo; } } } if (log.isDebugEnabled()) { log.debug("JspEngine --> " + jspUri); log.debug("\t ServletPath: " + request.getServletPath()); log.debug("\t PathInfo: " + request.getPathInfo()); log.debug("\t RealPath: " + context.getRealPath(jspUri)); log.debug("\t RequestURI: " + request.getRequestURI()); log.debug("\t QueryString: " + request.getQueryString()); } try { boolean precompile = preCompile(request); serviceJspFile(request, response, jspUri, precompile); } catch (RuntimeException e) { throw e; } catch (ServletException e) { throw e; } catch (IOException e) { throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException(e); } }
// in java/org/apache/jasper/servlet/JspServlet.java
private void serviceJspFile(HttpServletRequest request, HttpServletResponse response, String jspUri, boolean precompile) throws ServletException, IOException { JspServletWrapper wrapper = rctxt.getWrapper(jspUri); if (wrapper == null) { synchronized(this) { wrapper = rctxt.getWrapper(jspUri); if (wrapper == null) { // Check if the requested JSP page exists, to avoid // creating unnecessary directories and files. if (null == context.getResource(jspUri)) { handleMissingResource(request, response, jspUri); return; } wrapper = new JspServletWrapper(config, options, jspUri, rctxt); rctxt.addWrapper(jspUri,wrapper); } } } try { wrapper.service(request, response, precompile); } catch (FileNotFoundException fnfe) { handleMissingResource(request, response, jspUri); } }
// in java/org/apache/jasper/servlet/JspServlet.java
private void handleMissingResource(HttpServletRequest request, HttpServletResponse response, String jspUri) throws ServletException, IOException { String includeRequestUri = (String)request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored String msg = Localizer.getMessage("jsp.error.file.not.found",jspUri); // Strictly, filtering this is an application // responsibility but just in case... throw new ServletException(SecurityUtil.filter(msg)); } else { try { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); } catch (IllegalStateException ise) { log.error(Localizer.getMessage("jsp.error.file.not.found", jspUri)); } } return; }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(this.mark); out.writeObject(this.target); }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.mark = in.readUTF(); this.target = (MethodExpression) in.readObject(); }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(this.mark); out.writeObject(this.target); }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.mark = in.readUTF(); this.target = (ValueExpression) in.readObject(); }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public static Object[] getEncoding(String fname, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err) throws IOException, JasperException { InputStream inStream = JspUtil.getInputStream(fname, jarFile, ctxt); XMLEncodingDetector detector = new XMLEncodingDetector(); Object[] ret = detector.getEncoding(inStream, err); inStream.close(); return ret; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private Object[] getEncoding(InputStream in, ErrorDispatcher err) throws IOException, JasperException { this.stream = in; this.err=err; createInitialReader(); scanXMLDecl(); return new Object[] { this.encoding, Boolean.valueOf(this.isEncodingSetInProlog), Boolean.valueOf(this.isBomPresent), Integer.valueOf(this.skip) }; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void createInitialReader() throws IOException, JasperException { // wrap this stream in RewindableInputStream stream = new RewindableInputStream(stream); // perform auto-detect of encoding if necessary if (encoding == null) { // read first four bytes and determine encoding final byte[] b4 = new byte[4]; int count = 0; for (; count<4; count++ ) { b4[count] = (byte)stream.read(); } if (count == 4) { Object [] encodingDesc = getEncodingName(b4, count); encoding = (String)(encodingDesc[0]); isBigEndian = (Boolean)(encodingDesc[1]); if (encodingDesc.length > 3) { isBomPresent = ((Boolean)(encodingDesc[2])).booleanValue(); skip = ((Integer)(encodingDesc[3])).intValue(); } else { isBomPresent = true; skip = ((Integer)(encodingDesc[2])).intValue(); } stream.reset(); // Special case UTF-8 files with BOM created by Microsoft // tools. It's more efficient to consume the BOM than make // the reader perform extra checks. -Ac if (count > 2 && encoding.equals("UTF-8")) { int b0 = b4[0] & 0xFF; int b1 = b4[1] & 0xFF; int b2 = b4[2] & 0xFF; if (b0 == 0xEF && b1 == 0xBB && b2 == 0xBF) { // ignore first three bytes... long skipped = stream.skip(3); if (skipped != 3) { throw new IOException(Localizer.getMessage( "xmlParser.skipBomFail")); } } } reader = createReader(stream, encoding, isBigEndian); } else { reader = createReader(stream, encoding, isBigEndian); } } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private Reader createReader(InputStream inputStream, String encoding, Boolean isBigEndian) throws IOException, JasperException { // normalize encoding name if (encoding == null) { encoding = "UTF-8"; } // try to use an optimized reader String ENCODING = encoding.toUpperCase(Locale.ENGLISH); if (ENCODING.equals("UTF-8")) { return new UTF8Reader(inputStream, fBufferSize); } if (ENCODING.equals("US-ASCII")) { return new ASCIIReader(inputStream, fBufferSize); } if (ENCODING.equals("ISO-10646-UCS-4")) { if (isBigEndian != null) { boolean isBE = isBigEndian.booleanValue(); if (isBE) { return new UCSReader(inputStream, UCSReader.UCS4BE); } else { return new UCSReader(inputStream, UCSReader.UCS4LE); } } else { err.jspError("jsp.error.xml.encodingByteOrderUnsupported", encoding); } } if (ENCODING.equals("ISO-10646-UCS-2")) { if (isBigEndian != null) { // sould never happen with this encoding... boolean isBE = isBigEndian.booleanValue(); if (isBE) { return new UCSReader(inputStream, UCSReader.UCS2BE); } else { return new UCSReader(inputStream, UCSReader.UCS2LE); } } else { err.jspError("jsp.error.xml.encodingByteOrderUnsupported", encoding); } } // check for valid name boolean validIANA = XMLChar.isValidIANAEncoding(encoding); boolean validJava = XMLChar.isValidJavaEncoding(encoding); if (!validIANA || (fAllowJavaEncodings && !validJava)) { err.jspError("jsp.error.xml.encodingDeclInvalid", encoding); // NOTE: AndyH suggested that, on failure, we use ISO Latin 1 // because every byte is a valid ISO Latin 1 character. // It may not translate correctly but if we failed on // the encoding anyway, then we're expecting the content // of the document to be bad. This will just prevent an // invalid UTF-8 sequence to be detected. This is only // important when continue-after-fatal-error is turned // on. -Ac encoding = "ISO-8859-1"; } // try to use a Java reader String javaEncoding = EncodingMap.getIANA2JavaMapping(ENCODING); if (javaEncoding == null) { if (fAllowJavaEncodings) { javaEncoding = encoding; } else { err.jspError("jsp.error.xml.encodingDeclInvalid", encoding); // see comment above. javaEncoding = "ISO8859_1"; } } return new InputStreamReader(inputStream, javaEncoding); }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public int peekChar() throws IOException { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } // peek at character int c = fCurrentEntity.ch[fCurrentEntity.position]; // return peeked character if (fCurrentEntity.isExternal()) { return c != '\r' ? c : '\n'; } else { return c; } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public int scanChar() throws IOException { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } // scan character int c = fCurrentEntity.ch[fCurrentEntity.position++]; boolean external = false; if (c == '\n' || (c == '\r' && (external = fCurrentEntity.isExternal()))) { if (fCurrentEntity.position == fCurrentEntity.count) { fCurrentEntity.ch[0] = (char)c; load(1, false); } if (c == '\r' && external) { if (fCurrentEntity.ch[fCurrentEntity.position++] != '\n') { fCurrentEntity.position--; } c = '\n'; } } // return character that was scanned return c; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public String scanName() throws IOException { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } // scan name int offset = fCurrentEntity.position; if (XMLChar.isNameStart(fCurrentEntity.ch[offset])) { if (++fCurrentEntity.position == fCurrentEntity.count) { fCurrentEntity.ch[0] = fCurrentEntity.ch[offset]; offset = 0; if (load(1, false)) { String symbol = fSymbolTable.addSymbol(fCurrentEntity.ch, 0, 1); return symbol; } } while (XMLChar.isName(fCurrentEntity.ch[fCurrentEntity.position])) { if (++fCurrentEntity.position == fCurrentEntity.count) { int length = fCurrentEntity.position - offset; if (length == fBufferSize) { // bad luck we have to resize our buffer char[] tmp = new char[fBufferSize * 2]; System.arraycopy(fCurrentEntity.ch, offset, tmp, 0, length); fCurrentEntity.ch = tmp; fBufferSize *= 2; } else { System.arraycopy(fCurrentEntity.ch, offset, fCurrentEntity.ch, 0, length); } offset = 0; if (load(length, false)) { break; } } } } int length = fCurrentEntity.position - offset; // return name String symbol = null; if (length > 0) { symbol = fSymbolTable.addSymbol(fCurrentEntity.ch, offset, length); } return symbol; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public int scanLiteral(int quote, XMLString content) throws IOException { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } else if (fCurrentEntity.position == fCurrentEntity.count - 1) { fCurrentEntity.ch[0] = fCurrentEntity.ch[fCurrentEntity.count - 1]; load(1, false); fCurrentEntity.position = 0; } // normalize newlines int offset = fCurrentEntity.position; int c = fCurrentEntity.ch[offset]; int newlines = 0; boolean external = fCurrentEntity.isExternal(); if (c == '\n' || (c == '\r' && external)) { do { c = fCurrentEntity.ch[fCurrentEntity.position++]; if (c == '\r' && external) { newlines++; if (fCurrentEntity.position == fCurrentEntity.count) { offset = 0; fCurrentEntity.position = newlines; if (load(newlines, false)) { break; } } if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') { fCurrentEntity.position++; offset++; } /*** NEWLINE NORMALIZATION ***/ else { newlines++; } /***/ } else if (c == '\n') { newlines++; if (fCurrentEntity.position == fCurrentEntity.count) { offset = 0; fCurrentEntity.position = newlines; if (load(newlines, false)) { break; } } /*** NEWLINE NORMALIZATION *** if (fCurrentEntity.ch[fCurrentEntity.position] == '\r' && external) { fCurrentEntity.position++; offset++; } /***/ } else { fCurrentEntity.position--; break; } } while (fCurrentEntity.position < fCurrentEntity.count - 1); for (int i = offset; i < fCurrentEntity.position; i++) { fCurrentEntity.ch[i] = '\n'; } int length = fCurrentEntity.position - offset; if (fCurrentEntity.position == fCurrentEntity.count - 1) { content.setValues(fCurrentEntity.ch, offset, length); return -1; } } // scan literal value while (fCurrentEntity.position < fCurrentEntity.count) { c = fCurrentEntity.ch[fCurrentEntity.position++]; if ((c == quote && (!fCurrentEntity.literal || external)) || c == '%' || !XMLChar.isContent(c)) { fCurrentEntity.position--; break; } } int length = fCurrentEntity.position - offset; content.setValues(fCurrentEntity.ch, offset, length); // return next character if (fCurrentEntity.position != fCurrentEntity.count) { c = fCurrentEntity.ch[fCurrentEntity.position]; // NOTE: We don't want to accidentally signal the // end of the literal if we're expanding an // entity appearing in the literal. -Ac if (c == quote && fCurrentEntity.literal) { c = -1; } } else { c = -1; } return c; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public boolean scanData(String delimiter, XMLStringBuffer buffer) throws IOException { boolean done = false; int delimLen = delimiter.length(); char charAt0 = delimiter.charAt(0); boolean external = fCurrentEntity.isExternal(); do { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } else if (fCurrentEntity.position >= fCurrentEntity.count - delimLen) { System.arraycopy(fCurrentEntity.ch, fCurrentEntity.position, fCurrentEntity.ch, 0, fCurrentEntity.count - fCurrentEntity.position); load(fCurrentEntity.count - fCurrentEntity.position, false); fCurrentEntity.position = 0; } if (fCurrentEntity.position >= fCurrentEntity.count - delimLen) { // something must be wrong with the input: e.g., file ends an // unterminated comment int length = fCurrentEntity.count - fCurrentEntity.position; buffer.append (fCurrentEntity.ch, fCurrentEntity.position, length); fCurrentEntity.position = fCurrentEntity.count; load(0,true); return false; } // normalize newlines int offset = fCurrentEntity.position; int c = fCurrentEntity.ch[offset]; int newlines = 0; if (c == '\n' || (c == '\r' && external)) { do { c = fCurrentEntity.ch[fCurrentEntity.position++]; if (c == '\r' && external) { newlines++; if (fCurrentEntity.position == fCurrentEntity.count) { offset = 0; fCurrentEntity.position = newlines; if (load(newlines, false)) { break; } } if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') { fCurrentEntity.position++; offset++; } /*** NEWLINE NORMALIZATION ***/ else { newlines++; } } else if (c == '\n') { newlines++; if (fCurrentEntity.position == fCurrentEntity.count) { offset = 0; fCurrentEntity.position = newlines; fCurrentEntity.count = newlines; if (load(newlines, false)) { break; } } } else { fCurrentEntity.position--; break; } } while (fCurrentEntity.position < fCurrentEntity.count - 1); for (int i = offset; i < fCurrentEntity.position; i++) { fCurrentEntity.ch[i] = '\n'; } int length = fCurrentEntity.position - offset; if (fCurrentEntity.position == fCurrentEntity.count - 1) { buffer.append(fCurrentEntity.ch, offset, length); return true; } } // iterate over buffer looking for delimiter OUTER: while (fCurrentEntity.position < fCurrentEntity.count) { c = fCurrentEntity.ch[fCurrentEntity.position++]; if (c == charAt0) { // looks like we just hit the delimiter int delimOffset = fCurrentEntity.position - 1; for (int i = 1; i < delimLen; i++) { if (fCurrentEntity.position == fCurrentEntity.count) { fCurrentEntity.position -= i; break OUTER; } c = fCurrentEntity.ch[fCurrentEntity.position++]; if (delimiter.charAt(i) != c) { fCurrentEntity.position--; break; } } if (fCurrentEntity.position == delimOffset + delimLen) { done = true; break; } } else if (c == '\n' || (external && c == '\r')) { fCurrentEntity.position--; break; } else if (XMLChar.isInvalid(c)) { fCurrentEntity.position--; int length = fCurrentEntity.position - offset; buffer.append(fCurrentEntity.ch, offset, length); return true; } } int length = fCurrentEntity.position - offset; if (done) { length -= delimLen; } buffer.append (fCurrentEntity.ch, offset, length); // return true if string was skipped } while (!done); return !done; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public boolean skipChar(int c) throws IOException { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } // skip character int cc = fCurrentEntity.ch[fCurrentEntity.position]; if (cc == c) { fCurrentEntity.position++; return true; } else if (c == '\n' && cc == '\r' && fCurrentEntity.isExternal()) { // handle newlines if (fCurrentEntity.position == fCurrentEntity.count) { fCurrentEntity.ch[0] = (char)cc; load(1, false); } fCurrentEntity.position++; if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') { fCurrentEntity.position++; } return true; } // character was not skipped return false; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public boolean skipSpaces() throws IOException { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } // skip spaces int c = fCurrentEntity.ch[fCurrentEntity.position]; if (XMLChar.isSpace(c)) { boolean external = fCurrentEntity.isExternal(); do { boolean entityChanged = false; // handle newlines if (c == '\n' || (external && c == '\r')) { if (fCurrentEntity.position == fCurrentEntity.count - 1) { fCurrentEntity.ch[0] = (char)c; entityChanged = load(1, true); if (!entityChanged) // the load change the position to be 1, // need to restore it when entity not changed fCurrentEntity.position = 0; } if (c == '\r' && external) { // REVISIT: Does this need to be updated to fix the // #x0D ^#x0A newline normalization problem? -Ac if (fCurrentEntity.ch[++fCurrentEntity.position] != '\n') { fCurrentEntity.position--; } } /*** NEWLINE NORMALIZATION *** else { if (fCurrentEntity.ch[fCurrentEntity.position + 1] == '\r' && external) { fCurrentEntity.position++; } } /***/ } // load more characters, if needed if (!entityChanged) fCurrentEntity.position++; if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } } while (XMLChar.isSpace(c = fCurrentEntity.ch[fCurrentEntity.position])); return true; } // no spaces were found return false; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public boolean skipString(String s) throws IOException { // load more characters, if needed if (fCurrentEntity.position == fCurrentEntity.count) { load(0, true); } // skip string final int length = s.length(); for (int i = 0; i < length; i++) { char c = fCurrentEntity.ch[fCurrentEntity.position++]; if (c != s.charAt(i)) { fCurrentEntity.position -= i + 1; return false; } if (i < length - 1 && fCurrentEntity.position == fCurrentEntity.count) { System.arraycopy(fCurrentEntity.ch, fCurrentEntity.count - i - 1, fCurrentEntity.ch, 0, i + 1); // REVISIT: Can a string to be skipped cross an // entity boundary? -Ac if (load(i + 1, false)) { fCurrentEntity.position -= i + 1; return false; } } } return true; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
final boolean load(int offset, boolean changeEntity) throws IOException { // read characters int length = fCurrentEntity.mayReadChunks? (fCurrentEntity.ch.length - offset): (DEFAULT_XMLDECL_BUFFER_SIZE); int count = fCurrentEntity.reader.read(fCurrentEntity.ch, offset, length); // reset count and position boolean entityChanged = false; if (count != -1) { if (count != 0) { fCurrentEntity.count = count + offset; fCurrentEntity.position = offset; } } // end of this entity else { fCurrentEntity.count = offset; fCurrentEntity.position = offset; entityChanged = true; if (changeEntity) { endEntity(); if (fCurrentEntity == null) { throw new EOFException(); } // handle the trailing edges if (fCurrentEntity.position == fCurrentEntity.count) { load(0, false); } } } return entityChanged; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
Override public int read() throws IOException { int b = 0; if (fOffset < fLength) { return fData[fOffset++] & 0xff; } if (fOffset == fEndOffset) { return -1; } if (fOffset == fData.length) { byte[] newData = new byte[fOffset << 1]; System.arraycopy(fData, 0, newData, 0, fOffset); fData = newData; } b = fInputStream.read(); if (b == -1) { fEndOffset = fOffset; return -1; } fData[fLength++] = (byte)b; fOffset++; return b & 0xff; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
Override public int read(byte[] b, int off, int len) throws IOException { int bytesLeft = fLength - fOffset; if (bytesLeft == 0) { if (fOffset == fEndOffset) { return -1; } // better get some more for the voracious reader... if (fCurrentEntity.mayReadChunks) { return fInputStream.read(b, off, len); } int returnedVal = read(); if (returnedVal == -1) { fEndOffset = fOffset; return -1; } b[off] = (byte)returnedVal; return 1; } if (len < bytesLeft) { if (len <= 0) { return 0; } } else { len = bytesLeft; } if (b != null) { System.arraycopy(fData, fOffset, b, off, len); } fOffset += len; return len; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
Override public long skip(long n) throws IOException { int bytesLeft; if (n <= 0) { return 0; } bytesLeft = fLength - fOffset; if (bytesLeft == 0) { if (fOffset == fEndOffset) { return 0; } return fInputStream.skip(n); } if (n <= bytesLeft) { fOffset += n; return n; } fOffset += bytesLeft; if (fOffset == fEndOffset) { return bytesLeft; } n -= bytesLeft; /* * In a manner of speaking, when this class isn't permitting more * than one byte at a time to be read, it is "blocking". The * available() method should indicate how much can be read without * blocking, so while we're in this mode, it should only indicate * that bytes in its buffer are available; otherwise, the result of * available() on the underlying InputStream is appropriate. */ return fInputStream.skip(n) + bytesLeft; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
Override public int available() throws IOException { int bytesLeft = fLength - fOffset; if (bytesLeft == 0) { if (fOffset == fEndOffset) { return -1; } return fCurrentEntity.mayReadChunks ? fInputStream.available() : 0; } return bytesLeft; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
Override public void close() throws IOException { if (fInputStream != null) { fInputStream.close(); fInputStream = null; } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanXMLDecl() throws IOException, JasperException { if (skipString("<?xml")) { // NOTE: special case where document starts with a PI // whose name starts with "xml" (e.g. "xmlfoo") if (XMLChar.isName(peekChar())) { fStringBuffer.clear(); fStringBuffer.append("xml"); while (XMLChar.isName(peekChar())) { fStringBuffer.append((char)scanChar()); } String target = fSymbolTable.addSymbol(fStringBuffer.ch, fStringBuffer.offset, fStringBuffer.length); scanPIData(target, fString); } // standard XML declaration else { scanXMLDeclOrTextDecl(false); } } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanXMLDeclOrTextDecl(boolean scanningTextDecl) throws IOException, JasperException { // scan decl scanXMLDeclOrTextDecl(scanningTextDecl, fStrings); // pseudo-attribute values String encodingPseudoAttr = fStrings[1]; // set encoding on reader if (encodingPseudoAttr != null) { isEncodingSetInProlog = true; encoding = encodingPseudoAttr; } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanXMLDeclOrTextDecl(boolean scanningTextDecl, String[] pseudoAttributeValues) throws IOException, JasperException { // pseudo-attribute values String version = null; String encoding = null; String standalone = null; // scan pseudo-attributes final int STATE_VERSION = 0; final int STATE_ENCODING = 1; final int STATE_STANDALONE = 2; final int STATE_DONE = 3; int state = STATE_VERSION; boolean dataFoundForTarget = false; boolean sawSpace = skipSpaces(); while (peekChar() != '?') { dataFoundForTarget = true; String name = scanPseudoAttribute(scanningTextDecl, fString); switch (state) { case STATE_VERSION: { if (name == fVersionSymbol) { if (!sawSpace) { reportFatalError(scanningTextDecl ? "jsp.error.xml.spaceRequiredBeforeVersionInTextDecl" : "jsp.error.xml.spaceRequiredBeforeVersionInXMLDecl", null); } version = fString.toString(); state = STATE_ENCODING; if (!version.equals("1.0")) { // REVISIT: XML REC says we should throw an error // in such cases. // some may object the throwing of fatalError. err.jspError("jsp.error.xml.versionNotSupported", version); } } else if (name == fEncodingSymbol) { if (!scanningTextDecl) { err.jspError("jsp.error.xml.versionInfoRequired"); } if (!sawSpace) { reportFatalError(scanningTextDecl ? "jsp.error.xml.spaceRequiredBeforeEncodingInTextDecl" : "jsp.error.xml.spaceRequiredBeforeEncodingInXMLDecl", null); } encoding = fString.toString(); state = scanningTextDecl ? STATE_DONE : STATE_STANDALONE; } else { if (scanningTextDecl) { err.jspError("jsp.error.xml.encodingDeclRequired"); } else { err.jspError("jsp.error.xml.versionInfoRequired"); } } break; } case STATE_ENCODING: { if (name == fEncodingSymbol) { if (!sawSpace) { reportFatalError(scanningTextDecl ? "jsp.error.xml.spaceRequiredBeforeEncodingInTextDecl" : "jsp.error.xml.spaceRequiredBeforeEncodingInXMLDecl", null); } encoding = fString.toString(); state = scanningTextDecl ? STATE_DONE : STATE_STANDALONE; // TODO: check encoding name; set encoding on // entity scanner } else if (!scanningTextDecl && name == fStandaloneSymbol) { if (!sawSpace) { err.jspError("jsp.error.xml.spaceRequiredBeforeStandalone"); } standalone = fString.toString(); state = STATE_DONE; if (!standalone.equals("yes") && !standalone.equals("no")) { err.jspError("jsp.error.xml.sdDeclInvalid"); } } else { err.jspError("jsp.error.xml.encodingDeclRequired"); } break; } case STATE_STANDALONE: { if (name == fStandaloneSymbol) { if (!sawSpace) { err.jspError("jsp.error.xml.spaceRequiredBeforeStandalone"); } standalone = fString.toString(); state = STATE_DONE; if (!standalone.equals("yes") && !standalone.equals("no")) { err.jspError("jsp.error.xml.sdDeclInvalid"); } } else { err.jspError("jsp.error.xml.encodingDeclRequired"); } break; } default: { err.jspError("jsp.error.xml.noMorePseudoAttributes"); } } sawSpace = skipSpaces(); } // REVISIT: should we remove this error reporting? if (scanningTextDecl && state != STATE_DONE) { err.jspError("jsp.error.xml.morePseudoAttributes"); } // If there is no data in the xml or text decl then we fail to report // error for version or encoding info above. if (scanningTextDecl) { if (!dataFoundForTarget && encoding == null) { err.jspError("jsp.error.xml.encodingDeclRequired"); } } else { if (!dataFoundForTarget && version == null) { err.jspError("jsp.error.xml.versionInfoRequired"); } } // end if (!skipChar('?')) { err.jspError("jsp.error.xml.xmlDeclUnterminated"); } if (!skipChar('>')) { err.jspError("jsp.error.xml.xmlDeclUnterminated"); } // fill in return array pseudoAttributeValues[0] = version; pseudoAttributeValues[1] = encoding; pseudoAttributeValues[2] = standalone; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public String scanPseudoAttribute(boolean scanningTextDecl, XMLString value) throws IOException, JasperException { String name = scanName(); if (name == null) { err.jspError("jsp.error.xml.pseudoAttrNameExpected"); } skipSpaces(); if (!skipChar('=')) { reportFatalError(scanningTextDecl ? "jsp.error.xml.eqRequiredInTextDecl" : "jsp.error.xml.eqRequiredInXMLDecl", name); } skipSpaces(); int quote = peekChar(); if (quote != '\'' && quote != '"') { reportFatalError(scanningTextDecl ? "jsp.error.xml.quoteRequiredInTextDecl" : "jsp.error.xml.quoteRequiredInXMLDecl" , name); } scanChar(); int c = scanLiteral(quote, value); if (c != quote) { fStringBuffer2.clear(); do { fStringBuffer2.append(value); if (c != -1) { if (c == '&' || c == '%' || c == '<' || c == ']') { fStringBuffer2.append((char)scanChar()); } else if (XMLChar.isHighSurrogate(c)) { scanSurrogates(fStringBuffer2); } else if (XMLChar.isInvalid(c)) { String key = scanningTextDecl ? "jsp.error.xml.invalidCharInTextDecl" : "jsp.error.xml.invalidCharInXMLDecl"; reportFatalError(key, Integer.toString(c, 16)); scanChar(); } } c = scanLiteral(quote, value); } while (c != quote); fStringBuffer2.append(value); value.setValues(fStringBuffer2); } if (!skipChar(quote)) { reportFatalError(scanningTextDecl ? "jsp.error.xml.closeQuoteMissingInTextDecl" : "jsp.error.xml.closeQuoteMissingInXMLDecl", name); } // return return name; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanPIData(String target, XMLString data) throws IOException, JasperException { // check target if (target.length() == 3) { char c0 = Character.toLowerCase(target.charAt(0)); char c1 = Character.toLowerCase(target.charAt(1)); char c2 = Character.toLowerCase(target.charAt(2)); if (c0 == 'x' && c1 == 'm' && c2 == 'l') { err.jspError("jsp.error.xml.reservedPITarget"); } } // spaces if (!skipSpaces()) { if (skipString("?>")) { // we found the end, there is no data data.clear(); return; } else { // if there is data there should be some space err.jspError("jsp.error.xml.spaceRequiredInPI"); } } fStringBuffer.clear(); // data if (scanData("?>", fStringBuffer)) { do { int c = peekChar(); if (c != -1) { if (XMLChar.isHighSurrogate(c)) { scanSurrogates(fStringBuffer); } else if (XMLChar.isInvalid(c)) { err.jspError("jsp.error.xml.invalidCharInPI", Integer.toHexString(c)); scanChar(); } } } while (scanData("?>", fStringBuffer)); } data.setValues(fStringBuffer); }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private boolean scanSurrogates(XMLStringBuffer buf) throws IOException, JasperException { int high = scanChar(); int low = peekChar(); if (!XMLChar.isLowSurrogate(low)) { err.jspError("jsp.error.xml.invalidCharInContent", Integer.toString(high, 16)); return false; } scanChar(); // convert surrogates to supplemental character int c = XMLChar.supplemental((char)high, (char)low); // supplemental character must be a valid XML character if (!XMLChar.isValid(c)) { err.jspError("jsp.error.xml.invalidCharInContent", Integer.toString(c, 16)); return false; } // fill in the buffer buf.append((char)high); buf.append((char)low); return true; }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public int read() throws IOException { // decode character int c = fSurrogate; if (fSurrogate == -1) { // NOTE: We use the index into the buffer if there are remaining // bytes from the last block read. -Ac int index = 0; // get first byte int b0 = index == fOffset ? fInputStream.read() : fBuffer[index++] & 0x00FF; if (b0 == -1) { return -1; } // UTF-8: [0xxx xxxx] // Unicode: [0000 0000] [0xxx xxxx] if (b0 < 0x80) { c = (char)b0; } // UTF-8: [110y yyyy] [10xx xxxx] // Unicode: [0000 0yyy] [yyxx xxxx] else if ((b0 & 0xE0) == 0xC0) { int b1 = index == fOffset ? fInputStream.read() : fBuffer[index++] & 0x00FF; if (b1 == -1) { expectedByte(2, 2); } if ((b1 & 0xC0) != 0x80) { invalidByte(2, 2); } c = ((b0 << 6) & 0x07C0) | (b1 & 0x003F); } // UTF-8: [1110 zzzz] [10yy yyyy] [10xx xxxx] // Unicode: [zzzz yyyy] [yyxx xxxx] else if ((b0 & 0xF0) == 0xE0) { int b1 = index == fOffset ? fInputStream.read() : fBuffer[index++] & 0x00FF; if (b1 == -1) { expectedByte(2, 3); } if ((b1 & 0xC0) != 0x80) { invalidByte(2, 3); } int b2 = index == fOffset ? fInputStream.read() : fBuffer[index++] & 0x00FF; if (b2 == -1) { expectedByte(3, 3); } if ((b2 & 0xC0) != 0x80) { invalidByte(3, 3); } c = ((b0 << 12) & 0xF000) | ((b1 << 6) & 0x0FC0) | (b2 & 0x003F); } // UTF-8: [1111 0uuu] [10uu zzzz] [10yy yyyy] [10xx xxxx]* // Unicode: [1101 10ww] [wwzz zzyy] (high surrogate) // [1101 11yy] [yyxx xxxx] (low surrogate) // * uuuuu = wwww + 1 else if ((b0 & 0xF8) == 0xF0) { int b1 = index == fOffset ? fInputStream.read() : fBuffer[index++] & 0x00FF; if (b1 == -1) { expectedByte(2, 4); } if ((b1 & 0xC0) != 0x80) { invalidByte(2, 3); } int b2 = index == fOffset ? fInputStream.read() : fBuffer[index++] & 0x00FF; if (b2 == -1) { expectedByte(3, 4); } if ((b2 & 0xC0) != 0x80) { invalidByte(3, 3); } int b3 = index == fOffset ? fInputStream.read() : fBuffer[index++] & 0x00FF; if (b3 == -1) { expectedByte(4, 4); } if ((b3 & 0xC0) != 0x80) { invalidByte(4, 4); } int uuuuu = ((b0 << 2) & 0x001C) | ((b1 >> 4) & 0x0003); if (uuuuu > 0x10) { invalidSurrogate(uuuuu); } int wwww = uuuuu - 1; int hs = 0xD800 | ((wwww << 6) & 0x03C0) | ((b1 << 2) & 0x003C) | ((b2 >> 4) & 0x0003); int ls = 0xDC00 | ((b2 << 6) & 0x03C0) | (b3 & 0x003F); c = hs; fSurrogate = ls; } // error else { invalidByte(1, 1); } } // use surrogate else { fSurrogate = -1; } // return character if (DEBUG_READ) { if (log.isDebugEnabled()) log.debug("read(): 0x"+Integer.toHexString(c)); } return c; }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public int read(char ch[], int offset, int length) throws IOException { // handle surrogate int out = offset; if (fSurrogate != -1) { ch[offset + 1] = (char)fSurrogate; fSurrogate = -1; length--; out++; } // read bytes int count = 0; if (fOffset == 0) { // adjust length to read if (length > fBuffer.length) { length = fBuffer.length; } // perform read operation count = fInputStream.read(fBuffer, 0, length); if (count == -1) { return -1; } count += out - offset; } // skip read; last character was in error // NOTE: Having an offset value other than zero means that there was // an error in the last character read. In this case, we have // skipped the read so we don't consume any bytes past the // error. By signaling the error on the next block read we // allow the method to return the most valid characters that // it can on the previous block read. -Ac else { count = fOffset; fOffset = 0; } // convert bytes to characters final int total = count; for (int in = 0; in < total; in++) { int b0 = fBuffer[in] & 0x00FF; // UTF-8: [0xxx xxxx] // Unicode: [0000 0000] [0xxx xxxx] if (b0 < 0x80) { ch[out++] = (char)b0; continue; } // UTF-8: [110y yyyy] [10xx xxxx] // Unicode: [0000 0yyy] [yyxx xxxx] if ((b0 & 0xE0) == 0xC0) { int b1 = -1; if (++in < total) { b1 = fBuffer[in] & 0x00FF; } else { b1 = fInputStream.read(); if (b1 == -1) { if (out > offset) { fBuffer[0] = (byte)b0; fOffset = 1; return out - offset; } expectedByte(2, 2); } count++; } if ((b1 & 0xC0) != 0x80) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fOffset = 2; return out - offset; } invalidByte(2, 2); } int c = ((b0 << 6) & 0x07C0) | (b1 & 0x003F); ch[out++] = (char)c; count -= 1; continue; } // UTF-8: [1110 zzzz] [10yy yyyy] [10xx xxxx] // Unicode: [zzzz yyyy] [yyxx xxxx] if ((b0 & 0xF0) == 0xE0) { int b1 = -1; if (++in < total) { b1 = fBuffer[in] & 0x00FF; } else { b1 = fInputStream.read(); if (b1 == -1) { if (out > offset) { fBuffer[0] = (byte)b0; fOffset = 1; return out - offset; } expectedByte(2, 3); } count++; } if ((b1 & 0xC0) != 0x80) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fOffset = 2; return out - offset; } invalidByte(2, 3); } int b2 = -1; if (++in < total) { b2 = fBuffer[in] & 0x00FF; } else { b2 = fInputStream.read(); if (b2 == -1) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fOffset = 2; return out - offset; } expectedByte(3, 3); } count++; } if ((b2 & 0xC0) != 0x80) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fBuffer[2] = (byte)b2; fOffset = 3; return out - offset; } invalidByte(3, 3); } int c = ((b0 << 12) & 0xF000) | ((b1 << 6) & 0x0FC0) | (b2 & 0x003F); ch[out++] = (char)c; count -= 2; continue; } // UTF-8: [1111 0uuu] [10uu zzzz] [10yy yyyy] [10xx xxxx]* // Unicode: [1101 10ww] [wwzz zzyy] (high surrogate) // [1101 11yy] [yyxx xxxx] (low surrogate) // * uuuuu = wwww + 1 if ((b0 & 0xF8) == 0xF0) { int b1 = -1; if (++in < total) { b1 = fBuffer[in] & 0x00FF; } else { b1 = fInputStream.read(); if (b1 == -1) { if (out > offset) { fBuffer[0] = (byte)b0; fOffset = 1; return out - offset; } expectedByte(2, 4); } count++; } if ((b1 & 0xC0) != 0x80) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fOffset = 2; return out - offset; } invalidByte(2, 4); } int b2 = -1; if (++in < total) { b2 = fBuffer[in] & 0x00FF; } else { b2 = fInputStream.read(); if (b2 == -1) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fOffset = 2; return out - offset; } expectedByte(3, 4); } count++; } if ((b2 & 0xC0) != 0x80) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fBuffer[2] = (byte)b2; fOffset = 3; return out - offset; } invalidByte(3, 4); } int b3 = -1; if (++in < total) { b3 = fBuffer[in] & 0x00FF; } else { b3 = fInputStream.read(); if (b3 == -1) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fBuffer[2] = (byte)b2; fOffset = 3; return out - offset; } expectedByte(4, 4); } count++; } if ((b3 & 0xC0) != 0x80) { if (out > offset) { fBuffer[0] = (byte)b0; fBuffer[1] = (byte)b1; fBuffer[2] = (byte)b2; fBuffer[3] = (byte)b3; fOffset = 4; return out - offset; } invalidByte(4, 4); } // decode bytes into surrogate characters int uuuuu = ((b0 << 2) & 0x001C) | ((b1 >> 4) & 0x0003); if (uuuuu > 0x10) { invalidSurrogate(uuuuu); } int wwww = uuuuu - 1; int zzzz = b1 & 0x000F; int yyyyyy = b2 & 0x003F; int xxxxxx = b3 & 0x003F; int hs = 0xD800 | ((wwww << 6) & 0x03C0) | (zzzz << 2) | (yyyyyy >> 4); int ls = 0xDC00 | ((yyyyyy << 6) & 0x03C0) | xxxxxx; // set characters ch[out++] = (char)hs; ch[out++] = (char)ls; count -= 2; continue; } // error if (out > offset) { fBuffer[0] = (byte)b0; fOffset = 1; return out - offset; } invalidByte(1, 1); } // return number of characters converted if (DEBUG_READ) { if (log.isDebugEnabled()) log.debug("read(char[],"+offset+','+length+"): count="+count); } return count; }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public long skip(long n) throws IOException { long remaining = n; final char[] ch = new char[fBuffer.length]; do { int length = ch.length < remaining ? ch.length : (int)remaining; int count = read(ch, 0, length); if (count > 0) { remaining -= count; } else { break; } } while (remaining > 0); long skipped = n - remaining; return skipped; }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public boolean ready() throws IOException { return false; }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public void mark(int readAheadLimit) throws IOException { throw new IOException( Localizer.getMessage("jsp.error.xml.operationNotSupported", "mark()", "UTF-8")); }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public void reset() throws IOException { fOffset = 0; fSurrogate = -1; }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
Override public void close() throws IOException { fInputStream.close(); }
// in java/org/apache/jasper/xmlparser/UCSReader.java
Override public int read() throws IOException { int b0 = fInputStream.read() & 0xff; if (b0 == 0xff) return -1; int b1 = fInputStream.read() & 0xff; if (b1 == 0xff) return -1; if(fEncoding >=4) { int b2 = fInputStream.read() & 0xff; if (b2 == 0xff) return -1; int b3 = fInputStream.read() & 0xff; if (b3 == 0xff) return -1; if (log.isDebugEnabled()) log.debug("b0 is " + (b0 & 0xff) + " b1 " + (b1 & 0xff) + " b2 " + (b2 & 0xff) + " b3 " + (b3 & 0xff)); if (fEncoding == UCS4BE) return (b0<<24)+(b1<<16)+(b2<<8)+b3; else return (b3<<24)+(b2<<16)+(b1<<8)+b0; } else { // UCS-2 if (fEncoding == UCS2BE) return (b0<<8)+b1; else return (b1<<8)+b0; } }
// in java/org/apache/jasper/xmlparser/UCSReader.java
Override public int read(char ch[], int offset, int length) throws IOException { int byteLength = length << ((fEncoding >= 4)?2:1); if (byteLength > fBuffer.length) { byteLength = fBuffer.length; } int count = fInputStream.read(fBuffer, 0, byteLength); if(count == -1) return -1; // try and make count be a multiple of the number of bytes we're looking for if(fEncoding >= 4) { // BigEndian // this looks ugly, but it avoids an if at any rate... int numToRead = (4 - (count & 3) & 3); for(int i=0; i<numToRead; i++) { int charRead = fInputStream.read(); if(charRead == -1) { // end of input; something likely went wrong!A Pad buffer with nulls. for (int j = i;j<numToRead; j++) fBuffer[count+j] = 0; break; } else { fBuffer[count+i] = (byte)charRead; } } count += numToRead; } else { int numToRead = count & 1; if(numToRead != 0) { count++; int charRead = fInputStream.read(); if(charRead == -1) { // end of input; something likely went wrong!A Pad buffer with nulls. fBuffer[count] = 0; } else { fBuffer[count] = (byte)charRead; } } } // now count is a multiple of the right number of bytes int numChars = count >> ((fEncoding >= 4)?2:1); int curPos = 0; for (int i = 0; i < numChars; i++) { int b0 = fBuffer[curPos++] & 0xff; int b1 = fBuffer[curPos++] & 0xff; if(fEncoding >=4) { int b2 = fBuffer[curPos++] & 0xff; int b3 = fBuffer[curPos++] & 0xff; if (fEncoding == UCS4BE) ch[offset+i] = (char)((b0<<24)+(b1<<16)+(b2<<8)+b3); else ch[offset+i] = (char)((b3<<24)+(b2<<16)+(b1<<8)+b0); } else { // UCS-2 if (fEncoding == UCS2BE) ch[offset+i] = (char)((b0<<8)+b1); else ch[offset+i] = (char)((b1<<8)+b0); } } return numChars; }
// in java/org/apache/jasper/xmlparser/UCSReader.java
Override public long skip(long n) throws IOException { // charWidth will represent the number of bits to move // n leftward to get num of bytes to skip, and then move the result rightward // to get num of chars effectively skipped. // The trick with &'ing, as with elsewhere in this dcode, is // intended to avoid an expensive use of / that might not be optimized // away. int charWidth = (fEncoding >=4)?2:1; long bytesSkipped = fInputStream.skip(n<<charWidth); if((bytesSkipped & (charWidth | 1)) == 0) return bytesSkipped >> charWidth; return (bytesSkipped >> charWidth) + 1; }
// in java/org/apache/jasper/xmlparser/UCSReader.java
Override public boolean ready() throws IOException { return false; }
// in java/org/apache/jasper/xmlparser/UCSReader.java
Override public void mark(int readAheadLimit) throws IOException { fInputStream.mark(readAheadLimit); }
// in java/org/apache/jasper/xmlparser/UCSReader.java
Override public void reset() throws IOException { fInputStream.reset(); }
// in java/org/apache/jasper/xmlparser/UCSReader.java
Override public void close() throws IOException { fInputStream.close(); }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public int read() throws IOException { int b0 = fInputStream.read(); if (b0 > 0x80) { throw new IOException(Localizer.getMessage("jsp.error.xml.invalidASCII", Integer.toString(b0))); } return b0; }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public int read(char ch[], int offset, int length) throws IOException { if (length > fBuffer.length) { length = fBuffer.length; } int count = fInputStream.read(fBuffer, 0, length); for (int i = 0; i < count; i++) { int b0 = (0xff & fBuffer[i]); // Convert to unsigned if (b0 > 0x80) { throw new IOException(Localizer.getMessage("jsp.error.xml.invalidASCII", Integer.toString(b0))); } ch[offset + i] = (char)b0; } return count; }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public long skip(long n) throws IOException { return fInputStream.skip(n); }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public boolean ready() throws IOException { return false; }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public void mark(int readAheadLimit) throws IOException { fInputStream.mark(readAheadLimit); }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public void reset() throws IOException { fInputStream.reset(); }
// in java/org/apache/jasper/xmlparser/ASCIIReader.java
Override public void close() throws IOException { fInputStream.close(); }
// in java/org/apache/jasper/JspC.java
public void generateWebMapping( String file, JspCompilationContext clctxt ) throws IOException { if (log.isDebugEnabled()) { log.debug("Generating web mapping for file " + file + " using compilation context " + clctxt); } String className = clctxt.getServletClassName(); String packageName = clctxt.getServletPackageName(); String thisServletName; if ("".equals(packageName)) { thisServletName = className; } else { thisServletName = packageName + '.' + className; } if (servletout != null) { servletout.write("\n <servlet>\n <servlet-name>"); servletout.write(thisServletName); servletout.write("</servlet-name>\n <servlet-class>"); servletout.write(thisServletName); servletout.write("</servlet-class>\n </servlet>\n"); } if (mappingout != null) { mappingout.write("\n <servlet-mapping>\n <servlet-name>"); mappingout.write(thisServletName); mappingout.write("</servlet-name>\n <url-pattern>"); mappingout.write(file.replace('\\', '/')); mappingout.write("</url-pattern>\n </servlet-mapping>\n"); } }
// in java/org/apache/jasper/JspC.java
protected void mergeIntoWebXml() throws IOException { File webappBase = new File(uriRoot); File webXml = new File(webappBase, "WEB-INF/web.xml"); File webXml2 = new File(webappBase, "WEB-INF/web2.xml"); String insertStartMarker = Localizer.getMessage("jspc.webinc.insertStart"); String insertEndMarker = Localizer.getMessage("jspc.webinc.insertEnd"); BufferedReader reader = new BufferedReader(openWebxmlReader(webXml)); BufferedReader fragmentReader = new BufferedReader( openWebxmlReader(new File(webxmlFile))); PrintWriter writer = new PrintWriter(openWebxmlWriter(webXml2)); // Insert the <servlet> and <servlet-mapping> declarations boolean inserted = false; int current = reader.read(); while (current > -1) { if (current == '<') { String element = getElement(reader); if (!inserted && insertBefore.contains(element)) { // Insert generated content here writer.println(insertStartMarker); while (true) { String line = fragmentReader.readLine(); if (line == null) { writer.println(); break; } writer.println(line); } writer.println(insertEndMarker); writer.println(); writer.write(element); inserted = true; } else if (element.equals(insertStartMarker)) { // Skip the previous auto-generated content while (true) { current = reader.read(); if (current < 0) { throw new EOFException(); } if (current == '<') { element = getElement(reader); if (element.equals(insertEndMarker)) { break; } } } current = reader.read(); while (current == '\n' || current == '\r') { current = reader.read(); } continue; } else { writer.write(element); } } else { writer.write(current); } current = reader.read(); } writer.close(); reader.close(); fragmentReader.close(); FileInputStream fis = new FileInputStream(webXml2); FileOutputStream fos = new FileOutputStream(webXml); byte buf[] = new byte[512]; while (true) { int n = fis.read(buf); if (n < 0) { break; } fos.write(buf, 0, n); } fis.close(); fos.close(); if(!webXml2.delete() && log.isDebugEnabled()) log.debug(Localizer.getMessage("jspc.delete.fail", webXml2.toString())); if (!(new File(webxmlFile)).delete() && log.isDebugEnabled()) log.debug(Localizer.getMessage("jspc.delete.fail", webxmlFile)); }
// in java/org/apache/jasper/JspC.java
private String getElement(Reader reader) throws IOException { StringBuilder result = new StringBuilder(); result.append('<'); boolean done = false; while (!done) { int current = reader.read(); while (current != '>') { if (current < 0) { throw new EOFException(); } result.append((char) current); current = reader.read(); } result.append((char) current); int len = result.length(); if (len > 4 && result.substring(0, 4).equals("<!--")) { // This is a comment - make sure we are at the end if (len >= 7 && result.substring(len - 3, len).equals("-->")) { done = true; } } else { done = true; } } return result.toString(); }
// in java/org/apache/jasper/JspC.java
protected void initClassLoader(JspCompilationContext clctxt) throws IOException { classPath = getClassPath(); ClassLoader jspcLoader = getClass().getClassLoader(); if (jspcLoader instanceof AntClassLoader) { classPath += File.pathSeparator + ((AntClassLoader) jspcLoader).getClasspath(); } // Turn the classPath into URLs ArrayList<URL> urls = new ArrayList<URL>(); StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { String path = tokenizer.nextToken(); try { File libFile = new File(path); urls.add(libFile.toURI().toURL()); } catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); } } File webappBase = new File(uriRoot); if (webappBase.exists()) { File classes = new File(webappBase, "/WEB-INF/classes"); try { if (classes.exists()) { classPath = classPath + File.pathSeparator + classes.getCanonicalPath(); urls.add(classes.getCanonicalFile().toURI().toURL()); } } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } File lib = new File(webappBase, "/WEB-INF/lib"); if (lib.exists() && lib.isDirectory()) { String[] libs = lib.list(); for (int i = 0; i < libs.length; i++) { if( libs[i].length() <5 ) continue; String ext=libs[i].substring( libs[i].length() - 4 ); if (! ".jar".equalsIgnoreCase(ext)) { if (".tld".equalsIgnoreCase(ext)) { log.warn("TLD files should not be placed in " + "/WEB-INF/lib"); } continue; } try { File libFile = new File(lib, libs[i]); classPath = classPath + File.pathSeparator + libFile.getAbsolutePath(); urls.add(libFile.getAbsoluteFile().toURI().toURL()); } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } } } } // What is this ?? urls.add(new File( clctxt.getRealPath("/")).getCanonicalFile().toURI().toURL()); URL urlsA[]=new URL[urls.size()]; urls.toArray(urlsA); loader = new URLClassLoader(urlsA, this.getClass().getClassLoader()); }
// in java/org/apache/jasper/JspC.java
private Reader openWebxmlReader(File file) throws IOException { FileInputStream fis = new FileInputStream(file); try { return webxmlEncoding != null ? new InputStreamReader(fis, webxmlEncoding) : new InputStreamReader(fis); } catch (IOException ex) { fis.close(); throw ex; } }
// in java/org/apache/jasper/JspC.java
private Writer openWebxmlWriter(File file) throws IOException { FileOutputStream fos = new FileOutputStream(file); try { return webxmlEncoding != null ? new OutputStreamWriter(fos, webxmlEncoding) : new OutputStreamWriter(fos); } catch (IOException ex) { fos.close(); throw ex; } }
// in java/org/apache/naming/resources/WARDirContext.java
Override public InputStream streamContent() throws IOException { try { if (binaryContent == null) { InputStream is = base.getInputStream(entry); inputStream = is; return is; } } catch (ZipException e) { throw new IOException(e.getMessage(), e); } return super.streamContent(); }
// in java/org/apache/naming/resources/DirContextURLConnection.java
Override public void connect() throws IOException { if (!connected) { try { date = System.currentTimeMillis(); String path = getURL().getFile(); if (context instanceof ProxyDirContext) { ProxyDirContext proxyDirContext = (ProxyDirContext) context; String hostName = proxyDirContext.getHostName(); String contextPath = proxyDirContext.getContextPath(); if (hostName != null) { if (!path.startsWith("/" + hostName + "/")) return; path = path.substring(hostName.length()+ 1); } if (contextPath != null) { if (!path.startsWith(contextPath + "/")) { return; } path = path.substring(contextPath.length()); } } path = URLDecoder.decode(path, "UTF-8"); object = context.lookup(path); attributes = context.getAttributes(path); if (object instanceof Resource) resource = (Resource) object; if (object instanceof DirContext) collection = (DirContext) object; } catch (NamingException e) { // Object not found } connected = true; } }
// in java/org/apache/naming/resources/DirContextURLConnection.java
Override public Object getContent() throws IOException { if (!connected) connect(); if (resource != null) return getInputStream(); if (collection != null) return collection; if (object != null) return object; throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); }
// in java/org/apache/naming/resources/DirContextURLConnection.java
Override public InputStream getInputStream() throws IOException { if (!connected) connect(); if (resource == null) { throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); } // Reopen resource try { resource = (Resource) context.lookup( URLDecoder.decode(getURL().getFile(), "UTF-8")); } catch (NamingException e) { // Ignore } return (resource.streamContent()); }
// in java/org/apache/naming/resources/DirContextURLConnection.java
public Enumeration<String> list() throws IOException { if (!connected) { connect(); } if ((resource == null) && (collection == null)) { throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); } Vector<String> result = new Vector<String>(); if (collection != null) { try { String file = getURL().getFile(); // This will be of the form /<hostname>/<contextpath>/file name // if <contextpath> is not empty otherwise this will be of the // form /<hostname>/file name // Strip off the hostname and the contextpath (note that context // path may contain '/' int start; if (context instanceof ProxyDirContext) { String cp = ((ProxyDirContext)context).getContextPath(); String h = ((ProxyDirContext)context).getHostName(); if ("".equals(cp)) { start = h.length() + 2; } else { start = h.length() + cp.length() + 2; } } else { start = file.indexOf('/', file.indexOf('/', 1) + 1); } NamingEnumeration<NameClassPair> enumeration = context.list(file.substring(start)); while (enumeration.hasMoreElements()) { NameClassPair ncp = enumeration.nextElement(); result.addElement( URLEncoder.encode(ncp.getName(), "UTF-8")); } } catch (NamingException e) { // Unexpected exception throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); } } return result.elements(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public InputStream streamContent() throws IOException { if (binaryContent == null) { FileInputStream fis = new FileInputStream(file); inputStream = fis; return fis; } return super.streamContent(); }
// in java/org/apache/naming/resources/Resource.java
public InputStream streamContent() throws IOException { if (binaryContent != null) { return new ByteArrayInputStream(binaryContent); } return inputStream; }
// in java/org/apache/naming/resources/DirContextURLStreamHandler.java
Override protected URLConnection openConnection(URL u) throws IOException { DirContext currentContext = this.context; if (currentContext == null) currentContext = get(); return new DirContextURLConnection(currentContext, u); }
// in java/org/apache/juli/ClassLoaderLogManager.java
Override public void readConfiguration() throws IOException, SecurityException { checkAccess(); readConfiguration(Thread.currentThread().getContextClassLoader()); }
// in java/org/apache/juli/ClassLoaderLogManager.java
Override public void readConfiguration(InputStream is) throws IOException, SecurityException { checkAccess(); reset(); readConfiguration(is, Thread.currentThread().getContextClassLoader()); }
// in java/org/apache/juli/ClassLoaderLogManager.java
protected void readConfiguration(ClassLoader classLoader) throws IOException { InputStream is = null; // Special case for URL classloaders which are used in containers: // only look in the local repositories to avoid redefining loggers 20 times try { if ((classLoader instanceof URLClassLoader) && (((URLClassLoader) classLoader).findResource("logging.properties") != null)) { is = classLoader.getResourceAsStream("logging.properties"); } } catch (AccessControlException ace) { // No permission to configure logging in context // Log and carry on ClassLoaderLogInfo info = classLoaderLoggers.get(ClassLoader.getSystemClassLoader()); if (info != null) { Logger log = info.loggers.get(""); if (log != null) { Permission perm = ace.getPermission(); if (perm instanceof FilePermission && perm.getActions().equals("read")) { log.warning("Reading " + perm.getName() + " is not permitted. See \"per context logging\" in the default catalina.policy file."); } else { log.warning("Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file."); log.warning("Original error was: " + ace.getMessage()); } } } } if ((is == null) && (classLoader == ClassLoader.getSystemClassLoader())) { String configFileStr = System.getProperty("java.util.logging.config.file"); if (configFileStr != null) { try { is = new FileInputStream(replace(configFileStr)); } catch (IOException e) { // Ignore } } // Try the default JVM configuration if (is == null) { File defaultFile = new File(new File(System.getProperty("java.home"), "lib"), "logging.properties"); try { is = new FileInputStream(defaultFile); } catch (IOException e) { // Critical problem, do something ... } } } Logger localRootLogger = new RootLogger(); if (is == null) { // Retrieve the root logger of the parent classloader instead ClassLoader current = classLoader.getParent(); ClassLoaderLogInfo info = null; while (current != null && info == null) { info = getClassLoaderInfo(current); current = current.getParent(); } if (info != null) { localRootLogger.setParent(info.rootNode.logger); } } ClassLoaderLogInfo info = new ClassLoaderLogInfo(new LogNode(null, localRootLogger)); classLoaderLoggers.put(classLoader, info); if (is != null) { readConfiguration(is, classLoader); } addLogger(localRootLogger); }
// in java/org/apache/juli/ClassLoaderLogManager.java
protected void readConfiguration(InputStream is, ClassLoader classLoader) throws IOException { ClassLoaderLogInfo info = classLoaderLoggers.get(classLoader); try { info.props.load(is); } catch (IOException e) { // Report error System.err.println("Configuration error"); e.printStackTrace(); } finally { try { is.close(); } catch (IOException ioe) { // Ignore } } // Create handlers for the root logger of this classloader String rootHandlers = info.props.getProperty(".handlers"); String handlers = info.props.getProperty("handlers"); Logger localRootLogger = info.rootNode.logger; if (handlers != null) { StringTokenizer tok = new StringTokenizer(handlers, ","); while (tok.hasMoreTokens()) { String handlerName = (tok.nextToken().trim()); String handlerClassName = handlerName; String prefix = ""; if (handlerClassName.length() <= 0) { continue; } // Parse and remove a prefix (prefix start with a digit, such as // "10WebappFooHanlder.") if (Character.isDigit(handlerClassName.charAt(0))) { int pos = handlerClassName.indexOf('.'); if (pos >= 0) { prefix = handlerClassName.substring(0, pos + 1); handlerClassName = handlerClassName.substring(pos + 1); } } try { this.prefix.set(prefix); Handler handler = (Handler) classLoader.loadClass(handlerClassName).newInstance(); // The specification strongly implies all configuration should be done // during the creation of the handler object. // This includes setting level, filter, formatter and encoding. this.prefix.set(null); info.handlers.put(handlerName, handler); if (rootHandlers == null) { localRootLogger.addHandler(handler); } } catch (Exception e) { // Report error System.err.println("Handler error"); e.printStackTrace(); } } } }
// in java/org/apache/coyote/Request.java
public int doRead(ByteChunk chunk) throws IOException { int n = inputBuffer.doRead(chunk, this); if (n > 0) { bytesRead+=n; } return n; }
// in java/org/apache/coyote/Response.java
public void doWrite(ByteChunk chunk/*byte buffer[], int pos, int count*/) throws IOException { outputBuffer.doWrite(chunk, this); contentWritten+=chunk.getLength(); }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
Override public SocketState process(SocketWrapper<Long> socket) throws IOException { RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); // Setting up the socket this.socket = socket; long socketRef = socket.getSocket().longValue(); Socket.setrbb(socketRef, inputBuffer); Socket.setsbb(socketRef, outputBuffer); boolean cping = false; // Error flag error = false; boolean keptAlive = false; while (!error && !endpoint.isPaused()) { // Parsing the request header try { // Get first message of the request if (!readMessage(requestHeaderMessage, true, keptAlive)) { // This means that no data is available right now // (long keepalive), so that the processor should be recycled // and the method should return true break; } // Check message type, process right away and break if // not regular request processing int type = requestHeaderMessage.getByte(); if (type == Constants.JK_AJP13_CPING_REQUEST) { if (endpoint.isPaused()) { recycle(true); break; } cping = true; if (Socket.send(socketRef, pongMessageArray, 0, pongMessageArray.length) < 0) { error = true; } continue; } else if(type != Constants.JK_AJP13_FORWARD_REQUEST) { // Unexpected packet type. Unread body packets should have // been swallowed in finish(). if (log.isDebugEnabled()) { log.debug("Unexpected message: " + type); } error = true; break; } keptAlive = true; request.setStartTime(System.currentTimeMillis()); } catch (IOException e) { error = true; break; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; } if (!error) { // Setting up filters, and parse some request headers rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); try { prepareRequest(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; } } if (!error && !cping && endpoint.isPaused()) { // 503 - Service unavailable response.setStatus(503); adapter.log(request, response, 0); error = true; } cping = false; // Process the request in the adapter if (!error) { try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); adapter.service(request, response); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; } } if (isAsync() && !error) { break; } // Finish the response if not done yet if (!finished) { try { finish(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; } } // If there was an error, make sure the request is counted as // and error, and update the statistics counter if (error) { response.setStatus(500); } request.updateCounters(); rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); recycle(false); } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (!error && !endpoint.isPaused()) { if (isAsync()) { return SocketState.LONG; } else { return SocketState.OPEN; } } else { return SocketState.CLOSED; } }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
Override protected void output(byte[] src, int offset, int length) throws IOException { outputBuffer.put(src, offset, length); long socketRef = socket.getSocket().longValue(); if (outputBuffer.position() > 0) { if ((socketRef != 0) && Socket.sendbb(socketRef, 0, outputBuffer.position()) < 0) { throw new IOException(sm.getString("ajpprocessor.failedsend")); } outputBuffer.clear(); } }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
protected boolean read(int n) throws IOException { if (inputBuffer.capacity() - inputBuffer.limit() <= n - inputBuffer.remaining()) { inputBuffer.compact(); inputBuffer.limit(inputBuffer.position()); inputBuffer.position(0); } int nRead; while (inputBuffer.remaining() < n) { nRead = Socket.recvbb (socket.getSocket().longValue(), inputBuffer.limit(), inputBuffer.capacity() - inputBuffer.limit()); if (nRead > 0) { inputBuffer.limit(inputBuffer.limit() + nRead); } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } } return true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
protected boolean readt(int n, boolean useAvailableData) throws IOException { if (useAvailableData && inputBuffer.remaining() == 0) { return false; } if (inputBuffer.capacity() - inputBuffer.limit() <= n - inputBuffer.remaining()) { inputBuffer.compact(); inputBuffer.limit(inputBuffer.position()); inputBuffer.position(0); } int nRead; while (inputBuffer.remaining() < n) { nRead = Socket.recvbb (socket.getSocket().longValue(), inputBuffer.limit(), inputBuffer.capacity() - inputBuffer.limit()); if (nRead > 0) { inputBuffer.limit(inputBuffer.limit() + nRead); } else { if ((-nRead) == Status.ETIMEDOUT || (-nRead) == Status.TIMEUP) { return false; } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } } } return true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
Override public boolean receive() throws IOException { first = false; bodyMessage.reset(); if (!readMessage(bodyMessage, false, false)) { // Invalid message return false; } // No data received. if (bodyMessage.getLen() == 0) { // just the header // Don't mark 'end of stream' for the first chunk. return false; } int blen = bodyMessage.peekInt(); if (blen == 0) { return false; } bodyMessage.getBodyBytes(bodyBytes); empty = false; return true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
protected boolean readMessage(AjpMessage message, boolean first, boolean useAvailableData) throws IOException { int headerLength = message.getHeaderLength(); if (first) { if (!readt(headerLength, useAvailableData)) { return false; } } else { read(headerLength); } inputBuffer.get(message.getBuffer(), 0, headerLength); int messageLength = message.processHeader(true); if (messageLength < 0) { // Invalid AJP header signature // TODO: Throw some exception and close the connection to frontend. return false; } else if (messageLength == 0) { // Zero length message. return true; } else { if (messageLength > message.getBuffer().length) { // Message too long for the buffer // Need to trigger a 400 response throw new IllegalArgumentException(sm.getString( "ajpprocessor.header.tooLong", Integer.valueOf(messageLength), Integer.valueOf(message.getBuffer().length))); } read(messageLength); inputBuffer.get(message.getBuffer(), headerLength, messageLength); return true; } }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
Override public SocketState process(SocketWrapper<NioChannel> socket) throws IOException { RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); // Setting up the socket this.socket = socket.getSocket(); long soTimeout = endpoint.getSoTimeout(); boolean cping = false; // Error flag error = false; while (!error && !endpoint.isPaused()) { // Parsing the request header try { // Get first message of the request int bytesRead = readMessage(requestHeaderMessage, false); if (bytesRead == 0) { break; } // Set back timeout if keep alive timeout is enabled if (keepAliveTimeout > 0) { socket.setTimeout(soTimeout); } // Check message type, process right away and break if // not regular request processing int type = requestHeaderMessage.getByte(); if (type == Constants.JK_AJP13_CPING_REQUEST) { if (endpoint.isPaused()) { recycle(true); break; } cping = true; try { output(pongMessageArray, 0, pongMessageArray.length); } catch (IOException e) { error = true; } recycle(false); continue; } else if(type != Constants.JK_AJP13_FORWARD_REQUEST) { // Unexpected packet type. Unread body packets should have // been swallowed in finish(). if (log.isDebugEnabled()) { log.debug("Unexpected message: " + type); } error = true; recycle(true); break; } request.setStartTime(System.currentTimeMillis()); } catch (IOException e) { error = true; break; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; } if (!error) { // Setting up filters, and parse some request headers rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); try { prepareRequest(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; } } if (!error && !cping && endpoint.isPaused()) { // 503 - Service unavailable response.setStatus(503); adapter.log(request, response, 0); error = true; } cping = false; // Process the request in the adapter if (!error) { try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); adapter.service(request, response); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; } } if (isAsync() && !error) { break; } // Finish the response if not done yet if (!finished) { try { finish(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; } } // If there was an error, make sure the request is counted as // and error, and update the statistics counter if (error) { response.setStatus(500); } request.updateCounters(); rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); // Set keep alive timeout if enabled if (keepAliveTimeout > 0) { socket.setTimeout(keepAliveTimeout); } recycle(false); } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (!error && !endpoint.isPaused()) { if (isAsync()) { return SocketState.LONG; } else { return SocketState.OPEN; } } else { return SocketState.CLOSED; } }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
Override protected void output(byte[] src, int offset, int length) throws IOException { ByteBuffer writeBuffer = socket.getBufHandler() .getWriteBuffer(); writeBuffer.put(src, offset, length); writeBuffer.flip(); NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled"); long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { pool.write(writeBuffer, socket, selector, writeTimeout, true); }finally { if ( selector != null ) pool.put(selector); } writeBuffer.clear(); }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
protected int read(byte[] buf, int pos, int n, boolean blockFirstRead) throws IOException { int read = 0; int res = 0; boolean block = blockFirstRead; while (read < n) { res = readSocket(buf, read + pos, n, block); if (res > 0) { read += res; } else if (res == 0 && !block) { break; } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } block = true; } return read; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
private int readSocket(byte[] buf, int pos, int n, boolean block) throws IOException { int nRead = 0; socket.getBufHandler().getReadBuffer().clear(); socket.getBufHandler().getReadBuffer().limit(n); if ( block ) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled."); nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout()); } catch ( EOFException eof ) { nRead = -1; } finally { if ( selector != null ) pool.put(selector); } } else { nRead = socket.read(socket.getBufHandler().getReadBuffer()); } if (nRead > 0) { socket.getBufHandler().getReadBuffer().flip(); socket.getBufHandler().getReadBuffer().limit(nRead); socket.getBufHandler().getReadBuffer().get(buf, pos, nRead); return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("iib.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
Override public boolean receive() throws IOException { first = false; bodyMessage.reset(); readMessage(bodyMessage, true); // No data received. if (bodyMessage.getLen() == 0) { // just the header // Don't mark 'end of stream' for the first chunk. return false; } int blen = bodyMessage.peekInt(); if (blen == 0) { return false; } bodyMessage.getBodyBytes(bodyBytes); empty = false; return true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
protected int readMessage(AjpMessage message, boolean blockFirstRead) throws IOException { byte[] buf = message.getBuffer(); int headerLength = message.getHeaderLength(); int bytesRead = read(buf, 0, headerLength, blockFirstRead); if (bytesRead == 0) { return 0; } int messageLength = message.processHeader(true); if (messageLength < 0) { // Invalid AJP header signature throw new IOException(sm.getString("ajpmessage.invalidLength", Integer.valueOf(messageLength))); } else if (messageLength == 0) { // Zero length message. return bytesRead; } else { if (messageLength > buf.length) { // Message too long for the buffer // Need to trigger a 400 response throw new IllegalArgumentException(sm.getString( "ajpprocessor.header.tooLong", Integer.valueOf(messageLength), Integer.valueOf(buf.length))); } bytesRead += read(buf, headerLength, messageLength, true); return bytesRead; } }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public SocketState event(SocketStatus status) throws IOException { // Should never reach this code but in case we do... throw new IOException( sm.getString("ajpprocessor.comet.notsupported")); }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public SocketState upgradeDispatch() throws IOException { // Should never reach this code but in case we do... throw new IOException( sm.getString("ajpprocessor.httpupgrade.notsupported")); }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
protected boolean refillReadBuffer() throws IOException { // If the server returns an empty packet, assume that that end of // the stream has been reached (yuck -- fix protocol??). // FORM support if (replay) { endOfStream = true; // we've read everything there is } if (endOfStream) { return false; } // Request more data immediately output(getBodyMessageArray, 0, getBodyMessageArray.length); boolean moreData = receive(); if( !moreData ) { endOfStream = true; } return moreData; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
protected void prepareResponse() throws IOException { response.setCommitted(true); responseMessage.reset(); responseMessage.appendByte(Constants.JK_AJP13_SEND_HEADERS); // HTTP header contents responseMessage.appendInt(response.getStatus()); String message = null; if (org.apache.coyote.Constants.USE_CUSTOM_STATUS_MSG_IN_HEADER && HttpMessages.isSafeInHttpHeader(response.getMessage())) { message = response.getMessage(); } if (message == null){ message = HttpMessages.getMessage(response.getStatus()); } if (message == null) { // mod_jk + httpd 2.x fails with a null status message - bug 45026 message = Integer.toString(response.getStatus()); } tmpMB.setString(message); responseMessage.appendBytes(tmpMB); // Special headers MimeHeaders headers = response.getMimeHeaders(); String contentType = response.getContentType(); if (contentType != null) { headers.setValue("Content-Type").setString(contentType); } String contentLanguage = response.getContentLanguage(); if (contentLanguage != null) { headers.setValue("Content-Language").setString(contentLanguage); } long contentLength = response.getContentLengthLong(); if (contentLength >= 0) { headers.setValue("Content-Length").setLong(contentLength); } // Other headers int numHeaders = headers.size(); responseMessage.appendInt(numHeaders); for (int i = 0; i < numHeaders; i++) { MessageBytes hN = headers.getName(i); int hC = Constants.getResponseAjpIndex(hN.toString()); if (hC > 0) { responseMessage.appendInt(hC); } else { responseMessage.appendBytes(hN); } MessageBytes hV=headers.getValue(i); responseMessage.appendBytes(hV); } // Write to buffer responseMessage.end(); output(responseMessage.getBuffer(), 0, responseMessage.getLen()); }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
protected void flush(boolean explicit) throws IOException { if (explicit && !finished) { // Send the flush message output(flushMessageArray, 0, flushMessageArray.length); } }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
protected void finish() throws IOException { if (!response.isCommitted()) { // Validate and write response headers try { prepareResponse(); } catch (IOException e) { // Set error flag error = true; } } if (finished) return; finished = true; // Swallow the unread body packet if present if (first && request.getContentLengthLong() > 0) { receive(); } // Add the end message if (error) { output(endAndCloseMessageArray, 0, endAndCloseMessageArray.length); } else { output(endMessageArray, 0, endMessageArray.length); } }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public int doRead(ByteChunk chunk, Request req) throws IOException { if (endOfStream) { return -1; } if (first && req.getContentLengthLong() > 0) { // Handle special first-body-chunk if (!receive()) { return 0; } } else if (empty) { if (!refillReadBuffer()) { return -1; } } ByteChunk bc = bodyBytes.getByteChunk(); chunk.setBytes(bc.getBuffer(), bc.getStart(), bc.getLength()); empty = true; return chunk.getLength(); }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { if (!response.isCommitted()) { // Validate and write response headers try { prepareResponse(); } catch (IOException e) { // Set error flag error = true; } } int len = chunk.getLength(); // 4 - hardcoded, byte[] marshaling overhead // Adjust allowed size if packetSize != default (Constants.MAX_PACKET_SIZE) int chunkSize = Constants.MAX_SEND_SIZE + packetSize - Constants.MAX_PACKET_SIZE; int off = 0; while (len > 0) { int thisTime = len; if (thisTime > chunkSize) { thisTime = chunkSize; } len -= thisTime; responseMessage.reset(); responseMessage.appendByte(Constants.JK_AJP13_SEND_BODY_CHUNK); responseMessage.appendBytes(chunk.getBytes(), chunk.getOffset() + off, thisTime); responseMessage.end(); output(responseMessage.getBuffer(), 0, responseMessage.getLen()); off += thisTime; } bytesWritten += chunk.getLength(); return chunk.getLength(); }
// in java/org/apache/coyote/ajp/AjpProcessor.java
Override public SocketState process(SocketWrapper<Socket> socket) throws IOException { RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); // Setting up the socket this.socket = socket; input = socket.getSocket().getInputStream(); output = socket.getSocket().getOutputStream(); int soTimeout = -1; if (keepAliveTimeout > 0) { soTimeout = socket.getSocket().getSoTimeout(); } boolean cping = false; // Error flag error = false; while (!error && !endpoint.isPaused()) { // Parsing the request header try { // Set keep alive timeout if enabled if (keepAliveTimeout > 0) { socket.getSocket().setSoTimeout(keepAliveTimeout); } // Get first message of the request if (!readMessage(requestHeaderMessage)) { // This means a connection timeout break; } // Set back timeout if keep alive timeout is enabled if (keepAliveTimeout > 0) { socket.getSocket().setSoTimeout(soTimeout); } // Check message type, process right away and break if // not regular request processing int type = requestHeaderMessage.getByte(); if (type == Constants.JK_AJP13_CPING_REQUEST) { if (endpoint.isPaused()) { recycle(true); break; } cping = true; try { output.write(pongMessageArray); } catch (IOException e) { error = true; } continue; } else if(type != Constants.JK_AJP13_FORWARD_REQUEST) { // Unexpected packet type. Unread body packets should have // been swallowed in finish(). if (log.isDebugEnabled()) { log.debug("Unexpected message: " + type); } error = true; break; } request.setStartTime(System.currentTimeMillis()); } catch (IOException e) { error = true; break; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; } if (!error) { // Setting up filters, and parse some request headers rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); try { prepareRequest(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; } } if (!error && !cping && endpoint.isPaused()) { // 503 - Service unavailable response.setStatus(503); adapter.log(request, response, 0); error = true; } cping = false; // Process the request in the adapter if (!error) { try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); adapter.service(request, response); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; } } if (isAsync() && !error) { break; } // Finish the response if not done yet if (!finished) { try { finish(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; } } // If there was an error, make sure the request is counted as // and error, and update the statistics counter if (error) { response.setStatus(500); } request.updateCounters(); rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); recycle(false); } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (isAsync() && !error && !endpoint.isPaused()) { return SocketState.LONG; } else { input = null; output = null; return SocketState.CLOSED; } }
// in java/org/apache/coyote/ajp/AjpProcessor.java
Override protected void output(byte[] src, int offset, int length) throws IOException { output.write(src, offset, length); }
// in java/org/apache/coyote/ajp/AjpProcessor.java
protected boolean read(byte[] buf, int pos, int n) throws IOException { int read = 0; int res = 0; while (read < n) { res = input.read(buf, read + pos, n - read); if (res > 0) { read += res; } else { throw new IOException(sm.getString("ajpprotocol.failedread")); } } return true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
Override public boolean receive() throws IOException { first = false; bodyMessage.reset(); if (!readMessage(bodyMessage)) { // Invalid message return false; } // No data received. if (bodyMessage.getLen() == 0) { // just the header // Don't mark 'end of stream' for the first chunk. return false; } int blen = bodyMessage.peekInt(); if (blen == 0) { return false; } bodyMessage.getBodyBytes(bodyBytes); empty = false; return true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
protected boolean readMessage(AjpMessage message) throws IOException { byte[] buf = message.getBuffer(); int headerLength = message.getHeaderLength(); read(buf, 0, headerLength); int messageLength = message.processHeader(true); if (messageLength < 0) { // Invalid AJP header signature // TODO: Throw some exception and close the connection to frontend. return false; } else if (messageLength == 0) { // Zero length message. return true; } else { if (messageLength > buf.length) { // Message too long for the buffer // Need to trigger a 400 response throw new IllegalArgumentException(sm.getString( "ajpprocessor.header.tooLong", Integer.valueOf(messageLength), Integer.valueOf(buf.length))); } read(buf, headerLength, messageLength); return true; } }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
Override public SocketState event(SocketStatus status) throws IOException { RequestInfo rp = request.getRequestProcessor(); try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); error = !adapter.event(request, response, status); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (error) { return SocketState.CLOSED; } else if (!comet) { inputBuffer.nextRequest(); outputBuffer.nextRequest(); return SocketState.OPEN; } else { return SocketState.LONG; } }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
Override protected void setRequestLineReadTimeout() throws IOException { // Timeouts while in the poller are handled entirely by the poller // Only need to be concerned with socket timeouts // APR uses simulated blocking so if some request line data is present // then it must all be presented (with the normal socket timeout). // When entering the processing loop for the first time there will // always be some data to read so the keep-alive timeout is not required // For the second and subsequent executions of the processing loop, if // there is no request line data present then no further data will be // read from the socket. If there is request line data present then it // must all be presented (with the normal socket timeout) // When the socket is created it is given the correct timeout. // sendfile may change the timeout but will restore it // This processor may change the timeout for uploads but will restore it // NO-OP }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
Override public SocketState event(SocketStatus status) throws IOException { long soTimeout = endpoint.getSoTimeout(); RequestInfo rp = request.getRequestProcessor(); final NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment)socket.getSocket().getAttachment(false); try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); error = !adapter.event(request, response, status); if ( !error ) { if (attach != null) { attach.setComet(comet); if (comet) { Integer comettimeout = (Integer) request.getAttribute( org.apache.coyote.Constants.COMET_TIMEOUT_ATTR); if (comettimeout != null) { attach.setTimeout(comettimeout.longValue()); } } else { //reset the timeout if (keepAlive) { attach.setTimeout(keepAliveTimeout); } else { attach.setTimeout(soTimeout); } } } } } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (error) { return SocketState.CLOSED; } else if (!comet) { if (keepAlive) { inputBuffer.nextRequest(); outputBuffer.nextRequest(); return SocketState.OPEN; } else { return SocketState.CLOSED; } } else { return SocketState.LONG; } }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
Override protected void setRequestLineReadTimeout() throws IOException { // socket.setTimeout() // - timeout used by poller // socket.getSocket().getIOChannel().socket().setSoTimeout() // - timeout used for blocking reads // When entering the processing loop there will always be data to read // so no point changing timeouts at this point // For the second and subsequent executions of the processing loop, a // non-blocking read is used so again no need to set the timeouts // Because NIO supports non-blocking reading of the request line and // headers the timeouts need to be set when returning the socket to // the poller rather than here. // NO-OP }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
Override protected void setSocketTimeout(int timeout) throws IOException { socket.getSocket().getIOChannel().socket().setSoTimeout(timeout); }
// in java/org/apache/coyote/http11/InternalOutputBuffer.java
Override public void init(SocketWrapper<Socket> socketWrapper, AbstractEndpoint endpoint) throws IOException { outputStream = socketWrapper.getSocket().getOutputStream(); }
// in java/org/apache/coyote/http11/InternalOutputBuffer.java
Override public void flush() throws IOException { super.flush(); // Flush the current buffer if (useSocketBuffer) { socketBuffer.flushBuffer(); } }
// in java/org/apache/coyote/http11/InternalOutputBuffer.java
Override public void endRequest() throws IOException { super.endRequest(); if (useSocketBuffer) { socketBuffer.flushBuffer(); } }
// in java/org/apache/coyote/http11/InternalOutputBuffer.java
Override public void sendAck() throws IOException { if (!committed) outputStream.write(Constants.ACK_BYTES); }
// in java/org/apache/coyote/http11/InternalOutputBuffer.java
Override protected void commit() throws IOException { // The response is now committed committed = true; response.setCommitted(true); if (pos > 0) { // Sending the response header buffer if (useSocketBuffer) { socketBuffer.append(buf, 0, pos); } else { outputStream.write(buf, 0, pos); } } }
// in java/org/apache/coyote/http11/InternalOutputBuffer.java
Override public void realWriteBytes(byte cbuf[], int off, int len) throws IOException { if (len > 0) { outputStream.write(cbuf, off, len); } }
// in java/org/apache/coyote/http11/InternalOutputBuffer.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { int length = chunk.getLength(); if (useSocketBuffer) { socketBuffer.append(chunk.getBuffer(), chunk.getStart(), length); } else { outputStream.write(chunk.getBuffer(), chunk.getStart(), length); } byteCount += chunk.getLength(); return chunk.getLength(); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableDataOnly) throws IOException { //check state if ( !parsingRequestLine ) return true; // // Skipping blank lines // if ( parsingRequestLinePhase == 0 ) { byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (useAvailableDataOnly) { return false; } // Ignore bytes that were read pos = lastValid = 0; // Do a simple read with a short timeout if ( readSocket(true, false)==0 ) return false; } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; if (pos >= skipBlankLinesSize) { // Move data, to have enough space for further reading // of headers and body System.arraycopy(buf, pos, buf, 0, lastValid - pos); lastValid -= pos; pos = 0; } skipBlankLinesBytes = pos; parsingRequestLineStart = pos; parsingRequestLinePhase = 2; if (log.isDebugEnabled()) { log.debug("Received [" + new String(buf, pos, lastValid - pos, DEFAULT_CHARSET) + "]"); } } if ( parsingRequestLinePhase == 2 ) { // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, parsingRequestLineStart, pos - parsingRequestLineStart); } pos++; } parsingRequestLinePhase = 3; } if ( parsingRequestLinePhase == 3 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 4; } if (parsingRequestLinePhase == 4) { // Mark the current buffer position int end = 0; // // Reading the URI // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request parsingRequestLineEol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (parsingRequestLineQPos == -1)) { parsingRequestLineQPos = pos; } pos++; } request.unparsedURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); if (parsingRequestLineQPos >= 0) { request.queryString().setBytes(buf, parsingRequestLineQPos + 1, end - parsingRequestLineQPos - 1); request.requestURI().setBytes(buf, parsingRequestLineStart, parsingRequestLineQPos - parsingRequestLineStart); } else { request.requestURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } parsingRequestLinePhase = 5; } if ( parsingRequestLinePhase == 5 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 6; } if (parsingRequestLinePhase == 6) { // Mark the current buffer position end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!parsingRequestLineEol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; parsingRequestLineEol = true; } pos++; } if ( (end - parsingRequestLineStart) > 0) { request.protocol().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } else { request.protocol().setString(""); } parsingRequestLine = false; parsingRequestLinePhase = 0; parsingRequestLineEol = false; parsingRequestLineStart = 0; return true; } throw new IllegalStateException("Invalid request line parse phase:"+parsingRequestLinePhase); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
private int readSocket(boolean timeout, boolean block) throws IOException { int nRead = 0; socket.getBufHandler().getReadBuffer().clear(); if ( block ) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled."); nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout()); } catch ( EOFException eof ) { nRead = -1; } finally { if ( selector != null ) pool.put(selector); } } else { nRead = socket.read(socket.getBufHandler().getReadBuffer()); } if (nRead > 0) { socket.getBufHandler().getReadBuffer().flip(); socket.getBufHandler().getReadBuffer().limit(nRead); expand(nRead + pos); socket.getBufHandler().getReadBuffer().get(buf, pos, nRead); lastValid = pos + nRead; return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("iib.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } HeaderParseStatus status = HeaderParseStatus.HAVE_MORE_HEADERS; do { status = parseHeader(); } while ( status == HeaderParseStatus.HAVE_MORE_HEADERS ); if (status == HeaderParseStatus.DONE) { parsingHeader = false; end = pos; // Checking that // (1) Headers plus request line size does not exceed its limit // (2) There are enough bytes to avoid expanding the buffer when // reading body // Technically, (2) is technical limitation, (1) is logical // limitation to enforce the meaning of headerBufferSize // From the way how buf is allocated and how blank lines are being // read, it should be enough to check (1) only. if (end - skipBlankLinesBytes > headerBufferSize || buf.length - end < socketReadBufferSize) { throw new IllegalArgumentException( sm.getString("iib.requestheadertoolarge.error")); } return true; } else { return false; } }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
private HeaderParseStatus parseHeader() throws IOException { // // Check for blank line // byte chr = 0; while (headerParsePos == HeaderParsePosition.HEADER_START) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header headerParsePos = HeaderParsePosition.HEADER_START; return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.CR) { // Skip } else if (chr == Constants.LF) { pos++; return HeaderParseStatus.DONE; } else { break; } pos++; } if ( headerParsePos == HeaderParsePosition.HEADER_START ) { // Mark the current buffer position headerData.start = pos; headerParsePos = HeaderParsePosition.HEADER_NAME; } // // Reading the header name // Header name is always US-ASCII // while (headerParsePos == HeaderParsePosition.HEADER_NAME) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) { //parse header return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.COLON) { headerParsePos = HeaderParsePosition.HEADER_VALUE_START; headerData.headerValue = headers.addValue(buf, headerData.start, pos - headerData.start); pos++; // Mark the current buffer position headerData.start = pos; headerData.realPos = pos; headerData.lastSignificantChar = pos; break; } else if (!HTTP_TOKEN_CHAR[chr]) { // If a non-token header is detected, skip the line and // ignore the header headerData.lastSignificantChar = pos; return skipLine(); } // chr is next byte of header name. Convert to lowercase. if ((chr >= Constants.A) && (chr <= Constants.Z)) { buf[pos] = (byte) (chr - Constants.LC_OFFSET); } pos++; } // Skip the line and ignore the header if (headerParsePos == HeaderParsePosition.HEADER_SKIPLINE) { return skipLine(); } // // Reading the header value (which can be spanned over multiple lines) // while (headerParsePos == HeaderParsePosition.HEADER_VALUE_START || headerParsePos == HeaderParsePosition.HEADER_VALUE || headerParsePos == HeaderParsePosition.HEADER_MULTI_LINE) { if ( headerParsePos == HeaderParsePosition.HEADER_VALUE_START ) { // Skipping spaces while (true) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header //HEADER_VALUE_START return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.SP || chr == Constants.HT) { pos++; } else { headerParsePos = HeaderParsePosition.HEADER_VALUE; break; } } } if ( headerParsePos == HeaderParsePosition.HEADER_VALUE ) { // Reading bytes until the end of the line boolean eol = false; while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header //HEADER_VALUE return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.CR) { // Skip } else if (chr == Constants.LF) { eol = true; } else if (chr == Constants.SP || chr == Constants.HT) { buf[headerData.realPos] = chr; headerData.realPos++; } else { buf[headerData.realPos] = chr; headerData.realPos++; headerData.lastSignificantChar = headerData.realPos; } pos++; } // Ignore whitespaces at the end of the line headerData.realPos = headerData.lastSignificantChar; // Checking the first character of the new line. If the character // is a LWS, then it's a multiline header headerParsePos = HeaderParsePosition.HEADER_MULTI_LINE; } // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header //HEADER_MULTI_LINE return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if ( headerParsePos == HeaderParsePosition.HEADER_MULTI_LINE ) { if ( (chr != Constants.SP) && (chr != Constants.HT)) { headerParsePos = HeaderParsePosition.HEADER_START; break; } else { // Copying one extra space in the buffer (since there must // be at least one space inserted between the lines) buf[headerData.realPos] = chr; headerData.realPos++; headerParsePos = HeaderParsePosition.HEADER_VALUE_START; } } } // Set the header value headerData.headerValue.setBytes(buf, headerData.start, headerData.lastSignificantChar - headerData.start); headerData.recycle(); return HeaderParseStatus.HAVE_MORE_HEADERS; }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
private HeaderParseStatus skipLine() throws IOException { headerParsePos = HeaderParsePosition.HEADER_SKIPLINE; boolean eol = false; // Reading bytes until the end of the line while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) { return HeaderParseStatus.NEED_MORE_DATA; } } if (buf[pos] == Constants.CR) { // Skip } else if (buf[pos] == Constants.LF) { eol = true; } else { headerData.lastSignificantChar = pos; } pos++; } if (log.isDebugEnabled()) { log.debug(sm.getString("iib.invalidheader", new String(buf, headerData.start, headerData.lastSignificantChar - headerData.start + 1, DEFAULT_CHARSET))); } headerParsePos = HeaderParsePosition.HEADER_START; return HeaderParseStatus.HAVE_MORE_HEADERS; }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override protected void init(SocketWrapper<NioChannel> socketWrapper, AbstractEndpoint endpoint) throws IOException { socket = socketWrapper.getSocket(); socketReadBufferSize = socket.getBufHandler().getReadBuffer().capacity(); int bufLength = skipBlankLinesSize + headerBufferSize + socketReadBufferSize; if (buf == null || buf.length < bufLength) { buf = new byte[bufLength]; } pool = ((NioEndpoint)endpoint).getSelectorPool(); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override protected boolean fill(boolean block) throws IOException, EOFException { return fill(true,block); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
protected boolean fill(boolean timeout, boolean block) throws IOException, EOFException { boolean read = false; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } // Do a simple read with a short timeout read = readSocket(timeout,block)>0; } else { lastValid = pos = end; // Do a simple read with a short timeout read = readSocket(timeout, block)>0; } return read; }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override public int doRead(ByteChunk chunk, Request req ) throws IOException { if (pos >= lastValid) { if (!fill(true,true)) //read body, must be blocking, as the thread is inside the app return -1; } int length = lastValid - pos; chunk.setBytes(buf, pos, length); pos = lastValid; return (length); }
// in java/org/apache/coyote/http11/upgrade/UpgradeProcessor.java
Override public final SocketState upgradeDispatch() throws IOException { return upgradeInbound.onData(); }
// in java/org/apache/coyote/http11/upgrade/UpgradeProcessor.java
Override public final SocketState process(SocketWrapper<S> socketWrapper) throws IOException { return null; }
// in java/org/apache/coyote/http11/upgrade/UpgradeProcessor.java
Override public final SocketState event(SocketStatus status) throws IOException { return null; }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
Override public void flush() throws IOException { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) nioChannel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled"); } long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { do { if (nioChannel.flush(true, selector, writeTimeout)) { break; } } while (true); } finally { if (selector != null) { pool.put(selector); } } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
Override public void write(int b) throws IOException { writeToSocket(new byte[] {(byte) b}, 0, 1); }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
Override public void write(byte[]b, int off, int len) throws IOException { int written = 0; while (len - written > maxWrite) { written += writeToSocket(b, off + written, maxWrite); } writeToSocket(b, off + written, len - written); }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
Override public int read() throws IOException { byte[] bytes = new byte[1]; int result = readSocket(true, bytes, 0, 1); if (result == -1) { return -1; } else { return bytes[0] & 0xFF; } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
Override public int read(boolean block, byte[] bytes, int off, int len) throws IOException { if (len > maxRead) { return readSocket(block, bytes, off, maxRead); } else { return readSocket(block, bytes, off, len); } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
private int readSocket(boolean block, byte[] bytes, int offset, int len) throws IOException { int nRead = 0; nioChannel.getBufHandler().getReadBuffer().clear(); nioChannel.getBufHandler().getReadBuffer().limit(len); if (block) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) nioChannel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled."); } nRead = pool.read(nioChannel.getBufHandler().getReadBuffer(), nioChannel, selector, att.getTimeout()); } catch (EOFException eof) { nRead = -1; } finally { if (selector != null) { pool.put(selector); } } } else { nRead = nioChannel.read(nioChannel.getBufHandler().getReadBuffer()); } if (nRead > 0) { nioChannel.getBufHandler().getReadBuffer().flip(); nioChannel.getBufHandler().getReadBuffer().limit(nRead); nioChannel.getBufHandler().getReadBuffer().get(bytes, offset, nRead); return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("nio.eof.error")); } else { return 0; } }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
private synchronized int writeToSocket(byte[] bytes, int off, int len) throws IOException { nioChannel.getBufHandler().getWriteBuffer().clear(); nioChannel.getBufHandler().getWriteBuffer().put(bytes, off, len); nioChannel.getBufHandler().getWriteBuffer().flip(); int written = 0; NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) nioChannel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled"); } long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { written = pool.write(nioChannel.getBufHandler().getWriteBuffer(), nioChannel, selector, writeTimeout, true); } finally { if (selector != null) { pool.put(selector); } } return written; }
// in java/org/apache/coyote/http11/upgrade/UpgradeBioProcessor.java
Override public void flush() throws IOException { outputStream.flush(); }
// in java/org/apache/coyote/http11/upgrade/UpgradeBioProcessor.java
Override public void write(int b) throws IOException { outputStream.write(b); }
// in java/org/apache/coyote/http11/upgrade/UpgradeBioProcessor.java
Override public void write(byte[]b, int off, int len) throws IOException { outputStream.write(b, off, len); }
// in java/org/apache/coyote/http11/upgrade/UpgradeBioProcessor.java
Override public int read() throws IOException { return inputStream.read(); }
// in java/org/apache/coyote/http11/upgrade/UpgradeBioProcessor.java
Override public int read(boolean block, byte[] bytes, int off, int len) throws IOException { // The BIO endpoint always uses blocking IO so the block parameter is // ignored and a blocking read is performed. return inputStream.read(bytes, off, len); }
// in java/org/apache/coyote/http11/upgrade/UpgradeAprProcessor.java
Override public void flush() throws IOException { // NOOP }
// in java/org/apache/coyote/http11/upgrade/UpgradeAprProcessor.java
Override public void write(int b) throws IOException { Socket.send(socket, new byte[] {(byte) b}, 0, 1); }
// in java/org/apache/coyote/http11/upgrade/UpgradeAprProcessor.java
Override public void write(byte[]b, int off, int len) throws IOException { Socket.send(socket, b, off, len); }
// in java/org/apache/coyote/http11/upgrade/UpgradeAprProcessor.java
Override public int read() throws IOException { byte[] bytes = new byte[1]; int result = Socket.recv(socket, bytes, 0, 1); if (result == -1) { return -1; } else { return bytes[0] & 0xFF; } }
// in java/org/apache/coyote/http11/upgrade/UpgradeAprProcessor.java
Override public int read(boolean block, byte[] bytes, int off, int len) throws IOException { if (!block) { Socket.optSet(socket, Socket.APR_SO_NONBLOCK, -1); } try { int result = Socket.recv(socket, bytes, off, len); if (result > 0) { return result; } else if (-result == Status.EAGAIN) { return 0; } else { throw new IOException(sm.getString("apr.error", Integer.valueOf(-result))); } } finally { if (!block) { Socket.optSet(socket, Socket.APR_SO_NONBLOCK, 0); } } }
// in java/org/apache/coyote/http11/upgrade/UpgradeOutbound.java
Override public void flush() throws IOException { processor.flush(); }
// in java/org/apache/coyote/http11/upgrade/UpgradeOutbound.java
Override public void write(int b) throws IOException { processor.write(b); }
// in java/org/apache/coyote/http11/upgrade/UpgradeOutbound.java
Override public void write(byte[] b, int off, int len) throws IOException { processor.write(b, off, len); }
// in java/org/apache/coyote/http11/Http11NioProtocol.java
Override protected Processor<NioChannel> createUpgradeProcessor( SocketWrapper<NioChannel> socket, UpgradeInbound inbound) throws IOException { return new UpgradeNioProcessor(socket, inbound, ((Http11NioProtocol) getProtocol()).getEndpoint().getSelectorPool()); }
// in java/org/apache/coyote/http11/filters/SavedRequestInputFilter.java
Override public int doRead(ByteChunk chunk, org.apache.coyote.Request request) throws IOException { int writeLength = 0; if (chunk.getLimit() > 0 && chunk.getLimit() < input.getLength()) { writeLength = chunk.getLimit(); } else { writeLength = input.getLength(); } if(input.getOffset()>= input.getEnd()) return -1; input.substract(chunk.getBuffer(), 0, writeLength); chunk.setOffset(0); chunk.setEnd(writeLength); return writeLength; }
// in java/org/apache/coyote/http11/filters/SavedRequestInputFilter.java
Override public long end() throws IOException { return 0; }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
Override public int doRead(ByteChunk chunk, Request req) throws IOException { if (endChunk) return -1; if(needCRLFParse) { needCRLFParse = false; parseCRLF(); } if (remaining <= 0) { if (!parseChunkHeader()) { throw new IOException("Invalid chunk header"); } if (endChunk) { parseEndChunk(); return -1; } } int result = 0; if (pos >= lastValid) { readBytes(); } if (remaining > (lastValid - pos)) { result = lastValid - pos; remaining = remaining - result; chunk.setBytes(buf, pos, result); pos = lastValid; } else { result = remaining; chunk.setBytes(buf, pos, remaining); pos = pos + remaining; remaining = 0; //we need a CRLF if ((pos+1) >= lastValid) { //if we call parseCRLF we overrun the buffer here //so we defer it to the next call BZ 11117 needCRLFParse = true; } else { parseCRLF(); //parse the CRLF immediately } } return result; }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
Override public long end() throws IOException { // Consume extra bytes : parse the stream until the end chunk is found while (doRead(readChunk, null) >= 0) { // NOOP: Just consume the input } // Return the number of extra bytes which were consumed return (lastValid - pos); }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
protected int readBytes() throws IOException { int nRead = buffer.doRead(readChunk, null); pos = readChunk.getStart(); lastValid = pos + nRead; buf = readChunk.getBytes(); return nRead; }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
protected boolean parseChunkHeader() throws IOException { int result = 0; boolean eol = false; boolean readDigit = false; boolean trailer = false; while (!eol) { if (pos >= lastValid) { if (readBytes() <= 0) return false; } if (buf[pos] == Constants.CR) { // FIXME: Improve parsing to check for CRLF } else if (buf[pos] == Constants.LF) { eol = true; } else if (buf[pos] == Constants.SEMI_COLON) { trailer = true; } else if (!trailer) { //don't read data after the trailer if (HexUtils.getDec(buf[pos]) != -1) { readDigit = true; result *= 16; result += HexUtils.getDec(buf[pos]); } else { //we shouldn't allow invalid, non hex characters //in the chunked header return false; } } pos++; } if (!readDigit) return false; if (result == 0) endChunk = true; remaining = result; if (remaining < 0) return false; return true; }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
protected boolean parseCRLF() throws IOException { boolean eol = false; boolean crfound = false; while (!eol) { if (pos >= lastValid) { if (readBytes() <= 0) throw new IOException("Invalid CRLF"); } if (buf[pos] == Constants.CR) { if (crfound) throw new IOException("Invalid CRLF, two CR characters encountered."); crfound = true; } else if (buf[pos] == Constants.LF) { if (!crfound) throw new IOException("Invalid CRLF, no CR character encountered."); eol = true; } else { throw new IOException("Invalid CRLF"); } pos++; } return true; }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
protected void parseEndChunk() throws IOException { // Handle option trailer headers while (parseHeader()) { // Loop until we run out of headers } }
// in java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
private boolean parseHeader() throws IOException { MimeHeaders headers = request.getMimeHeaders(); byte chr = 0; while (true) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr == Constants.CR) || (chr == Constants.LF)) { if (chr == Constants.LF) { pos++; return false; } } else { break; } pos++; } // Mark the current buffer position int start = trailingHeaders.getEnd(); // // Reading the header name // Header name is always US-ASCII // boolean colon = false; while (!colon) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr >= Constants.A) && (chr <= Constants.Z)) { chr = (byte) (chr - Constants.LC_OFFSET); } if (chr == Constants.COLON) { colon = true; } else { trailingHeaders.append(chr); } pos++; } MessageBytes headerValue = headers.addValue(trailingHeaders.getBytes(), start, trailingHeaders.getEnd() - start); // Mark the current buffer position start = trailingHeaders.getEnd(); // // Reading the header value (which can be spanned over multiple lines) // boolean eol = false; boolean validLine = true; int lastSignificantChar = 0; while (validLine) { boolean space = true; // Skipping spaces while (space) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr == Constants.SP) || (chr == Constants.HT)) { pos++; } else { space = false; } } // Reading bytes until the end of the line while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if (chr == Constants.CR) { // Skip } else if (chr == Constants.LF) { eol = true; } else if (chr == Constants.SP) { trailingHeaders.append(chr); } else { trailingHeaders.append(chr); lastSignificantChar = trailingHeaders.getEnd(); } pos++; } // Checking the first character of the new line. If the character // is a LWS, then it's a multiline header // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr != Constants.SP) && (chr != Constants.HT)) { validLine = false; } else { eol = false; // Copying one extra space in the buffer (since there must // be at least one space inserted between the lines) trailingHeaders.append(chr); } } // Set the header value headerValue.setBytes(trailingHeaders.getBytes(), start, lastSignificantChar - start); return true; }
// in java/org/apache/coyote/http11/filters/IdentityInputFilter.java
Override public int doRead(ByteChunk chunk, Request req) throws IOException { int result = -1; if (contentLength >= 0) { if (remaining > 0) { int nRead = buffer.doRead(chunk, req); if (nRead > remaining) { // The chunk is longer than the number of bytes remaining // in the body; changing the chunk length to the number // of bytes remaining chunk.setBytes(chunk.getBytes(), chunk.getStart(), (int) remaining); result = (int) remaining; } else { result = nRead; } remaining = remaining - nRead; } else { // No more bytes left to be read : return -1 and clear the // buffer chunk.recycle(); result = -1; } } return result; }
// in java/org/apache/coyote/http11/filters/IdentityInputFilter.java
Override public long end() throws IOException { // Consume extra bytes. while (remaining > 0) { int nread = buffer.doRead(endChunk, null); if (nread > 0 ) { remaining = remaining - nread; } else { // errors are handled higher up. remaining = 0; } } // If too many bytes were read, return the amount. return -remaining; }
// in java/org/apache/coyote/http11/filters/ChunkedOutputFilter.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { int result = chunk.getLength(); if (result <= 0) { return 0; } // Calculate chunk header int pos = 7; int current = result; while (current > 0) { int digit = current % 16; current = current / 16; chunkLength[pos--] = HexUtils.getHex(digit); } chunkHeader.setBytes(chunkLength, pos + 1, 9 - pos); buffer.doWrite(chunkHeader, res); buffer.doWrite(chunk, res); chunkHeader.setBytes(chunkLength, 8, 2); buffer.doWrite(chunkHeader, res); return result; }
// in java/org/apache/coyote/http11/filters/ChunkedOutputFilter.java
Override public long end() throws IOException { // Write end chunk buffer.doWrite(END_CHUNK, null); return 0; }
// in java/org/apache/coyote/http11/filters/VoidOutputFilter.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { return chunk.getLength(); }
// in java/org/apache/coyote/http11/filters/VoidOutputFilter.java
Override public long end() throws IOException { return 0; }
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { if (compressionStream == null) { compressionStream = new FlushableGZIPOutputStream(fakeOutputStream); } compressionStream.write(chunk.getBytes(), chunk.getStart(), chunk.getLength()); return chunk.getLength(); }
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
Override public long end() throws IOException { if (compressionStream == null) { compressionStream = new FlushableGZIPOutputStream(fakeOutputStream); } compressionStream.finish(); compressionStream.close(); return ((OutputFilter) buffer).end(); }
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
Override public void write(int b) throws IOException { // Shouldn't get used for good performance, but is needed for // compatibility with Sun JDK 1.4.0 singleByteBuffer[0] = (byte) (b & 0xff); outputChunk.setBytes(singleByteBuffer, 0, 1); buffer.doWrite(outputChunk, null); }
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
Override public void write(byte[] b, int off, int len) throws IOException { outputChunk.setBytes(b, off, len); buffer.doWrite(outputChunk, null); }
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
Override public void flush() throws IOException {/*NOOP*/}
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
Override public void close() throws IOException {/*NOOP*/}
// in java/org/apache/coyote/http11/filters/BufferedInputFilter.java
Override public int doRead(ByteChunk chunk, Request request) throws IOException { if (hasRead || buffered.getLength() <= 0) { return -1; } chunk.setBytes(buffered.getBytes(), buffered.getStart(), buffered.getLength()); hasRead = true; return chunk.getLength(); }
// in java/org/apache/coyote/http11/filters/BufferedInputFilter.java
Override public long end() throws IOException { return 0; }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
Override public void write(byte[] bytes) throws IOException { write(bytes, 0, bytes.length); }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
Override public synchronized void write(byte[] bytes, int offset, int length) throws IOException { if (length > 0) { flushLastByte(); if (length > 1) { super.write(bytes, offset, length - 1); } rememberLastByte(bytes[offset + length - 1]); } }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
Override public synchronized void write(int i) throws IOException { flushLastByte(); rememberLastByte((byte) i); }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
Override public synchronized void finish() throws IOException { try { flushLastByte(); } catch (IOException ignore) { // If our write failed, then trailer write in finish() will fail // with IOException as well, but it will leave Deflater in more // consistent state. } super.finish(); }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
Override public synchronized void close() throws IOException { try { flushLastByte(); } catch (IOException ignored) { // Ignore. As OutputStream#close() says, the contract of close() // is to close the stream. It does not matter much if the // stream is not writable any more. } super.close(); }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
private void flushLastByte() throws IOException { if (hasLastByte) { // Clear the flag first, because write() may fail hasLastByte = false; super.write(lastByte, 0, 1); } }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
Override public synchronized void flush() throws IOException { if (hasLastByte) { // - do not allow the gzip header to be flushed on its own // - do not do anything if there is no data to send // trick the deflater to flush /** * Now this is tricky: We force the Deflater to flush its data by * switching compression level. As yet, a perplexingly simple workaround * for * http://developer.java.sun.com/developer/bugParade/bugs/4255743.html */ if (!def.finished()) { def.setLevel(Deflater.NO_COMPRESSION); flushLastByte(); def.setLevel(Deflater.DEFAULT_COMPRESSION); } } out.flush(); }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
Override protected void deflate() throws IOException { int len; do { len = def.deflate(buf, 0, buf.length); if (len > 0) { out.write(buf, 0, len); } } while (len != 0); }
// in java/org/apache/coyote/http11/filters/IdentityOutputFilter.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { int result = -1; if (contentLength >= 0) { if (remaining > 0) { result = chunk.getLength(); if (result > remaining) { // The chunk is longer than the number of bytes remaining // in the body; changing the chunk length to the number // of bytes remaining chunk.setBytes(chunk.getBytes(), chunk.getStart(), (int) remaining); result = (int) remaining; remaining = 0; } else { remaining = remaining - result; } buffer.doWrite(chunk, res); } else { // No more bytes left to be written : return -1 and clear the // buffer chunk.recycle(); result = -1; } } else { // If no content length was set, just write the bytes buffer.doWrite(chunk, res); result = chunk.getLength(); } return result; }
// in java/org/apache/coyote/http11/filters/IdentityOutputFilter.java
Override public long end() throws IOException { if (remaining > 0) return remaining; return 0; }
// in java/org/apache/coyote/http11/filters/VoidInputFilter.java
Override public int doRead(ByteChunk chunk, Request req) throws IOException { return -1; }
// in java/org/apache/coyote/http11/filters/VoidInputFilter.java
Override public long end() throws IOException { return 0; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
Override public SocketState process(SocketWrapper<S> socketWrapper) throws IOException { RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); // Setting up the I/O setSocketWrapper(socketWrapper); getInputBuffer().init(socketWrapper, endpoint); getOutputBuffer().init(socketWrapper, endpoint); // Flags error = false; keepAlive = true; comet = false; openSocket = false; sendfileInProgress = false; readComplete = true; if (endpoint.getUsePolling()) { keptAlive = false; } else { keptAlive = socketWrapper.isKeptAlive(); } if (disableKeepAlive()) { socketWrapper.setKeepAliveLeft(0); } while (!error && keepAlive && !comet && !isAsync() && upgradeInbound == null && !endpoint.isPaused()) { // Parsing the request header try { setRequestLineReadTimeout(); if (!getInputBuffer().parseRequestLine(keptAlive)) { if (handleIncompleteRequestLineRead()) { break; } } if (endpoint.isPaused()) { // 503 - Service unavailable response.setStatus(503); error = true; } else { request.setStartTime(System.currentTimeMillis()); keptAlive = true; // Currently only NIO will ever return false here if (!getInputBuffer().parseHeaders()) { // We've read part of the request, don't recycle it // instead associate it with the socket openSocket = true; readComplete = false; break; } if (!disableUploadTimeout) { setSocketTimeout(connectionUploadTimeout); } } } catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), e); } error = true; break; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), t); } // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; } if (!error) { // Setting up filters, and parse some request headers rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); try { prepareRequest(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug(sm.getString( "http11processor.request.prepare"), t); } // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; } } if (maxKeepAliveRequests == 1) { keepAlive = false; } else if (maxKeepAliveRequests > 0 && socketWrapper.decrementKeepAlive() <= 0) { keepAlive = false; } // Process the request in the adapter if (!error) { try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); adapter.service(request, response); // Handle when the response was committed before a serious // error occurred. Throwing a ServletException should both // set the status to 500 and set the errorException. // If we fail here, then the response is likely already // committed, so we can't try and set headers. if(keepAlive && !error) { // Avoid checking twice. error = response.getErrorException() != null || (!isAsync() && statusDropsConnection(response.getStatus())); } setCometTimeouts(socketWrapper); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString( "http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; } } // Finish the handling of the request rp.setStage(org.apache.coyote.Constants.STAGE_ENDINPUT); if (!isAsync() && !comet) { if (error) { // If we know we are closing the connection, don't drain // input. This way uploading a 100GB file doesn't tie up the // thread if the servlet has rejected it. getInputBuffer().setSwallowInput(false); } endRequest(); } rp.setStage(org.apache.coyote.Constants.STAGE_ENDOUTPUT); // If there was an error, make sure the request is counted as // and error, and update the statistics counter if (error) { response.setStatus(500); } request.updateCounters(); if (!isAsync() && !comet || error) { getInputBuffer().nextRequest(); getOutputBuffer().nextRequest(); } if (!disableUploadTimeout) { setSocketTimeout(endpoint.getSoTimeout()); } rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); if (breakKeepAliveLoop(socketWrapper)) { break; } } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (error || endpoint.isPaused()) { return SocketState.CLOSED; } else if (isAsync() || comet) { return SocketState.LONG; } else if (isUpgrade()) { return SocketState.UPGRADING; } else { if (sendfileInProgress) { return SocketState.SENDFILE; } else { if (openSocket) { if (readComplete) { return SocketState.OPEN; } else { return SocketState.LONG; } } else { return SocketState.CLOSED; } } } }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
Override public SocketState upgradeDispatch() throws IOException { // Should never reach this code but in case we do... // TODO throw new IOException( sm.getString("TODO")); }
// in java/org/apache/coyote/http11/Http11Protocol.java
Override protected Processor<Socket> createUpgradeProcessor( SocketWrapper<Socket> socket, UpgradeInbound inbound) throws IOException { return new UpgradeBioProcessor(socket, inbound); }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableDataOnly) throws IOException { int start = 0; // // Skipping blank lines // byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; // Mark the current buffer position start = pos; // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, start, pos - start); } pos++; } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; int end = 0; int questionPos = -1; // // Reading the URI // boolean eol = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request eol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (questionPos == -1)) { questionPos = pos; } pos++; } request.unparsedURI().setBytes(buf, start, end - start); if (questionPos >= 0) { request.queryString().setBytes(buf, questionPos + 1, end - questionPos - 1); request.requestURI().setBytes(buf, start, questionPos - start); } else { request.requestURI().setBytes(buf, start, end - start); } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; eol = true; } pos++; } if ((end - start) > 0) { request.protocol().setBytes(buf, start, end - start); } else { request.protocol().setString(""); } return true; }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } while (parseHeader()) { // Loop until we run out of headers } parsingHeader = false; end = pos; return true; }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override protected void init(SocketWrapper<Socket> socketWrapper, AbstractEndpoint endpoint) throws IOException { inputStream = socketWrapper.getSocket().getInputStream(); }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
private void skipLine(int start) throws IOException { boolean eol = false; int lastRealByte = start; if (pos - 1 > start) { lastRealByte = pos - 1; } while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { // Skip } else if (buf[pos] == Constants.LF) { eol = true; } else { lastRealByte = pos; } pos++; } if (log.isDebugEnabled()) { log.debug(sm.getString("iib.invalidheader", new String(buf, start, lastRealByte - start + 1, Charset.forName("ISO-8859-1")))); } }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
protected boolean fill() throws IOException { return fill(true); }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override protected boolean fill(boolean block) throws IOException { int nRead = 0; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } nRead = inputStream.read(buf, pos, buf.length - lastValid); if (nRead > 0) { lastValid = pos + nRead; } } else { if (buf.length - end < 4500) { // In this case, the request header was really large, so we allocate a // brand new one; the old one will get GCed when subsequent requests // clear all references buf = new byte[buf.length]; end = 0; } pos = end; lastValid = pos; nRead = inputStream.read(buf, pos, buf.length - lastValid); if (nRead > 0) { lastValid = pos + nRead; } } return (nRead > 0); }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override public int doRead(ByteChunk chunk, Request req ) throws IOException { if (pos >= lastValid) { if (!fill()) return -1; } int length = lastValid - pos; chunk.setBytes(buf, pos, length); pos = lastValid; return (length); }
// in java/org/apache/coyote/http11/Http11Processor.java
Override protected void setRequestLineReadTimeout() throws IOException { /* * When there is no data in the buffer and this is not the first * request on this connection and timeouts are being used the * first read for this request may need a different timeout to * take account of time spent waiting for a processing thread. * * This is a little hacky but better than exposing the socket * and the timeout info to the InputBuffer */ if (inputBuffer.lastValid == 0 && socket.getLastAccess() > -1) { int firstReadTimeout; if (keepAliveTimeout == -1) { firstReadTimeout = 0; } else { long queueTime = System.currentTimeMillis() - socket.getLastAccess(); if (queueTime >= keepAliveTimeout) { // Queued for longer than timeout but there might be // data so use shortest possible timeout firstReadTimeout = 1; } else { // Cast is safe since queueTime must be less than // keepAliveTimeout which is an int firstReadTimeout = keepAliveTimeout - (int) queueTime; } } socket.getSocket().setSoTimeout(firstReadTimeout); if (!inputBuffer.fill()) { throw new EOFException(sm.getString("iib.eof.error")); } // Once the first byte has been read, the standard timeout should be // used so restore it here. socket.getSocket().setSoTimeout(endpoint.getSoTimeout()); } }
// in java/org/apache/coyote/http11/Http11Processor.java
Override protected void setSocketTimeout(int timeout) throws IOException { socket.getSocket().setSoTimeout(timeout); }
// in java/org/apache/coyote/http11/Http11Processor.java
Override public SocketState event(SocketStatus status) throws IOException { // Should never reach this code but in case we do... throw new IOException( sm.getString("http11processor.comet.notsupported")); }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
Override public void init(SocketWrapper<Long> socketWrapper, AbstractEndpoint endpoint) throws IOException { socket = socketWrapper.getSocket().longValue(); Socket.setsbb(this.socket, bbuf); }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
Override public void flush() throws IOException { super.flush(); // Flush the current buffer flushBuffer(); }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
Override public void endRequest() throws IOException { if (!committed) { // Send the connector a request for commit. The connector should // then validate the headers, send them (using sendHeader) and // set the filters accordingly. response.action(ActionCode.COMMIT, null); } if (finished) return; if (lastActiveFilter != -1) activeFilters[lastActiveFilter].end(); flushBuffer(); finished = true; }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
Override public void sendAck() throws IOException { if (!committed) { if (Socket.send(socket, Constants.ACK_BYTES, 0, Constants.ACK_BYTES.length) < 0) throw new IOException(sm.getString("iib.failedwrite")); } }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
Override protected void commit() throws IOException { // The response is now committed committed = true; response.setCommitted(true); if (pos > 0) { // Sending the response header buffer bbuf.put(buf, 0, pos); } }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
private void flushBuffer() throws IOException { if (bbuf.position() > 0) { if (Socket.sendbb(socket, 0, bbuf.position()) < 0) { throw new IOException(); } bbuf.clear(); } }
// in java/org/apache/coyote/http11/InternalAprOutputBuffer.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { int len = chunk.getLength(); int start = chunk.getStart(); byte[] b = chunk.getBuffer(); while (len > 0) { int thisTime = len; if (bbuf.position() == bbuf.capacity()) { flushBuffer(); } if (thisTime > bbuf.capacity() - bbuf.position()) { thisTime = bbuf.capacity() - bbuf.position(); } bbuf.put(b, start, thisTime); len = len - thisTime; start = start + thisTime; } byteCount += chunk.getLength(); return chunk.getLength(); }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableData) throws IOException { int start = 0; // // Skipping blank lines // byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (useAvailableData) { return false; } if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; // Mark the current buffer position start = pos; if (pos >= lastValid) { if (useAvailableData) { return false; } if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, start, pos - start); } pos++; } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; int end = 0; int questionPos = -1; // // Reading the URI // boolean eol = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request eol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (questionPos == -1)) { questionPos = pos; } pos++; } request.unparsedURI().setBytes(buf, start, end - start); if (questionPos >= 0) { request.queryString().setBytes(buf, questionPos + 1, end - questionPos - 1); request.requestURI().setBytes(buf, start, questionPos - start); } else { request.requestURI().setBytes(buf, start, end - start); } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; eol = true; } pos++; } if ((end - start) > 0) { request.protocol().setBytes(buf, start, end - start); } else { request.protocol().setString(""); } return true; }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } while (parseHeader()) { // Loop until there are no more headers } parsingHeader = false; end = pos; return true; }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
private void skipLine(int start) throws IOException { boolean eol = false; int lastRealByte = start; if (pos - 1 > start) { lastRealByte = pos - 1; } while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { // Skip } else if (buf[pos] == Constants.LF) { eol = true; } else { lastRealByte = pos; } pos++; } if (log.isDebugEnabled()) { log.debug(sm.getString("iib.invalidheader", new String(buf, start, lastRealByte - start + 1, Charset.forName("ISO-8859-1")))); } }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override public int doRead(ByteChunk chunk, Request req) throws IOException { if (lastActiveFilter == -1) return inputStreamInputBuffer.doRead(chunk, req); else return activeFilters[lastActiveFilter].doRead(chunk,req); }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override protected void init(SocketWrapper<Long> socketWrapper, AbstractEndpoint endpoint) throws IOException { socket = socketWrapper.getSocket().longValue(); Socket.setrbb(this.socket, bbuf); }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override protected boolean fill(boolean block) throws IOException { // Ignore the block parameter and just call fill return fill(); }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
protected boolean fill() throws IOException { int nRead = 0; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.EAGAIN) { return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } else { if (buf.length - end < 4500) { // In this case, the request header was really large, so we allocate a // brand new one; the old one will get GCed when subsequent requests // clear all references buf = new byte[buf.length]; end = 0; } pos = end; lastValid = pos; bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.ETIMEDOUT || (-nRead) == Status.TIMEUP) { throw new SocketTimeoutException(sm.getString("iib.failedread")); } else if (nRead == 0) { // APR_STATUS_IS_EOF, since native 1.1.22 return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } return (nRead > 0); }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override public int doRead(ByteChunk chunk, Request req ) throws IOException { if (pos >= lastValid) { if (!fill()) return -1; } int length = lastValid - pos; chunk.setBytes(buf, pos, length); pos = lastValid; return (length); }
// in java/org/apache/coyote/http11/AbstractInputBuffer.java
public void endRequest() throws IOException { if (swallowInput && (lastActiveFilter != -1)) { int extraBytes = (int) activeFilters[lastActiveFilter].end(); pos = pos - extraBytes; } }
// in java/org/apache/coyote/http11/AbstractInputBuffer.java
Override public int doRead(ByteChunk chunk, Request req) throws IOException { if (lastActiveFilter == -1) return inputStreamInputBuffer.doRead(chunk, req); else return activeFilters[lastActiveFilter].doRead(chunk,req); }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
Override public void flush() throws IOException { super.flush(); // Flush the current buffer flushBuffer(); }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
Override public void endRequest() throws IOException { super.endRequest(); flushBuffer(); }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
Override public void sendAck() throws IOException { if (!committed) { //Socket.send(socket, Constants.ACK_BYTES, 0, Constants.ACK_BYTES.length) < 0 socket.getBufHandler() .getWriteBuffer().put(Constants.ACK_BYTES,0,Constants.ACK_BYTES.length); writeToSocket(socket.getBufHandler() .getWriteBuffer(),true,true); } }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
private synchronized int writeToSocket(ByteBuffer bytebuffer, boolean block, boolean flip) throws IOException { if ( flip ) bytebuffer.flip(); int written = 0; NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled"); long writeTimeout = att.getTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { written = pool.write(bytebuffer, socket, selector, writeTimeout, block); //make sure we are flushed do { if (socket.flush(true,selector,writeTimeout)) break; }while ( true ); }finally { if ( selector != null ) pool.put(selector); } if ( block ) bytebuffer.clear(); //only clear return written; }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
Override public void init(SocketWrapper<NioChannel> socketWrapper, AbstractEndpoint endpoint) throws IOException { socket = socketWrapper.getSocket(); pool = ((NioEndpoint)endpoint).getSelectorPool(); }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
Override protected void commit() throws IOException { // The response is now committed committed = true; response.setCommitted(true); if (pos > 0) { // Sending the response header buffer addToBB(buf, 0, pos); } }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
private synchronized void addToBB(byte[] buf, int offset, int length) throws IOException { while (length > 0) { int thisTime = length; if (socket.getBufHandler().getWriteBuffer().position() == socket.getBufHandler().getWriteBuffer().capacity() || socket.getBufHandler().getWriteBuffer().remaining()==0) { flushBuffer(); } if (thisTime > socket.getBufHandler().getWriteBuffer().remaining()) { thisTime = socket.getBufHandler().getWriteBuffer().remaining(); } socket.getBufHandler().getWriteBuffer().put(buf, offset, thisTime); length = length - thisTime; offset = offset + thisTime; } NioEndpoint.KeyAttachment ka = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( ka!= null ) ka.access();//prevent timeouts for just doing client writes }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
private void flushBuffer() throws IOException { //prevent timeout for async, SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if (key != null) { NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment) key.attachment(); attach.access(); } //write to the socket, if there is anything to write if (socket.getBufHandler().getWriteBuffer().position() > 0) { socket.getBufHandler().getWriteBuffer().flip(); writeToSocket(socket.getBufHandler().getWriteBuffer(),true, false); } }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { int len = chunk.getLength(); int start = chunk.getStart(); byte[] b = chunk.getBuffer(); addToBB(b, start, len); byteCount += chunk.getLength(); return chunk.getLength(); }
// in java/org/apache/coyote/http11/AbstractOutputBuffer.java
Override public int doWrite(ByteChunk chunk, Response res) throws IOException { if (!committed) { // Send the connector a request for commit. The connector should // then validate the headers, send them (using sendHeaders) and // set the filters accordingly. response.action(ActionCode.COMMIT, null); } if (lastActiveFilter == -1) return outputStreamOutputBuffer.doWrite(chunk, res); else return activeFilters[lastActiveFilter].doWrite(chunk, res); }
// in java/org/apache/coyote/http11/AbstractOutputBuffer.java
public void flush() throws IOException { if (!committed) { // Send the connector a request for commit. The connector should // then validate the headers, send them (using sendHeader) and // set the filters accordingly. response.action(ActionCode.COMMIT, null); } // go through the filters and if there is gzip filter // invoke it to flush for (int i = 0; i <= lastActiveFilter; i++) { if (activeFilters[i] instanceof GzipOutputFilter) { if (log.isDebugEnabled()) { log.debug("Flushing the gzip filter at position " + i + " of the filter chain..."); } ((GzipOutputFilter) activeFilters[i]).flush(); break; } } }
// in java/org/apache/coyote/http11/AbstractOutputBuffer.java
public void endRequest() throws IOException { if (!committed) { // Send the connector a request for commit. The connector should // then validate the headers, send them (using sendHeader) and // set the filters accordingly. response.action(ActionCode.COMMIT, null); } if (finished) return; if (lastActiveFilter != -1) activeFilters[lastActiveFilter].end(); finished = true; }
// in java/org/apache/coyote/http11/Http11AprProtocol.java
Override protected Processor<Long> createUpgradeProcessor( SocketWrapper<Long> socket, UpgradeInbound inbound) throws IOException { return new UpgradeAprProcessor(socket, inbound); }
// in java/org/apache/coyote/spdy/SpdyAprNpnHandler.java
Override public void init(final AbstractEndpoint ep, long sslContext, final Adapter adapter) { spdyContext = new SpdyContext(); if (sslContext == 0) { // Apr endpoint without SSL - proxy mode. spdyContext.setTlsComprression(false, false); return; } if (0 != SSLExt.setNPN(sslContext, SpdyContext.SPDY_NPN_OUT)) { log.warn("SPDY/NPN not supported"); } spdyContext.setNetSupport(new NetSupportOpenSSL()); spdyContext.setExecutor(ep.getExecutor()); spdyContext.setHandler(new SpdyHandler() { @Override public void onStream(SpdyConnection con, SpdyStream ch) throws IOException { SpdyProcessor sp = new SpdyProcessor(con, ep); sp.setAdapter(adapter); sp.onSynStream(ch); } }); }
// in java/org/apache/coyote/spdy/SpdyAprNpnHandler.java
Override public void onStream(SpdyConnection con, SpdyStream ch) throws IOException { SpdyProcessor sp = new SpdyProcessor(con, ep); sp.setAdapter(adapter); sp.onSynStream(ch); }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
Override public int doRead(ByteChunk bchunk, Request request) throws IOException { if (inFrame == null) { // blocking inFrame = spdyStream.getDataFrame(endpoint.getSoTimeout()); } if (inFrame == null) { return -1; // timeout } if (inFrame.remaining() == 0 && inFrame.isHalfClose()) { return -1; } int rd = Math.min(inFrame.remaining(), bchunk.getBytes().length); System.arraycopy(inFrame.data, inFrame.off, bchunk.getBytes(), bchunk.getStart(), rd); inFrame.advance(rd); if (inFrame.remaining() == 0) { spdy.getSpdyContext().releaseFrame(inFrame); if (!inFrame.isHalfClose()) { inFrame = null; } } bchunk.setEnd(bchunk.getEnd() + rd); return rd; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
Override public int doWrite(org.apache.tomcat.util.buf.ByteChunk chunk, Response response) throws IOException { if (!response.isCommitted()) { // Send the connector a request for commit. The connector should // then validate the headers, send them (using sendHeader) and // set the filters accordingly. response.action(ActionCode.COMMIT, null); } spdyStream.sendDataFrame(chunk.getBuffer(), chunk.getStart(), chunk.getLength(), false); byteCount += chunk.getLength(); return chunk.getLength(); }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
protected void sendSynReply() throws IOException { response.setCommitted(true); // Special headers MimeHeaders headers = response.getMimeHeaders(); String contentType = response.getContentType(); if (contentType != null) { headers.setValue("Content-Type").setString(contentType); } String contentLanguage = response.getContentLanguage(); if (contentLanguage != null) { headers.setValue("Content-Language").setString(contentLanguage); } long contentLength = response.getContentLengthLong(); if (contentLength >= 0) { headers.setValue("Content-Length").setLong(contentLength); } sendResponseHead(); }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
private void sendResponseHead() throws IOException { SpdyFrame rframe = spdy.getFrame(SpdyConnection.TYPE_SYN_REPLY); rframe.associated = 0; MimeHeaders headers = response.getMimeHeaders(); for (int i = 0; i < headers.size(); i++) { MessageBytes mb = headers.getName(i); mb.toBytes(); ByteChunk bc = mb.getByteChunk(); byte[] bb = bc.getBuffer(); for (int j = bc.getStart(); j < bc.getEnd(); j++) { bb[j] = (byte) Ascii.toLower(bb[j]); } // TODO: filter headers: Connection, Keep-Alive, Proxy-Connection, rframe.headerName(bc.getBuffer(), bc.getStart(), bc.getLength()); mb = headers.getValue(i); mb.toBytes(); bc = mb.getByteChunk(); rframe.headerValue(bc.getBuffer(), bc.getStart(), bc.getLength()); } if (response.getStatus() == 0) { rframe.addHeader(SpdyFrame.STATUS, SpdyFrame.OK200); } else { // HTTP header contents String message = null; if (org.apache.coyote.Constants.USE_CUSTOM_STATUS_MSG_IN_HEADER && HttpMessages.isSafeInHttpHeader(response.getMessage())) { message = response.getMessage(); } if (message == null) { message = HttpMessages.getMessage(response.getStatus()); } if (message == null) { // mod_jk + httpd 2.x fails with a null status message - bug // 45026 message = Integer.toString(response.getStatus()); } // TODO: optimize String status = response.getStatus() + " " + message; byte[] statusB = status.getBytes(); rframe.headerName(SpdyFrame.STATUS, 0, SpdyFrame.STATUS.length); rframe.headerValue(statusB, 0, statusB.length); } rframe.addHeader(SpdyFrame.VERSION, SpdyFrame.HTTP11); rframe.streamId = spdyStream.reqFrame.streamId; spdy.send(rframe, spdyStream); // we can't reuse the frame - it'll be queued, the coyote processor // may be reused as well. outCommit = true; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
Override public SocketState process(SocketWrapper<Object> socket) throws IOException { throw new IOException("Unimplemented"); }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
Override public SocketState event(SocketStatus status) throws IOException { System.err.println("EVENT: " + status); return null; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
Override public SocketState upgradeDispatch() throws IOException { return null; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
public void onSynStream(SpdyStream str) throws IOException { this.spdyStream = str; SpdyFrame frame = str.reqFrame; // We need to make a copy - the frame buffer will be reused. // We use the 'wrap' methods of MimeHeaders - which should be // lighter on mem in some cases. RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); // Request received. MimeHeaders mimeHeaders = request.getMimeHeaders(); for (int i = 0; i < frame.nvCount; i++) { int nameLen = frame.read16(); if (nameLen > frame.remaining()) { throw new IOException("Name too long"); } keyBuffer.setBytes(frame.data, frame.off, nameLen); if (keyBuffer.equals("method")) { frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } request.method().setBytes(frame.data, frame.off, valueLen); frame.advance(valueLen); } else if (keyBuffer.equals("url")) { frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } request.requestURI().setBytes(frame.data, frame.off, valueLen); if (SpdyContext.debug) { System.err.println("URL= " + request.requestURI()); } frame.advance(valueLen); } else if (keyBuffer.equals("version")) { frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } frame.advance(valueLen); } else { MessageBytes value = mimeHeaders.addValue(frame.data, frame.off, nameLen); frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } value.setBytes(frame.data, frame.off, valueLen); frame.advance(valueLen); } } onRequest(); }
// in java/org/apache/coyote/spdy/SpdyProxyProtocol.java
Override public void start() throws Exception { super.start(); spdyContext = new SpdyContext(); spdyContext.setTlsComprression(false, false); spdyContext.setHandler(new SpdyHandler() { @Override public void onStream(SpdyConnection con, SpdyStream ch) throws IOException { SpdyProcessor sp = new SpdyProcessor(con, endpoint); sp.setAdapter(adapter); sp.onSynStream(ch); } }); spdyContext.setNetSupport(new NetSupportSocket()); spdyContext.setExecutor(endpoint.getExecutor()); }
// in java/org/apache/coyote/spdy/SpdyProxyProtocol.java
Override public void onStream(SpdyConnection con, SpdyStream ch) throws IOException { SpdyProcessor sp = new SpdyProcessor(con, endpoint); sp.setAdapter(adapter); sp.onSynStream(ch); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public AprSocketContext setKeys(String certPemFile, String keyDerFile) throws IOException { this.sslMode = true; setTls(); certFile = certPemFile; keyFile = keyDerFile; return this; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public void listen(final int port) throws IOException { if (acceptor != null) { throw new IOException("Already accepting on " + acceptor.port); } if (sslMode && certFile == null) { throw new IOException("Missing certificates for server"); } if (sslMode || !nonBlockingAccept) { acceptorDispatch = new AcceptorDispatchThread(port); acceptorDispatch.setName("AprAcceptorDispatch-" + port); acceptorDispatch.start(); } acceptor = new AcceptorThread(port); acceptor.prepare(); acceptor.setName("AprAcceptor-" + port); acceptor.start(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public AprSocket socket(String host, int port, boolean ssl) throws IOException { HostInfo hi = getHostInfo(host, port, ssl); return socket(hi); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public AprSocket socket(HostInfo hi) throws IOException { AprSocket sock = newSocket(this); sock.setHost(hi); return sock; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public AprSocket socket(long socket) throws IOException { AprSocket sock = newSocket(this); // Tomcat doesn't set this SSLExt.sslSetMode(socket, SSLExt.SSL_MODE_ENABLE_PARTIAL_WRITE | SSLExt.SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); sock.setStatus(AprSocket.ACCEPTED); sock.socket = socket; return sock; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
protected void connectBlocking(AprSocket apr) throws IOException { try { if (!running) { throw new IOException("Stopped"); } HostInfo hi = apr.getHost(); long clientSockP; synchronized (pollers) { long socketpool = Pool.create(getRootPool()); int family = Socket.APR_INET; clientSockP = Socket.create(family, Socket.SOCK_STREAM, Socket.APR_PROTO_TCP, socketpool); // or rootPool ? } Socket.timeoutSet(clientSockP, connectTimeout * 1000); if (OS.IS_UNIX) { Socket.optSet(clientSockP, Socket.APR_SO_REUSEADDR, 1); } Socket.optSet(clientSockP, Socket.APR_SO_KEEPALIVE, 1); // Blocking // TODO: use socket pool // TODO: cache it ( and TTL ) in hi long inetAddress = Address.info(hi.host, Socket.APR_INET, hi.port, 0, rootPool); // this may take a long time - stop/destroy must wait // at least connect timeout int rc = Socket.connect(clientSockP, inetAddress); if (rc != 0) { synchronized (pollers) { Socket.close(clientSockP); Socket.destroy(clientSockP); } /////Pool.destroy(socketpool); throw new IOException("Socket.connect(): " + rc + " " + Error.strerror(rc) + " " + connectTimeout); } if (!running) { throw new IOException("Stopped"); } connectionsCount.incrementAndGet(); if (tcpNoDelay) { Socket.optSet(clientSockP, Socket.APR_TCP_NODELAY, 1); } Socket.timeoutSet(clientSockP, defaultTimeout * 1000); apr.socket = clientSockP; apr.afterConnect(); } catch (IOException e) { apr.reset(); throw e; } catch (Throwable e) { apr.reset(); e.printStackTrace(); throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
AprSocket newSocket(AprSocketContext context) throws IOException { return new AprSocket(context); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public void stop() throws IOException { synchronized (pollers) { if (!running) { return; } running = false; } if (rootPool != 0) { if (acceptor != null) { try { acceptor.unblock(); acceptor.join(); } catch (InterruptedException e) { e.printStackTrace(); } } if (acceptorDispatch != null) { acceptedQueue.add(END); try { acceptorDispatch.join(); } catch (InterruptedException e) { e.printStackTrace(); } } if (threadPool != null) { threadPool.shutdownNow(); } log.info("Stopping pollers " + contextId); while (true) { AprPoller a; synchronized (pollers) { if (pollers.size() == 0) { break; } a = pollers.remove(0); } a.interruptPoll(); try { a.join(); log.info("Poller " + a.id + " done "); } catch (InterruptedException e) { e.printStackTrace(); } } } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
private long getRootPool() throws IOException { if (rootPool == 0) { if (noApr != null) { throw noApr; } // Create the root APR memory pool rootPool = Pool.create(0); // Adjust poller sizes if ((OS.IS_WIN32 || OS.IS_WIN64) && (maxConnections > 1024)) { // The maximum per poller to get reasonable performance is 1024 pollerThreadCount = maxConnections / 1024; // Adjust poller size so that it won't reach the limit maxConnections = maxConnections - (maxConnections % 1024); } } return rootPool; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
void findPollerAndAdd(AprSocket ch) throws IOException { if (ch.poller != null) { ch.poller.requestUpdate(ch); return; } assignPoller(ch); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
void assignPoller(AprSocket ch) throws IOException { AprPoller target = null; synchronized (pollers) { // Make sure we have min number of pollers int needPollers = pollerThreadCount - pollers.size(); if (needPollers > 0) { for (int i = needPollers; i > 0; i--) { pollers.add(allocatePoller()); } } int max = 0; for (AprPoller poller: pollers) { int rem = poller.remaining(); if (rem > max) { target = poller; max = rem; } } } if (target != null && target.add(ch)) { return; } // can't be added - add a new poller synchronized (pollers) { AprPoller poller = allocatePoller(); poller.add(ch); pollers.add(poller); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
protected void onSocket(AprSocket s) throws IOException { }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
void prepare() throws IOException { try { // Create the pool for the server socket serverSockPool = Pool.create(getRootPool()); int family = Socket.APR_INET; inetAddress = Address.info(addressStr, family, port, 0, serverSockPool); // Create the APR server socket serverSock = Socket.create(family, Socket.SOCK_STREAM, Socket.APR_PROTO_TCP, serverSockPool); if (OS.IS_UNIX) { Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Deal with the firewalls that tend to drop the inactive sockets Socket.optSet(serverSock, Socket.APR_SO_KEEPALIVE, 1); // Bind the server socket int ret = Socket.bind(serverSock, inetAddress); if (ret != 0) { throw new IOException("Socket.bind " + ret + " " + Error.strerror(ret) + " port=" + port); } // Start listening on the server socket ret = Socket.listen(serverSock, backlog ); if (ret != 0) { throw new IOException("endpoint.init.listen" + ret + " " + Error.strerror(ret)); } if (OS.IS_WIN32 || OS.IS_WIN64) { // On Windows set the reuseaddr flag after the bind/listen Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Sendfile usage on systems which don't support it cause major problems if (useSendfile && !Library.APR_HAS_SENDFILE) { useSendfile = false; } // Delay accepting of new connections until data is available // Only Linux kernels 2.4 + have that implemented // on other platforms this call is noop and will return APR_ENOTIMPL. if (deferAccept) { if (Socket.optSet(serverSock, Socket.APR_TCP_DEFER_ACCEPT, 1) == Status.APR_ENOTIMPL) { deferAccept = false; } } } catch (Throwable t) { throw new IOException(t); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
AprPoller allocatePoller() throws IOException { long pool = Pool.create(getRootPool()); int size = maxConnections / pollerThreadCount; int timeout = keepAliveTimeout; long serverPollset = allocatePoller(size, pool, timeout); if (serverPollset == 0 && size > 1024) { log.severe("Falling back to 1024-sized poll, won't scale"); size = 1024; serverPollset = allocatePoller(size, pool, timeout); } if (serverPollset == 0) { log.severe("Falling back to 62-sized poll, won't scale"); size = 62; serverPollset = allocatePoller(size, pool, timeout); } AprPoller res = new AprPoller(); res.pool = pool; res.serverPollset = serverPollset; res.desc = new long[size * 2]; res.size = size; res.id = contextId++; res.setDaemon(true); res.setName("AprPoller-" + res.id); res.start(); if (debugPoll && !sizeLogged) { sizeLogged = true; log.info("Poller size " + (res.desc.length / 2)); } return res; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
protected void updates() throws IOException { synchronized (this) { for (AprSocket up: updates) { updateIOThread(up); } updates.clear(); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
boolean add(AprSocket ch) throws IOException { synchronized (this) { if (!running) { return false; } if (keepAliveCount.get() >= size) { return false; } keepAliveCount.incrementAndGet(); ch.poller = this; } requestUpdate(ch); return true; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
protected void requestUpdate(AprSocket ch) throws IOException { synchronized (this) { if (!running) { return; } } if (isPollerThread()) { updateIOThread(ch); } else { synchronized (this) { if (!updates.contains(ch)) { updates.add(ch); } interruptPoll(); } if (debugPoll) { log.info("Poll: requestUpdate " + id + " " + ch); } } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
private void updateIOThread(AprSocket ch) throws IOException { if (!running || ch.socket == 0) { return; } // called from IO thread, either in 'updates' or after // poll. //synchronized (ch) boolean polling = ch.checkPreConnect(AprSocket.POLL); int requested = ch.requestedPolling(); if (requested == 0) { if (polling) { removeSafe(ch); } if (ch.isClosed()) { synchronized (channels) { ch.poller = null; channels.remove(ch.socket); } keepAliveCount.decrementAndGet(); ch.reset(); } } else { if (polling) { removeSafe(ch); } // will close if error pollAdd(ch, requested); } if (debugPoll) { log.info("Poll: updated=" + id + " " + ch); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
private void pollAdd(AprSocket up, int req) throws IOException { boolean failed = false; int rv; synchronized (channels) { if (up.isClosed()) { return; } rv = Poll.add(serverPollset, up.socket, req); if (rv != Status.APR_SUCCESS) { up.poller = null; keepAliveCount.decrementAndGet(); failed = true; } else { polledCount.incrementAndGet(); channels.put(up.socket, up); up.setStatus(AprSocket.POLL); } } if (failed) { up.reset(); throw new IOException("poll add error " + rv + " " + up + " " + Error.strerror(rv)); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
private void removeSafe(AprSocket up) throws IOException { int rv = Status.APR_EGENERAL; if (running && serverPollset != 0 && up.socket != 0 && !up.isClosed()) { rv = Poll.remove(serverPollset, up.socket); } up.clearStatus(AprSocket.POLL); if (rv != Status.APR_SUCCESS) { log.severe("poll remove error " + Error.strerror(rv) + " " + up); } else { polledCount.decrementAndGet(); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public void connect() throws IOException { if (isBlocking()) { // will call handleConnected() at the end. context.connectBlocking(this); } else { synchronized(this) { if ((status & CONNECTING) != 0) { return; } status |= CONNECTING; } context.connectExecutor.execute(this); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
void afterConnect() throws IOException { if (hostInfo.secure) { blockingStartTLS(); } setNonBlocking(); // call again, to set the bits ( connect was blocking ) setStatus(CONNECTED); clearStatus(CONNECTING); notifyConnected(false); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int write(byte[] data, int off, int len, long to) throws IOException { long max = System.currentTimeMillis() + to; while (true) { int rc = writeInternal(data, off, len); if (rc < 0) { throw new IOException("Write error " + rc); } else if (rc == 0) { // need poll out - do we need to update polling ? context.findPollerAndAdd(this); } else { return rc; } try { long waitTime = max - System.currentTimeMillis(); if (waitTime <= 0) { return 0; } wait(waitTime); } catch (InterruptedException e) { return 0; } } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int write(byte[] data, int off, int len) throws IOException { // In SSL mode, read/write can't be called at the same time. int rc = writeInternal(data, off, len); if (rc < 0) { throw new IOException("Write error " + rc); } else if (rc == 0) { // need poll out - do we need to update polling ? synchronized (this) { context.findPollerAndAdd(this); } } return rc; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private int writeInternal(byte[] data, int off, int len) throws IOException { int rt = 0; int sent = 0; synchronized(this) { if ((status & CLOSED) != 0 || socket == 0 || !context.running) { throw new IOException("Closed"); } if ((status & WRITING) != 0) { throw new IOException("Write from 2 threads not allowed"); } status |= WRITING; while (len > 0) { sent = Socket.send(socket, data, off, len); if (sent <= 0) { break; } off += sent; len -= sent; } status &= ~WRITING; } if (context.rawDataHandler != null) { context.rawData(this, false, data, off, sent, len, false); } if (sent <= 0) { if (sent == -Status.TIMEUP || sent == -Status.EAGAIN || sent == 0) { setStatus(POLLOUT); updatePolling(); return rt; } if (context.debug) { log.warning("apr.send(): Failed to send, closing " + sent); } reset(); throw new IOException("Error sending " + sent + " " + Error.strerror(-sent)); } else { off += sent; len -= sent; rt += sent; return sent; } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int read(byte[] data, int off, int len, long to) throws IOException { int rd = readNB(data, off, len); if (rd == 0) { synchronized(this) { try { wait(to); } catch (InterruptedException e) { return 0; } } rd = readNB(data, off, len); } return processReadResult(data, off, len, rd); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int read(byte[] data, int off, int len) throws IOException { return readNB(data, off, len); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private int processReadResult(byte[] data, int off, int len, int read) throws IOException { if (context.rawDataHandler != null) { context.rawData(this, true, data, off, read, len, false); } if (read > 0) { return read; } if (read == 0 || read == -Status.TIMEUP || read == -Status.ETIMEDOUT || read == -Status.EAGAIN) { read = 0; setStatus(POLLIN); updatePolling(); return 0; } if (read == -Status.APR_EOF || read == -1) { close(); return -1; } // abrupt close reset(); throw new IOException("apr.read(): " + read + " " + Error.strerror(-read)); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int readNB(byte[] data, int off, int len) throws IOException { int read; synchronized(this) { if ((status & CLOSED) != 0 || socket == 0 || !context.running) { return -1; } if ((status & READING) != 0) { throw new IOException("Read from 2 threads not allowed"); } status |= READING; read = Socket.recv(socket, data, off, len); status &= ~READING; } return processReadResult(data, off, len, read); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public void close() throws IOException { synchronized (this) { if ((status & CLOSED) != 0 || socket == 0) { return; } status |= CLOSED; status &= ~POLLIN; status &= ~POLLOUT; } if (context.rawDataHandler != null) { context.rawDataHandler.rawData(this, false, null, 0, 0, 0, true); } Socket.close(socket); if (poller == null) { maybeDestroy(); } else { try { poller.requestUpdate(this); } catch (IOException e) { e.printStackTrace(); } } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public long getIOTimeout() throws IOException { if (socket != 0 && context.running) { try { return Socket.timeoutGet(socket) / 1000; } catch (Exception e) { throw new IOException(e); } } else { throw new IOException("Socket is closed"); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public byte[][] getPeerCert(boolean check) throws IOException { getHost(); if (hostInfo.certs != null && hostInfo.certs != NO_CERTS && !check) { return hostInfo.certs; } if (!checkBitAndSocket(SSL_ATTACHED)) { return NO_CERTS; } try { int certLength = SSLSocket.getInfoI(socket, SSL.SSL_INFO_CLIENT_CERT_CHAIN); // TODO: if resumed, old certs are good. // If not - warn if certs changed, remember first cert, etc. if (certLength <= 0) { // Can also happen on session resume - keep the old if (hostInfo.certs == null) { hostInfo.certs = NO_CERTS; } return hostInfo.certs; } hostInfo.certs = new byte[certLength + 1][]; hostInfo.certs[0] = SSLSocket.getInfoB(socket, SSL.SSL_INFO_CLIENT_CERT); for (int i = 0; i < certLength; i++) { hostInfo.certs[i + 1] = SSLSocket.getInfoB(socket, SSL.SSL_INFO_CLIENT_CERT_CHAIN + i); } return hostInfo.certs; } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public X509Certificate[] getPeerX509Cert() throws IOException { byte[][] certs = getPeerCert(false); X509Certificate[] xcerts = new X509Certificate[certs.length]; if (certs.length == 0) { return xcerts; } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (int i = 0; i < certs.length; i++) { if (certs[i] != null) { ByteArrayInputStream bis = new ByteArrayInputStream( certs[i]); xcerts[i] = (X509Certificate) cf.generateCertificate(bis); bis.close(); } } } catch (CertificateException ex) { throw new IOException(ex); } return xcerts; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getCipherSuite() throws IOException { if (checkBitAndSocket(SSL_ATTACHED)) { return null; } try { return SSLSocket.getInfoS(socket, SSL.SSL_INFO_CIPHER); } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int getKeySize() throws IOException { if (checkBitAndSocket(SSL_ATTACHED)) { return -1; } try { return SSLSocket.getInfoI(socket, SSL.SSL_INFO_CIPHER_USEKEYSIZE); } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int getRemotePort() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_REMOTE, socket); Sockaddr addr = Address.getInfo(sa); return addr.port; } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getRemoteAddress() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_REMOTE, socket); return Address.getip(sa); } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getRemoteHostname() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_REMOTE, socket); String remoteHost = Address.getnameinfo(sa, 0); if (remoteHost == null) { remoteHost = Address.getip(sa); } return remoteHost; } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public int getLocalPort() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_LOCAL, socket); Sockaddr addr = Address.getInfo(sa); return addr.port; } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getLocalAddress() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_LOCAL, socket); return Address.getip(sa); } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public String getLocalHostname() throws IOException { if (socket != 0 && context.running) { try { long sa = Address.get(Socket.APR_LOCAL, socket); return Address.getnameinfo(sa, 0); } catch (Exception ex) { throw new IOException(ex); } } throw new IOException("Socket closed"); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
void notifyIO() throws IOException { long t0 = System.currentTimeMillis(); try { if (handler != null) { handler.process(this, true, false, false); } } catch (Throwable t) { throw new IOException(t); } finally { long t1 = System.currentTimeMillis(); t1 -= t0; if (t1 > context.maxHandlerTime.get()) { context.maxHandlerTime.set(t1); } context.totalHandlerTime.addAndGet(t1); context.handlerCount.incrementAndGet(); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private void notifyConnected(boolean server) throws IOException { // Will set the handler on the channel for accepted context.onSocket(this); if (handler instanceof AprSocketContext.NonBlockingPollHandler) { ((AprSocketContext.NonBlockingPollHandler) handler).connected(this); ((AprSocketContext.NonBlockingPollHandler) handler).process(this, true, true, false); // Now register for polling - unless process() set suspendRead and // doesn't need out notifications updatePolling(); } else { if (server) { // client will block in connect(). // Server: call process(); notifyIO(); } } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private void updatePolling() throws IOException { synchronized (this) { if ((status & CLOSED) != 0) { maybeDestroy(); return; } } context.findPollerAndAdd(this); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
public void blockingStartTLS() throws IOException { synchronized(this) { if (socket == 0 || !context.running) { return; } if ((status & SSL_ATTACHED) != 0) { return; } status |= SSL_ATTACHED; } try { if (context.debug) { log.info(this + " StartSSL"); } AprSocketContext aprCon = context; SSLSocket.attach(aprCon.getSslCtx(), socket); if (context.debugSSL) { SSLExt.debug(socket); } if (!getContext().isServer()) { if (context.USE_TICKETS && hostInfo.ticketLen > 0) { SSLExt.setTicket(socket, hostInfo.ticket, hostInfo.ticketLen); } else if (hostInfo.sessDer != null) { SSLExt.setSessionData(socket, hostInfo.sessDer, hostInfo.sessDer.length); } } SSLExt.sslSetMode(socket, SSLExt.SSL_MODE_ENABLE_PARTIAL_WRITE | SSLExt.SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); int rc = SSLSocket.handshake(socket); // At this point we have the session ID, remote certs, etc // we can lookup host info if (hostInfo == null) { hostInfo = new HostInfo(); } if (rc != Status.APR_SUCCESS) { throw new IOException(this + " Handshake failed " + rc + " " + Error.strerror(rc) + " SSLL " + SSL.getLastError()); } else { // SUCCESS handshakeDone(); } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
private void handshakeDone() throws IOException { getHost(); if (socket == 0 || !context.running) { throw new IOException("Socket closed"); } if (context.USE_TICKETS && ! context.isServer()) { if (hostInfo.ticket == null) { hostInfo.ticket = new byte[2048]; } int ticketLen = SSLExt.getTicket(socket, hostInfo.ticket); if (ticketLen > 0) { hostInfo.ticketLen = ticketLen; if (context.debug) { log.info("Received ticket: " + ticketLen); } } } // TODO: if the ticket, session id or session changed - callback to // save the session again try { hostInfo.sessDer = SSLExt.getSessionData(socket); getPeerCert(true); hostInfo.sessionId = SSLSocket.getInfoS(socket, SSL.SSL_INFO_SESSION_ID); } catch (Exception e) { throw new IOException(e); } hostInfo.npn = new byte[32]; hostInfo.npnLen = SSLExt.getNPN(socket, hostInfo.npn); // If custom verification is used - should check the certificates if (context.tlsCertVerifier != null) { context.tlsCertVerifier.handshakeDone(this); } }
// in java/org/apache/tomcat/buildutil/CheckEol.java
private void check(File file, List<CheckFailure> errors, Mode mode) throws IOException { BufferedInputStream is = new BufferedInputStream(new FileInputStream( file)); try { int line = 1; int prev = -1; int ch; while ((ch = is.read()) != -1) { if (ch == '\n') { if (mode == Mode.LF && prev == '\r') { errors.add(new CheckFailure(file, line, "CRLF")); return; } else if (mode == Mode.CRLF && prev != '\r') { errors.add(new CheckFailure(file, line, "LF")); return; } line++; } else if (prev == '\r') { errors.add(new CheckFailure(file, line, "CR")); return; } prev = ch; } } finally { is.close(); } }
// in java/org/apache/tomcat/buildutil/Txt2Html.java
private void convert( File from, File to ) throws IOException { // Open files: BufferedReader in = new BufferedReader( new FileReader( from ) ); PrintWriter out = new PrintWriter( new FileWriter( to ) ); // Output header: out.println( "<html><body><pre>" ); // Convert, line-by-line: String line; while( (line = in.readLine()) != null ) { StringBuilder result = new StringBuilder(); int len = line.length(); for( int i = 0; i < len; i++ ) { char c = line.charAt( i ); switch( c ) { case '&': result.append( "&amp;" ); break; case '<': result.append( "&lt;" ); break; default: result.append( c ); } } out.println( result.toString() ); } // Output footer: out.println( "</pre></body></html>" ); // Close streams: out.close(); in.close(); }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public void onCtlFrame(SpdyFrame frame) throws IOException { // TODO: handle RST if (frame.type == SpdyConnection.TYPE_SYN_STREAM) { reqFrame = frame; } else if (frame.type == SpdyConnection.TYPE_SYN_REPLY) { resFrame = frame; } synchronized (this) { inData.add(frame); if (frame.isHalfClose()) { finRcvd = true; } } }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public SpdyFrame getDataFrame(long to) throws IOException { while (true) { SpdyFrame res = getFrame(to); if (res == null || res.isData()) { return res; } if (res.type == SpdyConnection.TYPE_RST_STREAM) { throw new IOException("Reset"); } } }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public SpdyFrame getFrame(long to) throws IOException { SpdyFrame in; try { synchronized (this) { if (inData.size() == 0 && finRcvd) { return END_FRAME; } } in = inData.poll(to, TimeUnit.MILLISECONDS); return in; } catch (InterruptedException e) { return null; } }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public synchronized void sendDataFrame(byte[] data, int start, int length, boolean close) throws IOException { SpdyFrame oframe = spdy.getDataFrame(); // Options: // 1. wrap the byte[] data, use a separate header[], wait frame sent // -> 2 socket writes // 2. copy the data to frame byte[] -> non-blocking queue // 3. copy the data, blocking drain -> like 1, trade one copy to // avoid // 1 tcp packet. That's the current choice, seems closer to rest of // tomcat if (close) oframe.halfClose(); oframe.append(data, start, length); spdy.send(oframe, this); }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public void send() throws IOException { send("http", "GET"); }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public void send(String host, String url, String scheme, String method) throws IOException { getRequest().addHeader("host", host); getRequest().addHeader("url", url); send(scheme, method); }
// in java/org/apache/tomcat/spdy/SpdyStream.java
public void send(String scheme, String method) throws IOException { getRequest(); if ("GET".equalsIgnoreCase(method)) { // TODO: add the others reqFrame.halfClose(); } getRequest().addHeader("scheme", "http"); // todo getRequest().addHeader("method", method); getRequest().addHeader("version", "HTTP/1.1"); if (reqFrame.isHalfClose()) { finSent = true; } spdy.send(reqFrame, this); }
// in java/org/apache/tomcat/spdy/SpdyStream.java
private void fill() throws IOException { if (current == null || current.off == current.endData) { if (current != null) { spdy.spdyContext.releaseFrame(current); } current = getFrame(to); } }
// in java/org/apache/tomcat/spdy/SpdyStream.java
Override public int read() throws IOException { fill(); if (current == null) { return -1; } return current.readByte(); }
// in java/org/apache/tomcat/spdy/SpdyStream.java
Override public int read(byte b[], int off, int len) throws IOException { fill(); if (current == null) { return -1; } // don't wait for next frame int rd = Math.min(len, current.endData - current.off); System.arraycopy(current.data, current.off, b, off, rd); current.off += rd; return rd; }
// in java/org/apache/tomcat/spdy/SpdyStream.java
Override public int available() throws IOException { return 0; }
// in java/org/apache/tomcat/spdy/SpdyStream.java
Override public void close() throws IOException { // send RST if not closed }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
public void nonBlockingSend(SpdyFrame oframe, SpdyStream proc) throws IOException { queueFrame(oframe, proc, oframe.pri == 0 ? outQueue : prioriyQueue); getSpdyContext().getExecutor().execute(nbDrain); }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
public void send(SpdyFrame oframe, SpdyStream proc) throws IOException { queueFrame(oframe, proc, oframe.pri == 0 ? outQueue : prioriyQueue); drain(); }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
private void queueFrame(SpdyFrame oframe, SpdyStream proc, LinkedList<SpdyFrame> queue) throws IOException { oframe.endData = oframe.off; oframe.off = 0; // We can't assing a stream ID until it is sent - priorities // we can't compress either - it's stateful. oframe.stream = proc; // all sync for adding/removing is on outQueue synchronized (outQueue) { queue.add(oframe); } }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
public int processInput() throws IOException { while (true) { if (inFrame == null) { inFrame = getSpdyContext().getFrame(); } if (inFrame.data == null) { inFrame.data = new byte[16 * 1024]; } // we might already have data from previous frame if (inFrame.endReadData < 8 || // we don't have the header inFrame.endReadData < inFrame.endData) { int rd = read(inFrame.data, inFrame.endReadData, inFrame.data.length - inFrame.endReadData); if (rd == -1) { if (channels.size() == 0) { return CLOSE; } else { abort("Closed"); } } else if (rd < 0) { abort("Closed - read error"); return CLOSE; } else if (rd == 0) { return LONG; // Non-blocking channel - will resume reading at off } inFrame.endReadData += rd; } if (inFrame.endReadData < 8) { continue; // keep reading } if (inFrame.endData == 0) { inFrame.parse(); if (inFrame.version != 2) { abort("Wrong version"); return CLOSE; } // MAX_FRAME_SIZE if (inFrame.endData < 0 || inFrame.endData > 32000) { abort("Framing error, size = " + inFrame.endData); return CLOSE; } // TODO: if data, split it in 2 frames // grow the buffer if needed. if (inFrame.data.length < inFrame.endData) { byte[] tmp = new byte[inFrame.endData]; System.arraycopy(inFrame.data, 0, tmp, 0, inFrame.endReadData); inFrame.data = tmp; } } if (inFrame.endReadData < inFrame.endData) { continue; // keep reading to fill current frame } // else: we have at least the current frame int extra = inFrame.endReadData - inFrame.endData; if (extra > 0) { // and a bit more - to keep things simple for now we // copy them to next frame, at least we saved reads. // it is possible to avoid copy - but later. nextFrame = getSpdyContext().getFrame(); nextFrame.makeSpace(extra); System.arraycopy(inFrame.data, inFrame.endData, nextFrame.data, 0, extra); nextFrame.endReadData = extra; inFrame.endReadData = inFrame.endData; } // decompress if (inFrame.type == TYPE_SYN_STREAM) { inFrame.streamId = inFrame.readInt(); // 4 lastChannel = inFrame.streamId; inFrame.associated = inFrame.readInt(); // 8 inFrame.pri = inFrame.read16(); // 10 pri and unused if (compressSupport != null) { compressSupport.decompress(inFrame, 18); } inFrame.nvCount = inFrame.read16(); } else if (inFrame.type == TYPE_SYN_REPLY || inFrame.type == TYPE_HEADERS) { inFrame.streamId = inFrame.readInt(); // 4 inFrame.read16(); if (compressSupport != null) { compressSupport.decompress(inFrame, 14); } inFrame.nvCount = inFrame.read16(); } if (SpdyContext.debug) { trace("< " + inFrame); } try { int state = handleFrame(); if (state == CLOSE) { return state; } } catch (Throwable t) { abort("Error handling frame"); t.printStackTrace(); return CLOSE; } if (inFrame != null) { inFrame.recyle(); if (nextFrame != null) { getSpdyContext().releaseFrame(inFrame); inFrame = nextFrame; nextFrame = null; } } else { inFrame = nextFrame; nextFrame = null; if (inFrame == null) { inFrame = getSpdyContext().getFrame(); } } } }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
protected int handleFrame() throws IOException { if (inFrame.c) { switch (inFrame.type) { case TYPE_SETTINGS: { int cnt = inFrame.readInt(); for (int i = 0; i < cnt; i++) { int flag = inFrame.readByte(); int id = inFrame.read24(); int value = inFrame.readInt(); } // TODO: save/interpret settings break; } case TYPE_GOAWAY: { int lastStream = inFrame.readInt(); log.info("GOAWAY last=" + lastStream); // Server will shut down - but will keep processing the current requests, // up to lastStream. If we sent any new ones - they need to be canceled. abort("GO_AWAY", lastStream); goAway = lastStream; return CLOSE; } case TYPE_RST_STREAM: { inFrame.streamId = inFrame.read32(); int errCode = inFrame.read32(); if (SpdyContext.debug) { trace("> RST " + inFrame.streamId + " " + ((errCode < RST_ERRORS.length) ? RST_ERRORS[errCode] : errCode)); } SpdyStream sch; synchronized(channels) { sch = channels.remove(inFrame.streamId); } // if RST stream is for a closed channel - we can ignore. if (sch != null) { sch.onReset(); } inFrame = null; break; } case TYPE_SYN_STREAM: { SpdyStream ch = getSpdyContext().getStream(this); synchronized (channels) { channels.put(inFrame.streamId, ch); } try { ch.onCtlFrame(inFrame); inFrame = null; } catch (Throwable t) { log.log(Level.SEVERE, "Error parsing head SYN_STREAM", t); abort("Error reading headers " + t); return CLOSE; } spdyContext.onStream(this, ch); break; } case TYPE_SYN_REPLY: { SpdyStream sch; synchronized(channels) { sch = channels.get(inFrame.streamId); } if (sch == null) { abort("Missing channel"); return CLOSE; } try { sch.onCtlFrame(inFrame); inFrame = null; } catch (Throwable t) { log.info("Error parsing head SYN_STREAM" + t); abort("Error reading headers " + t); return CLOSE; } break; } case TYPE_PING: { SpdyFrame oframe = getSpdyContext().getFrame(); oframe.type = TYPE_PING; oframe.c = true; oframe.append32(inFrame.read32()); oframe.pri = 0x80; send(oframe, null); break; } } } else { // Data frame SpdyStream sch; synchronized (channels) { sch = channels.get(inFrame.streamId); } if (sch == null) { abort("Missing channel"); return CLOSE; } sch.onDataFrame(inFrame); synchronized (channels) { if (sch.finRcvd && sch.finSent) { channels.remove(inFrame.streamId); } } inFrame = null; } return LONG; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
public SpdyStream get(String host, String url) throws IOException { SpdyStream sch = new SpdyStream(this); sch.getRequest().addHeader("host", host); sch.getRequest().addHeader("url", url); sch.send(); return sch; }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public SpdyConnection getConnection(String host, int port) throws IOException { SpdyConnectionAprSocket spdy = new SpdyConnectionAprSocket(ctx); AprSocket ch = con.socket(host, port, ctx.tls); spdy.setSocket(ch); ch.connect(); ch.setHandler(new SpdySocketHandler(spdy)); // need to consume the input to receive more read events int rc = spdy.processInput(); if (rc == SpdyConnection.CLOSE) { ch.close(); throw new IOException("Error connecting"); } return spdy; }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public void onAccept(Object socket) throws IOException { onAcceptLong((Long) socket); }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
public void onAcceptLong(long socket) throws IOException { SpdyConnectionAprSocket spdy = new SpdyConnectionAprSocket(ctx); AprSocket s = con.socket(socket); spdy.setSocket(s); SpdySocketHandler handler = new SpdySocketHandler(spdy); s.setHandler(handler); handler.process(s, true, true, false); }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public void listen(final int port, String cert, String key) throws IOException { con = new AprSocketContext() { @Override protected void onSocket(AprSocket s) throws IOException { SpdyConnectionAprSocket spdy = new SpdyConnectionAprSocket(ctx); spdy.setSocket(s); SpdySocketHandler handler = new SpdySocketHandler(spdy); s.setHandler(handler); } }; con.setNpn(SpdyContext.SPDY_NPN_OUT); con.setKeys(cert, key); con.listen(port); }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override protected void onSocket(AprSocket s) throws IOException { SpdyConnectionAprSocket spdy = new SpdyConnectionAprSocket(ctx); spdy.setSocket(s); SpdySocketHandler handler = new SpdySocketHandler(spdy); s.setHandler(handler); }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public void stop() throws IOException { con.stop(); }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public void close() throws IOException { socket.close(); }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public int write(byte[] data, int off, int len) throws IOException { if (socket == null) { return -1; } int sent = socket.write(data, off, len); if (sent < 0) { return -1; } return sent; }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
Override public int read(byte[] data, int off, int len) throws IOException { if (socket == null) { return -1; } int rd = socket.read(data, off, len); // org.apache.tomcat.jni.Socket.recv(socket, data, off, len); if (rd == -Status.APR_EOF) { return -1; } if (rd == -Status.TIMEUP || rd == -Status.EINTR || rd == -Status.EAGAIN) { rd = 0; } if (rd < 0) { return -1; } off += rd; len -= rd; return rd; }
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
Override public synchronized void compress(SpdyFrame frame, int start) throws IOException { init(); if (compressBuffer == null) { compressBuffer = new byte[frame.data.length]; } // last byte for flush ? zipOut.setInput(frame.data, start, frame.endData - start - 1); int coff = start; zipOut.setLevel(Deflater.DEFAULT_COMPRESSION); while (true) { int rd = zipOut.deflate(compressBuffer, coff, compressBuffer.length - coff); if (rd == 0) { // needsInput needs to be called - we're done with this frame ? zipOut.setInput(frame.data, frame.endData - 1, 1); zipOut.setLevel(Deflater.BEST_SPEED); while (true) { rd = zipOut.deflate(compressBuffer, coff, compressBuffer.length - coff); coff += rd; if (rd == 0) { break; } byte[] b = new byte[compressBuffer.length * 2]; System.arraycopy(compressBuffer, 0, b, 0, coff); compressBuffer = b; } zipOut.setLevel(Deflater.DEFAULT_COMPRESSION); break; } coff += rd; } byte[] tmp = frame.data; frame.data = compressBuffer; compressBuffer = tmp; frame.endData = coff; }
// in java/org/apache/tomcat/spdy/CompressDeflater6.java
Override public synchronized void decompress(SpdyFrame frame, int start) throws IOException { // stream id ( 4 ) + unused ( 2 ) // nvCount is compressed in impl - spec is different init(); if (decompressBuffer == null) { decompressBuffer = new byte[frame.data.length]; } // will read from dec buffer to frame.data decMax = frame.endData; decOff = start; int off = start; zipIn.setInput(frame.data, start, decMax - start); while (true) { int rd; try { rd = zipIn.inflate(decompressBuffer, off, decompressBuffer.length - off); if (rd == 0 && zipIn.needsDictionary()) { zipIn.setDictionary(SPDY_DICT); continue; } } catch (DataFormatException e) { throw new IOException(e); } if (rd == 0) { break; } if (rd == -1) { break; } off += rd; byte[] b = new byte[decompressBuffer.length * 2]; System.arraycopy(decompressBuffer, 0, b, 0, off); decompressBuffer = b; } byte[] tmpBuf = decompressBuffer; decompressBuffer = frame.data; frame.data = tmpBuf; frame.off = start; frame.endData = off; }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
Override public SpdyConnection getConnection(String host, int port) throws IOException { try { Socket sock = getSocket(host, port); sock.getInputStream(); SpdyConnectionSocket con = new SpdyConnectionSocket(ctx, sock); ctx.getExecutor().execute(con.inputThread); return con; } catch (IOException ex) { ex.printStackTrace(); throw ex; } }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
protected Socket getSocket(String host, int port) throws IOException { try { if (ctx.tls) { SSLContext sslCtx = SSLContext.getDefault(); SSLSocket socket = (SSLSocket) sslCtx.getSocketFactory().createSocket(host, port); //socket.setEnabledProtocols(new String[] {"TLS1"}); socket.startHandshake(); return socket; } else { return new Socket(host, port); } } catch (NoSuchAlgorithmException e) { throw new IOException(e); } }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
Override public void stop() throws IOException { running = false; serverSocket.close(); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
Override public void listen(final int port, String cert, String key) throws IOException { ctx.getExecutor().execute(new Runnable() { @Override public void run() { accept(port); } }); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
Override public void close() throws IOException { socket.close(); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
Override public synchronized int write(byte[] data, int off, int len) throws IOException { socket.getOutputStream().write(data, off, len); return len; }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
Override public int read(byte[] data, int off, int len) throws IOException { try { return socket.getInputStream().read(data, off, len); } catch (SocketTimeoutException ex) { return 0; } }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public void onAccept(Object socket) throws IOException { }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public void listen(int port, String cert, String key) throws IOException { }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public void stop() throws IOException { }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public SpdyConnection getConnection(String host, int port) throws IOException { return netSupport.getConnection(host, port); }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public final void listen(final int port, String cert, String key) throws IOException { netSupport.listen(port, cert, key); }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public final void stop() throws IOException { netSupport.stop(); }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public void onStream(SpdyConnection spdyConnection, SpdyStream ch) throws IOException { if (handler instanceof NonBlockingSpdyHandler) { handler.onStream(spdyConnection, ch); } else { getExecutor().execute(ch); } }
// in java/org/apache/tomcat/util/net/NioChannel.java
public void reset() throws IOException { bufHandler.getReadBuffer().clear(); bufHandler.getWriteBuffer().clear(); this.sendFile = false; }
// in java/org/apache/tomcat/util/net/NioChannel.java
public boolean flush(boolean block, Selector s, long timeout) throws IOException { return true; }
// in java/org/apache/tomcat/util/net/NioChannel.java
Override public void close() throws IOException { getIOChannel().socket().close(); getIOChannel().close(); }
// in java/org/apache/tomcat/util/net/NioChannel.java
public void close(boolean force) throws IOException { if (isOpen() || force ) close(); }
// in java/org/apache/tomcat/util/net/NioChannel.java
Override public int write(ByteBuffer src) throws IOException { return sc.write(src); }
// in java/org/apache/tomcat/util/net/NioChannel.java
Override public int read(ByteBuffer dst) throws IOException { return sc.read(dst); }
// in java/org/apache/tomcat/util/net/NioChannel.java
public int handshake(boolean read, boolean write) throws IOException { return 0; }
// in java/org/apache/tomcat/util/net/NioChannel.java
public boolean flushOutbound() throws IOException { return false; }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
public void reset(SSLEngine engine) throws IOException { this.sslEngine = engine; reset(); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public void reset() throws IOException { super.reset(); netOutBuffer.position(0); netOutBuffer.limit(0); netInBuffer.position(0); netInBuffer.limit(0); handshakeComplete = false; closed = false; closing = false; //initiate handshake sslEngine.beginHandshake(); handshakeStatus = sslEngine.getHandshakeStatus(); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public boolean flush(boolean block, Selector s, long timeout) throws IOException { if (!block) { flush(netOutBuffer); } else { pool.write(netOutBuffer, this, s, timeout,block); } return !netOutBuffer.hasRemaining(); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
protected boolean flush(ByteBuffer buf) throws IOException { int remaining = buf.remaining(); if ( remaining > 0 ) { int written = sc.write(buf); return written >= remaining; }else { return true; } }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int handshake(boolean read, boolean write) throws IOException { if ( handshakeComplete ) return 0; //we have done our initial handshake if (!flush(netOutBuffer)) return SelectionKey.OP_WRITE; //we still have data to write SSLEngineResult handshake = null; while (!handshakeComplete) { switch ( handshakeStatus ) { case NOT_HANDSHAKING: { //should never happen throw new IOException("NOT_HANDSHAKING during handshake"); } case FINISHED: { //we are complete if we have delivered the last package handshakeComplete = !netOutBuffer.hasRemaining(); //return 0 if we are complete, otherwise we still have data to write return handshakeComplete?0:SelectionKey.OP_WRITE; } case NEED_WRAP: { //perform the wrap function handshake = handshakeWrap(write); if ( handshake.getStatus() == Status.OK ){ if (handshakeStatus == HandshakeStatus.NEED_TASK) handshakeStatus = tasks(); } else { //wrap should always work with our buffers throw new IOException("Unexpected status:" + handshake.getStatus() + " during handshake WRAP."); } if ( handshakeStatus != HandshakeStatus.NEED_UNWRAP || (!flush(netOutBuffer)) ) { //should actually return OP_READ if we have NEED_UNWRAP return SelectionKey.OP_WRITE; } //fall down to NEED_UNWRAP on the same call, will result in a //BUFFER_UNDERFLOW if it needs data } //$FALL-THROUGH$ case NEED_UNWRAP: { //perform the unwrap function handshake = handshakeUnwrap(read); if ( handshake.getStatus() == Status.OK ) { if (handshakeStatus == HandshakeStatus.NEED_TASK) handshakeStatus = tasks(); } else if ( handshake.getStatus() == Status.BUFFER_UNDERFLOW ){ //read more data, reregister for OP_READ return SelectionKey.OP_READ; } else { throw new IOException("Invalid handshake status:"+handshakeStatus+" during handshake UNWRAP."); }//switch break; } case NEED_TASK: { handshakeStatus = tasks(); break; } default: throw new IllegalStateException("Invalid handshake status:"+handshakeStatus); }//switch }//while //return 0 if we are complete, otherwise reregister for any activity that //would cause this method to be called again. return handshakeComplete?0:(SelectionKey.OP_WRITE|SelectionKey.OP_READ); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
protected SSLEngineResult handshakeWrap(boolean doWrite) throws IOException { //this should never be called with a network buffer that contains data //so we can clear it here. netOutBuffer.clear(); //perform the wrap SSLEngineResult result = sslEngine.wrap(bufHandler.getWriteBuffer(), netOutBuffer); //prepare the results to be written netOutBuffer.flip(); //set the status handshakeStatus = result.getHandshakeStatus(); //optimization, if we do have a writable channel, write it now if ( doWrite ) flush(netOutBuffer); return result; }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
protected SSLEngineResult handshakeUnwrap(boolean doread) throws IOException { if (netInBuffer.position() == netInBuffer.limit()) { //clear the buffer if we have emptied it out on data netInBuffer.clear(); } if ( doread ) { //if we have data to read, read it int read = sc.read(netInBuffer); if (read == -1) throw new IOException("EOF encountered during handshake."); } SSLEngineResult result; boolean cont = false; //loop while we can perform pure SSLEngine data do { //prepare the buffer with the incoming data netInBuffer.flip(); //call unwrap result = sslEngine.unwrap(netInBuffer, bufHandler.getReadBuffer()); //compact the buffer, this is an optional method, wonder what would happen if we didn't netInBuffer.compact(); //read in the status handshakeStatus = result.getHandshakeStatus(); if ( result.getStatus() == SSLEngineResult.Status.OK && result.getHandshakeStatus() == HandshakeStatus.NEED_TASK ) { //execute tasks if we need to handshakeStatus = tasks(); } //perform another unwrap? cont = result.getStatus() == SSLEngineResult.Status.OK && handshakeStatus == HandshakeStatus.NEED_UNWRAP; }while ( cont ); return result; }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public void close() throws IOException { if (closing) return; closing = true; sslEngine.closeOutbound(); if (!flush(netOutBuffer)) { throw new IOException("Remaining data in the network buffer, can't send SSL close message, force a close with close(true) instead"); } //prep the buffer for the close message netOutBuffer.clear(); //perform the close, since we called sslEngine.closeOutbound SSLEngineResult handshake = sslEngine.wrap(getEmptyBuf(), netOutBuffer); //we should be in a close state if (handshake.getStatus() != SSLEngineResult.Status.CLOSED) { throw new IOException("Invalid close state, will not send network data."); } //prepare the buffer for writing netOutBuffer.flip(); //if there is data to be written flush(netOutBuffer); //is the channel closed? closed = (!netOutBuffer.hasRemaining() && (handshake.getHandshakeStatus() != HandshakeStatus.NEED_WRAP)); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public void close(boolean force) throws IOException { try { close(); }finally { if ( force || closed ) { closed = true; sc.socket().close(); sc.close(); } } }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int read(ByteBuffer dst) throws IOException { //if we want to take advantage of the expand function, make sure we only use the ApplicationBufferHandler's buffers if ( dst != bufHandler.getReadBuffer() ) throw new IllegalArgumentException("You can only read using the application read buffer provided by the handler."); //are we in the middle of closing or closed? if ( closing || closed) return -1; //did we finish our handshake? if (!handshakeComplete) throw new IllegalStateException("Handshake incomplete, you must complete handshake before reading data."); //read from the network int netread = sc.read(netInBuffer); //did we reach EOF? if so send EOF up one layer. if (netread == -1) return -1; //the data read int read = 0; //the SSL engine result SSLEngineResult unwrap; do { //prepare the buffer netInBuffer.flip(); //unwrap the data unwrap = sslEngine.unwrap(netInBuffer, dst); //compact the buffer netInBuffer.compact(); if ( unwrap.getStatus()==Status.OK || unwrap.getStatus()==Status.BUFFER_UNDERFLOW ) { //we did receive some data, add it to our total read += unwrap.bytesProduced(); //perform any tasks if needed if (unwrap.getHandshakeStatus() == HandshakeStatus.NEED_TASK) tasks(); //if we need more network data, then bail out for now. if ( unwrap.getStatus() == Status.BUFFER_UNDERFLOW ) break; }else if ( unwrap.getStatus()==Status.BUFFER_OVERFLOW && read>0 ) { //buffer overflow can happen, if we have read data, then //empty out the dst buffer before we do another read break; }else { //here we should trap BUFFER_OVERFLOW and call expand on the buffer //for now, throw an exception, as we initialized the buffers //in the constructor throw new IOException("Unable to unwrap data, invalid status: " + unwrap.getStatus()); } } while ( (netInBuffer.position() != 0)); //continue to unwrapping as long as the input buffer has stuff return (read); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int write(ByteBuffer src) throws IOException { if ( src == this.netOutBuffer ) { //we can get here through a recursive call //by using the NioBlockingSelector int written = sc.write(src); return written; } else { //make sure we can handle expand, and that we only use on buffer if ( (!this.isSendFile()) && (src != bufHandler.getWriteBuffer()) ) throw new IllegalArgumentException("You can only write using the application write buffer provided by the handler."); //are we closing or closed? if ( closing || closed) throw new IOException("Channel is in closing state."); //the number of bytes written int written = 0; if (!flush(netOutBuffer)) { //we haven't emptied out the buffer yet return written; } /* * The data buffer is empty, we can reuse the entire buffer. */ netOutBuffer.clear(); SSLEngineResult result = sslEngine.wrap(src, netOutBuffer); written = result.bytesConsumed(); netOutBuffer.flip(); if (result.getStatus() == Status.OK) { if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) tasks(); } else { throw new IOException("Unable to wrap data, invalid engine state: " +result.getStatus()); } //force a flush flush(netOutBuffer); return written; } }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public boolean flushOutbound() throws IOException { int remaining = netOutBuffer.remaining(); flush(netOutBuffer); int remaining2= netOutBuffer.remaining(); return remaining2 < remaining; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int write(ByteBuffer buf, NioChannel socket, long writeTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int written = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) && buf.hasRemaining()) { if (keycount > 0) { //only write if we were registered for a write int cnt = socket.write(buf); //write the data if (cnt == -1) throw new EOFException(); written += cnt; if (cnt > 0) { time = System.currentTimeMillis(); //reset our timeout timer continue; //we successfully wrote, try again without a selector } } try { if ( att.getWriteLatch()==null || att.getWriteLatch().getCount()==0) att.startWriteLatch(1); poller.add(att,SelectionKey.OP_WRITE,reference); if (writeTimeout < 0) { att.awaitWriteLatch(Long.MAX_VALUE,TimeUnit.MILLISECONDS); } else { att.awaitWriteLatch(writeTimeout,TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getWriteLatch()!=null && att.getWriteLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetWriteLatch(); } if (writeTimeout > 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= writeTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_WRITE); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return written; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int read(ByteBuffer buf, NioChannel socket, long readTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int read = 0; boolean timedout = false; int keycount = 1; //assume we can read long time = System.currentTimeMillis(); //start the timeout timer try { while(!timedout) { if (keycount > 0) { //only read if we were registered for a read read = socket.read(buf); if (read == -1) throw new EOFException(); if (read > 0) break; } try { if ( att.getReadLatch()==null || att.getReadLatch().getCount()==0) att.startReadLatch(1); poller.add(att,SelectionKey.OP_READ, reference); if (readTimeout < 0) { att.awaitReadLatch(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } else { att.awaitReadLatch(readTimeout, TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getReadLatch()!=null && att.getReadLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetReadLatch(); } if (readTimeout >= 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= readTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_READ); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return read; }
// in java/org/apache/tomcat/util/net/DefaultServerSocketFactory.java
Override public ServerSocket createSocket (int port) throws IOException { return new ServerSocket (port); }
// in java/org/apache/tomcat/util/net/DefaultServerSocketFactory.java
Override public ServerSocket createSocket (int port, int backlog) throws IOException { return new ServerSocket (port, backlog); }
// in java/org/apache/tomcat/util/net/DefaultServerSocketFactory.java
Override public ServerSocket createSocket (int port, int backlog, InetAddress ifAddress) throws IOException { return new ServerSocket (port, backlog, ifAddress); }
// in java/org/apache/tomcat/util/net/DefaultServerSocketFactory.java
Override public Socket acceptSocket(ServerSocket socket) throws IOException { return socket.accept(); }
// in java/org/apache/tomcat/util/net/DefaultServerSocketFactory.java
Override public void handshake(Socket sock) throws IOException { // NOOP }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
Override public String getCipherSuite() throws IOException { // Look up the current SSLSession if (session == null) return null; return session.getCipherSuite(); }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
Override public Object[] getPeerCertificateChain() throws IOException { return getPeerCertificateChain(false); }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
Override public Object[] getPeerCertificateChain(boolean force) throws IOException { // Look up the current SSLSession if (session == null) return null; // Convert JSSE's certificate format to the ones we need X509Certificate [] jsseCerts = null; try { jsseCerts = session.getPeerCertificateChain(); } catch(Exception bex) { // ignore. } if (jsseCerts == null) jsseCerts = new X509Certificate[0]; if(jsseCerts.length <= 0 && force && ssl != null) { session.invalidate(); handShake(); session = ssl.getSession(); } return getX509Certificates(session); }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
protected void handShake() throws IOException { if( ssl.getWantClientAuth() ) { log.debug(sm.getString("jsseSupport.noCertWant")); } else { ssl.setNeedClientAuth(true); } if (ssl.getEnabledCipherSuites().length == 0) { // Handshake is never going to be successful. // Assume this is because handshakes are disabled log.warn(sm.getString("jsseSupport.serverRenegDisabled")); session.invalidate(); ssl.close(); return; } InputStream in = ssl.getInputStream(); int oldTimeout = ssl.getSoTimeout(); ssl.setSoTimeout(1000); byte[] b = new byte[1]; listener.reset(); ssl.startHandshake(); int maxTries = 60; // 60 * 1000 = example 1 minute time out for (int i = 0; i < maxTries; i++) { if (log.isTraceEnabled()) log.trace("Reading for try #" + i); try { int read = in.read(b); if (read > 0) { // Shouldn't happen as all input should have been swallowed // before trying to do the handshake. If it does, something // went wrong so lets bomb out now. throw new SSLException( sm.getString("jsseSupport.unexpectedData")); } } catch(SSLException sslex) { log.info(sm.getString("jsseSupport.clientCertError"), sslex); throw sslex; } catch (IOException e) { // ignore - presumably the timeout } if (listener.completed) { break; } } ssl.setSoTimeout(oldTimeout); if (listener.completed == false) { throw new SocketException("SSL Cert handshake timeout"); } }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
Override public Integer getKeySize() throws IOException { // Look up the current SSLSession SSLSupport.CipherData c_aux[]=ciphers; if (session == null) return null; Integer keySize = null; synchronized(keySizeCache) { keySize = keySizeCache.get(session); } if (keySize == null) { int size = 0; String cipherSuite = session.getCipherSuite(); for (int i = 0; i < c_aux.length; i++) { if (cipherSuite.indexOf(c_aux[i].phrase) >= 0) { size = c_aux[i].keySize; break; } } keySize = Integer.valueOf(size); synchronized(keySizeCache) { keySizeCache.put(session, keySize); } } return keySize; }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
Override public String getSessionId() throws IOException { // Look up the current SSLSession if (session == null) return null; // Expose ssl_session (getId) byte [] ssl_session = session.getId(); if ( ssl_session == null) return null; StringBuilder buf=new StringBuilder(); for(int x=0; x<ssl_session.length; x++) { String digit=Integer.toHexString(ssl_session[x]); if (digit.length()<2) buf.append('0'); if (digit.length()>2) digit=digit.substring(digit.length()-2); buf.append(digit); } return buf.toString(); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public ServerSocket createSocket (int port) throws IOException { init(); ServerSocket socket = sslProxy.createServerSocket(port); initServerSocket(socket); return socket; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public ServerSocket createSocket (int port, int backlog) throws IOException { init(); ServerSocket socket = sslProxy.createServerSocket(port, backlog); initServerSocket(socket); return socket; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public ServerSocket createSocket (int port, int backlog, InetAddress ifAddress) throws IOException { init(); ServerSocket socket = sslProxy.createServerSocket(port, backlog, ifAddress); initServerSocket(socket); return socket; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public Socket acceptSocket(ServerSocket socket) throws IOException { SSLSocket asock = null; try { asock = (SSLSocket)socket.accept(); } catch (SSLException e){ throw new SocketException("SSL handshake error" + e.toString()); } return asock; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public void handshake(Socket sock) throws IOException { // We do getSession instead of startHandshake() so we can call this multiple times SSLSession session = ((SSLSocket)sock).getSession(); if (session.getCipherSuite().equals("SSL_NULL_WITH_NULL_NULL")) throw new IOException("SSL handshake failed. Ciper suite in SSL Session is SSL_NULL_WITH_NULL_NULL"); if (!allowUnsafeLegacyRenegotiation && !RFC_5746_SUPPORTED) { // Prevent further handshakes by removing all cipher suites ((SSLSocket) sock).setEnabledCipherSuites(new String[0]); } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected KeyStore getKeystore(String type, String provider, String pass) throws IOException { String keystoreFile = endpoint.getKeystoreFile(); if (keystoreFile == null) keystoreFile = defaultKeystoreFile; return getStore(type, provider, keystoreFile, pass); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected KeyStore getTrustStore(String keystoreType, String keystoreProvider) throws IOException { KeyStore trustStore = null; String truststoreFile = endpoint.getTruststoreFile(); if(truststoreFile == null) { truststoreFile = System.getProperty("javax.net.ssl.trustStore"); } if(log.isDebugEnabled()) { log.debug("Truststore = " + truststoreFile); } String truststorePassword = endpoint.getTruststorePass(); if( truststorePassword == null) { truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword"); } if(log.isDebugEnabled()) { log.debug("TrustPass = " + truststorePassword); } String truststoreType = endpoint.getTruststoreType(); if( truststoreType == null) { truststoreType = System.getProperty("javax.net.ssl.trustStoreType"); } if(truststoreType == null) { truststoreType = keystoreType; } if(log.isDebugEnabled()) { log.debug("trustType = " + truststoreType); } String truststoreProvider = endpoint.getTruststoreProvider(); if( truststoreProvider == null) { truststoreProvider = System.getProperty("javax.net.ssl.trustStoreProvider"); } if (truststoreProvider == null) { truststoreProvider = keystoreProvider; } if(log.isDebugEnabled()) { log.debug("trustProvider = " + truststoreProvider); } if (truststoreFile != null){ try { trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, truststorePassword); } catch (IOException ioe) { Throwable cause = ioe.getCause(); if (cause instanceof UnrecoverableKeyException) { // Log a warning we had a password issue log.warn(sm.getString("jsse.invalid_truststore_password"), cause); // Re-try trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, null); } else { // Something else went wrong - re-throw throw ioe; } } } return trustStore; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
private KeyStore getStore(String type, String provider, String path, String pass) throws IOException { KeyStore ks = null; InputStream istream = null; try { if (provider == null) { ks = KeyStore.getInstance(type); } else { ks = KeyStore.getInstance(type, provider); } if(!("PKCS11".equalsIgnoreCase(type) || "".equalsIgnoreCase(path))) { File keyStoreFile = new File(path); if (!keyStoreFile.isAbsolute()) { keyStoreFile = new File(System.getProperty( Constants.CATALINA_BASE_PROP), path); } istream = new FileInputStream(keyStoreFile); } char[] storePass = null; if (pass != null && !"".equals(pass)) { storePass = pass.toCharArray(); } ks.load(istream, storePass); } catch (FileNotFoundException fnfe) { log.error(sm.getString("jsse.keystore_load_failed", type, path, fnfe.getMessage()), fnfe); throw fnfe; } catch (IOException ioe) { // May be expected when working with a trust store // Re-throw. Caller will catch and log as required throw ioe; } catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); } finally { if (istream != null) { try { istream.close(); } catch (IOException ioe) { // Do nothing } } } return ks; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
void init() throws IOException { try { String clientAuthStr = endpoint.getClientAuth(); if("true".equalsIgnoreCase(clientAuthStr) || "yes".equalsIgnoreCase(clientAuthStr)) { requireClientAuth = true; } else if("want".equalsIgnoreCase(clientAuthStr)) { wantClientAuth = true; } SSLContext context = createSSLContext(); context.init(getKeyManagers(), getTrustManagers(), null); // Configure SSL session cache SSLSessionContext sessionContext = context.getServerSessionContext(); if (sessionContext != null) { configureSessionContext(sessionContext); } // create proxy sslProxy = context.getServerSocketFactory(); // Determine which cipher suites to enable String requestedCiphers = endpoint.getCiphers(); enabledCiphers = getEnabledCiphers(requestedCiphers, sslProxy.getSupportedCipherSuites()); allowUnsafeLegacyRenegotiation = "true".equals( endpoint.getAllowUnsafeLegacyRenegotiation()); // Check the SSL config is OK checkConfig(); } catch(Exception e) { if( e instanceof IOException ) throw (IOException)e; throw new IOException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected Collection<? extends CRL> getCRLs(String crlf) throws IOException, CRLException, CertificateException { File crlFile = new File(crlf); if( !crlFile.isAbsolute() ) { crlFile = new File( System.getProperty(Constants.CATALINA_BASE_PROP), crlf); } Collection<? extends CRL> crls = null; InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlFile); crls = cf.generateCRLs(is); } catch(IOException iex) { throw iex; } catch(CRLException crle) { throw crle; } catch(CertificateException ce) { throw ce; } finally { if(is != null) { try{ is.close(); } catch(Exception ex) { // Ignore } } } return crls; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
private void checkConfig() throws IOException { // Create an unbound server socket ServerSocket socket = sslProxy.createServerSocket(); initServerSocket(socket); try { // Set the timeout to 1ms as all we care about is if it throws an // SSLException on accept. socket.setSoTimeout(1); socket.accept(); // Will never get here - no client can connect to an unbound port } catch (SSLException ssle) { // SSL configuration is invalid. Possibly cert doesn't match ciphers IOException ioe = new IOException(sm.getString( "jsse.invalid_ssl_conf", ssle.getMessage())); ioe.initCause(ssle); throw ioe; } catch (Exception e) { /* * Possible ways of getting here * socket.accept() throws a SecurityException * socket.setSoTimeout() throws a SocketException * socket.accept() throws some other exception (after a JDK change) * In these cases the test won't work so carry on - essentially * the behaviour before this patch * socket.accept() throws a SocketTimeoutException * In this case all is well so carry on */ } finally { // Should be open here but just in case if (!socket.isClosed()) { socket.close(); } } }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
protected Selector getSharedSelector() throws IOException { if (SHARED && SHARED_SELECTOR == null) { synchronized ( NioSelectorPool.class ) { if ( SHARED_SELECTOR == null ) { synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 SHARED_SELECTOR = Selector.open(); } log.info("Using a shared selector for servlet write/read"); } }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public Selector get() throws IOException{ if ( SHARED ) { return getSharedSelector(); } if ( (!enabled) || active.incrementAndGet() >= maxSelectors ) { if ( enabled ) active.decrementAndGet(); return null; } Selector s = null; try { s = selectors.size()>0?selectors.poll():null; if (s == null) { synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 s = Selector.open(); } } else spare.decrementAndGet(); }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public void put(Selector s) throws IOException { if ( SHARED ) return; if ( enabled ) active.decrementAndGet(); if ( enabled && (maxSpareSelectors==-1 || spare.get() < Math.min(maxSpareSelectors,maxSelectors)) ) { spare.incrementAndGet(); selectors.offer(s); } else s.close(); }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public void close() throws IOException { enabled = false; Selector s; while ( (s = selectors.poll()) != null ) s.close(); spare.set(0); active.set(0); if (blockingSelector!=null) { blockingSelector.close(); } if ( SHARED && getSharedSelector()!=null ) { getSharedSelector().close(); SHARED_SELECTOR = null; } }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public void open() throws IOException { enabled = true; getSharedSelector(); if (SHARED) { blockingSelector = new NioBlockingSelector(); blockingSelector.open(getSharedSelector()); } }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int write(ByteBuffer buf, NioChannel socket, Selector selector, long writeTimeout) throws IOException { return write(buf,socket,selector,writeTimeout,true); }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int write(ByteBuffer buf, NioChannel socket, Selector selector, long writeTimeout, boolean block) throws IOException { if ( SHARED && block ) { return blockingSelector.write(buf,socket,writeTimeout); } SelectionKey key = null; int written = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) && buf.hasRemaining() ) { int cnt = 0; if ( keycount > 0 ) { //only write if we were registered for a write cnt = socket.write(buf); //write the data if (cnt == -1) throw new EOFException(); written += cnt; if (cnt > 0) { time = System.currentTimeMillis(); //reset our timeout timer continue; //we successfully wrote, try again without a selector } if (cnt==0 && (!block)) break; //don't block } if ( selector != null ) { //register OP_WRITE to the selector if (key==null) key = socket.getIOChannel().register(selector, SelectionKey.OP_WRITE); else key.interestOps(SelectionKey.OP_WRITE); keycount = selector.select(writeTimeout); } if (writeTimeout > 0 && (selector == null || keycount == 0) ) timedout = (System.currentTimeMillis()-time)>=writeTimeout; }//while if ( timedout ) throw new SocketTimeoutException(); } finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } } return written; }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int read(ByteBuffer buf, NioChannel socket, Selector selector, long readTimeout) throws IOException { return read(buf,socket,selector,readTimeout,true); }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int read(ByteBuffer buf, NioChannel socket, Selector selector, long readTimeout, boolean block) throws IOException { if ( SHARED && block ) { return blockingSelector.read(buf,socket,readTimeout); } SelectionKey key = null; int read = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) ) { int cnt = 0; if ( keycount > 0 ) { //only read if we were registered for a read cnt = socket.read(buf); if (cnt == -1) throw new EOFException(); read += cnt; if (cnt > 0) continue; //read some more if (cnt==0 && (read>0 || (!block) ) ) break; //we are done reading } if ( selector != null ) {//perform a blocking read //register OP_WRITE to the selector if (key==null) key = socket.getIOChannel().register(selector, SelectionKey.OP_READ); else key.interestOps(SelectionKey.OP_READ); keycount = selector.select(readTimeout); } if (readTimeout > 0 && (selector == null || keycount == 0) ) timedout = (System.currentTimeMillis()-time)>=readTimeout; }//while if ( timedout ) throw new SocketTimeoutException(); } finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } } return read; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
public char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); tokenBegin = bufpos; return c; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
public char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; return buffer[bufpos]; } if (++bufpos >= maxNextCharInd) FillBuff(); char c = buffer[bufpos]; UpdateLineColumn(c); return c; }
// in java/org/apache/tomcat/util/http/Parameters.java
private void urlDecode(ByteChunk bc) throws IOException { if( urlDec==null ) { urlDec=new UDecoder(); } urlDec.convert(bc, true); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public byte readByte() throws IOException { // Buffer depleted ? if (head == tail) { head = 0; // Refill. tail = input.read(buffer, head, bufSize); if (tail == -1) { // No more data available. throw new IOException("No more data is available"); } if (notifier != null) { notifier.noteBytesRead(tail); } } return buffer[head++]; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public int readBodyData(OutputStream output) throws MalformedStreamException, IOException { final InputStream istream = newInputStream(); return (int) Streams.copy(istream, output, false); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public int discardBodyData() throws MalformedStreamException, IOException { return readBodyData(null); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public boolean skipPreamble() throws IOException { // First delimiter may be not preceeded with a CRLF. System.arraycopy(boundary, 2, boundary, 0, boundary.length - 2); boundaryLength = boundary.length - 2; try { // Discard all data up to the delimiter. discardBodyData(); // Read boundary - if succeeded, the stream contains an // encapsulation. return readBoundary(); } catch (MalformedStreamException e) { return false; } finally { // Restore delimiter. System.arraycopy(boundary, 0, boundary, 2, boundary.length - 2); boundaryLength = boundary.length; boundary[0] = CR; boundary[1] = LF; } }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public int available() throws IOException { if (pos == -1) { return tail - head - pad; } return pos - head; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public int read() throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (available() == 0) { if (makeAvailable() == 0) { return -1; } } ++total; int b = buffer[head++]; if (b >= 0) { return b; } return b + BYTE_POSITIVE_OFFSET; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public int read(byte[] b, int off, int len) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (len == 0) { return 0; } int res = available(); if (res == 0) { res = makeAvailable(); if (res == 0) { return -1; } } res = Math.min(res, len); System.arraycopy(buffer, head, b, off, res); head += res; total += res; return res; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public void close() throws IOException { close(false); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public void close(boolean pCloseUnderlying) throws IOException { if (closed) { return; } if (pCloseUnderlying) { closed = true; input.close(); } else { for (;;) { int av = available(); if (av == 0) { av = makeAvailable(); if (av == 0) { break; } } skip(av); } } closed = true; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public long skip(long bytes) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } int av = available(); if (av == 0) { av = makeAvailable(); if (av == 0) { return 0; } } long res = Math.min(av, bytes); head += res; return res; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
private int makeAvailable() throws IOException { if (pos != -1) { return 0; } // Move the data to the beginning of the buffer. total += tail - head - pad; System.arraycopy(buffer, tail - pad, buffer, 0, pad); // Refill buffer with new data. head = 0; tail = pad; for (;;) { int bytesRead = input.read(buffer, tail, bufSize - tail); if (bytesRead == -1) { // The last pad amount is left in the buffer. // Boundary can't be in there so signal an error // condition. final String msg = "Stream ended unexpectedly"; throw new MalformedStreamException(msg); } if (notifier != null) { notifier.noteBytesRead(bytesRead); } tail += bytesRead; findSeparator(); int av = available(); if (av > 0 || pos != -1) { return av; } } }
// in java/org/apache/tomcat/util/http/fileupload/IOUtils.java
public static int copy(InputStream input, OutputStream output) throws IOException { long count = copyLarge(input, output); if (count > Integer.MAX_VALUE) { return -1; } return (int) count; }
// in java/org/apache/tomcat/util/http/fileupload/IOUtils.java
public static long copyLarge(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; long count = 0; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
Override public InputStream getInputStream() throws IOException { if (!isInMemory()) { return new FileInputStream(dfos.getFile()); } if (cachedContent == null) { cachedContent = dfos.getData(); } return new ByteArrayInputStream(cachedContent); }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
Override public OutputStream getOutputStream() throws IOException { if (dfos == null) { File outputFile = getTempFile(); dfos = new DeferredFileOutputStream(sizeThreshold, outputFile); } return dfos; }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
private void writeObject(ObjectOutputStream out) throws IOException { // Read the data if (dfos.isInMemory()) { cachedContent = get(); } else { cachedContent = null; dfosFile = dfos.getFile(); } // write out values out.defaultWriteObject(); }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // read values in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; }
// in java/org/apache/tomcat/util/http/fileupload/servlet/ServletRequestContext.java
Override public InputStream getInputStream() throws IOException { return request.getInputStream(); }
// in java/org/apache/tomcat/util/http/fileupload/servlet/ServletFileUpload.java
public FileItemIterator getItemIterator(HttpServletRequest request) throws FileUploadException, IOException { return super.getItemIterator(new ServletRequestContext(request)); }
// in java/org/apache/tomcat/util/http/fileupload/DeferredFileOutputStream.java
Override protected OutputStream getStream() throws IOException { return currentOutputStream; }
// in java/org/apache/tomcat/util/http/fileupload/DeferredFileOutputStream.java
Override protected void thresholdReached() throws IOException { if (prefix != null) { outputFile = File.createTempFile(prefix, suffix, directory); } FileOutputStream fos = new FileOutputStream(outputFile); memoryOutputStream.writeTo(fos); currentOutputStream = fos; memoryOutputStream = null; }
// in java/org/apache/tomcat/util/http/fileupload/DeferredFileOutputStream.java
Override public void close() throws IOException { super.close(); closed = true; }
// in java/org/apache/tomcat/util/http/fileupload/DeferredFileOutputStream.java
public void writeTo(OutputStream out) throws IOException { // we may only need to check if this is closed if we are working with a file // but we should force the habit of closing wether we are working with // a file or memory. if (!closed) { throw new IOException("Stream not closed"); } if(isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
public FileItemIterator getItemIterator(RequestContext ctx) throws FileUploadException, IOException { return new FileItemIteratorImpl(ctx); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override protected void raiseError(long pSizeMax, long pCount) throws IOException { itemStream.close(true); FileSizeLimitExceededException e = new FileSizeLimitExceededException( "The field " + fieldName + " exceeds its maximum permitted " + " size of " + pSizeMax + " bytes.", pCount, pSizeMax); e.setFieldName(fieldName); e.setFileName(name); throw new FileUploadIOException(e); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public InputStream openStream() throws IOException { if (opened) { throw new IllegalStateException( "The stream was already opened."); } if (((Closeable) stream).isClosed()) { throw new FileItemStream.ItemSkippedException(); } return stream; }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
void close() throws IOException { stream.close(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override protected void raiseError(long pSizeMax, long pCount) throws IOException { FileUploadException ex = new SizeLimitExceededException( "the request was rejected because" + " its size (" + pCount + ") exceeds the configured maximum" + " (" + pSizeMax + ")", pCount, pSizeMax); throw new FileUploadIOException(ex); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
private boolean findNextItem() throws IOException { if (eof) { return false; } if (currentItem != null) { currentItem.close(); currentItem = null; } for (;;) { boolean nextPart; if (skipPreamble) { nextPart = multi.skipPreamble(); } else { nextPart = multi.readBoundary(); } if (!nextPart) { if (currentFieldName == null) { // Outer multipart terminated -> No more data eof = true; return false; } // Inner multipart terminated -> Return to parsing the outer multi.setBoundary(boundary); currentFieldName = null; continue; } FileItemHeaders headers = getParsedHeaders(multi.readHeaders()); if (currentFieldName == null) { // We're parsing the outer multipart String fieldName = getFieldName(headers); if (fieldName != null) { String subContentType = headers.getHeader(CONTENT_TYPE); if (subContentType != null && subContentType.toLowerCase(Locale.ENGLISH) .startsWith(MULTIPART_MIXED)) { currentFieldName = fieldName; // Multiple files associated with this field name byte[] subBoundary = getBoundary(subContentType); multi.setBoundary(subBoundary); skipPreamble = true; continue; } String fileName = getFileName(headers); currentItem = new FileItemStreamImpl(fileName, fieldName, headers.getHeader(CONTENT_TYPE), fileName == null, getContentLength(headers)); currentItem.setHeaders(headers); notifier.noteItem(); itemValid = true; return true; } } else { String fileName = getFileName(headers); if (fileName != null) { currentItem = new FileItemStreamImpl(fileName, currentFieldName, headers.getHeader(CONTENT_TYPE), false, getContentLength(headers)); currentItem.setHeaders(headers); notifier.noteItem(); itemValid = true; return true; } } multi.discardBodyData(); } }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public boolean hasNext() throws FileUploadException, IOException { if (eof) { return false; } if (itemValid) { return true; } return findNextItem(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public FileItemStream next() throws FileUploadException, IOException { if (eof || (!itemValid && !hasNext())) { throw new NoSuchElementException(); } itemValid = false; return currentItem; }
// in java/org/apache/tomcat/util/http/fileupload/FileDeleteStrategy.java
public void delete(File fileToDelete) throws IOException { if (fileToDelete.exists() && doDelete(fileToDelete) == false) { throw new IOException("Deletion failed: " + fileToDelete); } }
// in java/org/apache/tomcat/util/http/fileupload/FileDeleteStrategy.java
protected boolean doDelete(File fileToDelete) throws IOException { return fileToDelete.delete(); }
// in java/org/apache/tomcat/util/http/fileupload/FileDeleteStrategy.java
Override protected boolean doDelete(File fileToDelete) throws IOException { FileUtils.forceDelete(fileToDelete); return true; }
// in java/org/apache/tomcat/util/http/fileupload/ByteArrayOutputStream.java
public synchronized int write(InputStream in) throws IOException { int readCount = 0; int inBufferPos = count - filledBufferSum; int n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos); while (n != -1) { readCount += n; inBufferPos += n; count += n; if (inBufferPos == currentBuffer.length) { needNewBuffer(currentBuffer.length); inBufferPos = 0; } n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos); } return readCount; }
// in java/org/apache/tomcat/util/http/fileupload/ByteArrayOutputStream.java
Override public void close() throws IOException { //nop }
// in java/org/apache/tomcat/util/http/fileupload/ByteArrayOutputStream.java
public synchronized void writeTo(OutputStream out) throws IOException { int remaining = count; for (int i = 0; i < buffers.size(); i++) { byte[] buf = getBuffer(i); int c = Math.min(buf.length, remaining); out.write(buf, 0, c); remaining -= c; if (remaining == 0) { break; } } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void deleteDirectory(File directory) throws IOException { if (!directory.exists()) { return; } cleanDirectory(directory); if (!directory.delete()) { String message = "Unable to delete directory " + directory + "."; throw new IOException(message); } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void cleanDirectory(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (int i = 0; i < files.length; i++) { File file = files[i]; try { forceDelete(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void forceDelete(File file) throws IOException { if (file.isDirectory()) { deleteDirectory(file); } else { boolean filePresent = file.exists(); if (!file.delete()) { if (!filePresent){ throw new FileNotFoundException("File does not exist: " + file); } String message = "Unable to delete file: " + file; throw new IOException(message); } } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void forceDeleteOnExit(File file) throws IOException { if (file.isDirectory()) { deleteDirectoryOnExit(file); } else { file.deleteOnExit(); } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
private static void deleteDirectoryOnExit(File directory) throws IOException { if (!directory.exists()) { return; } cleanDirectoryOnExit(directory); directory.deleteOnExit(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
private static void cleanDirectoryOnExit(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (int i = 0; i < files.length; i++) { File file = files[i]; try { forceDeleteOnExit(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } }
// in java/org/apache/tomcat/util/http/fileupload/util/Streams.java
public static long copy(InputStream pInputStream, OutputStream pOutputStream, boolean pClose) throws IOException { return copy(pInputStream, pOutputStream, pClose, new byte[DEFAULT_BUFFER_SIZE]); }
// in java/org/apache/tomcat/util/http/fileupload/util/Streams.java
public static long copy(InputStream pIn, OutputStream pOut, boolean pClose, byte[] pBuffer) throws IOException { OutputStream out = pOut; InputStream in = pIn; try { long total = 0; for (;;) { int res = in.read(pBuffer); if (res == -1) { break; } if (res > 0) { total += res; if (out != null) { out.write(pBuffer, 0, res); } } } if (out != null) { if (pClose) { out.close(); } else { out.flush(); } out = null; } in.close(); in = null; return total; } finally { if (in != null) { try { in.close(); } catch (IOException ioe) { /* Ignore me */ } } if (pClose && out != null) { try { out.close(); } catch (IOException ioe) { /* Ignore me */ } } } }
// in java/org/apache/tomcat/util/http/fileupload/util/Streams.java
public static String asString(InputStream pStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); copy(pStream, baos, true); return baos.toString(); }
// in java/org/apache/tomcat/util/http/fileupload/util/Streams.java
public static String asString(InputStream pStream, String pEncoding) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); copy(pStream, baos, true); return baos.toString(pEncoding); }
// in java/org/apache/tomcat/util/http/fileupload/util/LimitedInputStream.java
private void checkLimit() throws IOException { if (count > sizeMax) { raiseError(sizeMax, count); } }
// in java/org/apache/tomcat/util/http/fileupload/util/LimitedInputStream.java
Override public int read() throws IOException { int res = super.read(); if (res != -1) { count++; checkLimit(); } return res; }
// in java/org/apache/tomcat/util/http/fileupload/util/LimitedInputStream.java
Override public int read(byte[] b, int off, int len) throws IOException { int res = super.read(b, off, len); if (res > 0) { count += res; checkLimit(); } return res; }
// in java/org/apache/tomcat/util/http/fileupload/util/LimitedInputStream.java
Override public boolean isClosed() throws IOException { return closed; }
// in java/org/apache/tomcat/util/http/fileupload/util/LimitedInputStream.java
Override public void close() throws IOException { closed = true; super.close(); }
// in java/org/apache/tomcat/util/http/fileupload/ThresholdingOutputStream.java
Override public void write(int b) throws IOException { checkThreshold(1); getStream().write(b); written++; }
// in java/org/apache/tomcat/util/http/fileupload/ThresholdingOutputStream.java
Override public void write(byte b[]) throws IOException { checkThreshold(b.length); getStream().write(b); written += b.length; }
// in java/org/apache/tomcat/util/http/fileupload/ThresholdingOutputStream.java
Override public void write(byte b[], int off, int len) throws IOException { checkThreshold(len); getStream().write(b, off, len); written += len; }
// in java/org/apache/tomcat/util/http/fileupload/ThresholdingOutputStream.java
Override public void flush() throws IOException { getStream().flush(); }
// in java/org/apache/tomcat/util/http/fileupload/ThresholdingOutputStream.java
Override public void close() throws IOException { try { flush(); } catch (IOException ignored) { // ignore } getStream().close(); }
// in java/org/apache/tomcat/util/http/fileupload/ThresholdingOutputStream.java
protected void checkThreshold(int count) throws IOException { if (!thresholdExceeded && (written + count > threshold)) { thresholdExceeded = true; thresholdReached(); } }
// in java/org/apache/tomcat/util/buf/MessageBytes.java
public void duplicate( MessageBytes src ) throws IOException { switch( src.getType() ) { case MessageBytes.T_BYTES: type=T_BYTES; ByteChunk bc=src.getByteChunk(); byteC.allocate( 2 * bc.getLength(), -1 ); byteC.append( bc ); break; case MessageBytes.T_CHARS: type=T_CHARS; CharChunk cc=src.getCharChunk(); charC.allocate( 2 * cc.getLength(), -1 ); charC.append( cc ); break; case MessageBytes.T_STR: type=T_STR; String sc=src.getString(); this.setString( sc ); break; } }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
public void convert( ByteChunk bb, CharChunk cb, int limit) throws IOException { iis.setByteChunk( bb ); try { // read from the reader int bbLengthBeforeRead = 0; while( limit > 0 ) { int size = limit < BUFFER_SIZE ? limit : BUFFER_SIZE; bbLengthBeforeRead = bb.getLength(); int cnt=conv.read( result, 0, size ); if( cnt <= 0 ) { // End of stream ! - we may be in a bad state if(log.isDebugEnabled()) { log.debug("B2CConverter: EOF"); } return; } if(log.isDebugEnabled()) { log.debug("B2CConverter: Converted: " + new String(result, 0, cnt)); } cb.append( result, 0, cnt ); limit = limit - (bbLengthBeforeRead - bb.getLength()); } } catch( IOException ex) { if(log.isDebugEnabled()) { log.debug("B2CConverter: Reseting the converter " + ex.toString()); } reset(); throw ex; } }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
public void reset() throws IOException { // destroy the reader/iis iis=new IntermediateInputStream(); conv = new ReadConvertor(iis, getCharset(encoding)); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
Override public final void close() throws IOException { // NOTHING // Calling super.close() would reset out and cb. }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
Override public final int read(char cbuf[], int off, int len) throws IOException { // will do the conversion and call write on the output stream return super.read( cbuf, off, len ); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
Override public final void close() throws IOException { // shouldn't be called - we filter it out in writer throw new IOException("close() called - shouldn't happen "); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
Override public final int read(byte cbuf[], int off, int len) throws IOException { return bc.substract(cbuf, off, len); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
Override public final int read() throws IOException { return bc.substract(); }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public void append( char b ) throws IOException { makeSpace( 1 ); // couldn't make space if( limit >0 && end >= limit ) { flushBuffer(); } buff[end++]=b; }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public void append( CharChunk src ) throws IOException { append( src.getBuffer(), src.getOffset(), src.getLength()); }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public void append( char src[], int off, int len ) throws IOException { // will grow, up to limit makeSpace( len ); // if we don't have limit: makeSpace can grow as it wants if( limit < 0 ) { // assert: makeSpace made enough space System.arraycopy( src, off, buff, end, len ); end+=len; return; } // Optimize on a common case. // If the source is going to fill up all the space in buffer, may // as well write it directly to the output, and avoid an extra copy if ( optimizedWrite && len == limit && end == start && out != null ) { out.realWriteChars( src, off, len ); return; } // if we have limit and we're below if( len <= limit - end ) { // makeSpace will grow the buffer to the limit, // so we have space System.arraycopy( src, off, buff, end, len ); end+=len; return; } // need more space than we can afford, need to flush // buffer // the buffer is already at ( or bigger than ) limit // Optimization: // If len-avail < length ( i.e. after we fill the buffer with // what we can, the remaining will fit in the buffer ) we'll just // copy the first part, flush, then copy the second part - 1 write // and still have some space for more. We'll still have 2 writes, but // we write more on the first. if( len + end < 2 * limit ) { /* If the request length exceeds the size of the output buffer, flush the output buffer and then write the data directly. We can't avoid 2 writes, but we can write more on the second */ int avail=limit-end; System.arraycopy(src, off, buff, end, avail); end += avail; flushBuffer(); System.arraycopy(src, off+avail, buff, end, len - avail); end+= len - avail; } else { // len > buf.length + avail // long write - flush the buffer and write the rest // directly from source flushBuffer(); out.realWriteChars( src, off, len ); } }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public void append(String s) throws IOException { append(s, 0, s.length()); }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public void append(String s, int off, int len) throws IOException { if (s==null) { return; } // will grow, up to limit makeSpace( len ); // if we don't have limit: makeSpace can grow as it wants if( limit < 0 ) { // assert: makeSpace made enough space s.getChars(off, off+len, buff, end ); end+=len; return; } int sOff = off; int sEnd = off + len; while (sOff < sEnd) { int d = min(limit - end, sEnd - sOff); s.getChars( sOff, sOff+d, buff, end); sOff += d; end += d; if (end >= limit) { flushBuffer(); } } }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public int substract() throws IOException { if ((end - start) == 0) { if (in == null) { return -1; } int n = in.realReadChars(buff, end, buff.length - end); if (n < 0) { return -1; } } return (buff[start++]); }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public int substract( char src[], int off, int len ) throws IOException { if ((end - start) == 0) { if (in == null) { return -1; } int n = in.realReadChars( buff, end, buff.length - end); if (n < 0) { return -1; } } int n = len; if (len > getLength()) { n = getLength(); } System.arraycopy(buff, start, src, off, n); start += n; return n; }
// in java/org/apache/tomcat/util/buf/CharChunk.java
public void flushBuffer() throws IOException { //assert out!=null if( out==null ) { throw new IOException( "Buffer overflow, no sink " + limit + " " + buff.length ); } out.realWriteChars( buff, start, end - start ); end=start; }
// in java/org/apache/tomcat/util/buf/UDecoder.java
public void convert( ByteChunk mb, boolean query ) throws IOException { int start=mb.getOffset(); byte buff[]=mb.getBytes(); int end=mb.getEnd(); int idx= ByteChunk.findByte( buff, start, end, (byte) '%' ); int idx2=-1; if( query ) { idx2= ByteChunk.findByte( buff, start, (idx >= 0 ? idx : end), (byte) '+' ); } if( idx<0 && idx2<0 ) { return; } // idx will be the smallest positive index ( first % or + ) if( (idx2 >= 0 && idx2 < idx) || idx < 0 ) { idx=idx2; } final boolean noSlash = !(ALLOW_ENCODED_SLASH || query); for( int j=idx; j<end; j++, idx++ ) { if( buff[ j ] == '+' && query) { buff[idx]= (byte)' ' ; } else if( buff[ j ] != '%' ) { buff[idx]= buff[j]; } else { // read next 2 digits if( j+2 >= end ) { throw EXCEPTION_EOF; } byte b1= buff[j+1]; byte b2=buff[j+2]; if( !isHexDigit( b1 ) || ! isHexDigit(b2 )) { throw EXCEPTION_NOT_HEX_DIGIT; } j+=2; int res=x2c( b1, b2 ); if (noSlash && (res == '/')) { throw EXCEPTION_SLASH; } buff[idx]=(byte)res; } } mb.setEnd( idx ); return; }
// in java/org/apache/tomcat/util/buf/UDecoder.java
public void convert( CharChunk mb, boolean query ) throws IOException { // log( "Converting a char chunk "); int start=mb.getOffset(); char buff[]=mb.getBuffer(); int cend=mb.getEnd(); int idx= CharChunk.indexOf( buff, start, cend, '%' ); int idx2=-1; if( query ) { idx2= CharChunk.indexOf( buff, start, (idx >= 0 ? idx : cend), '+' ); } if( idx<0 && idx2<0 ) { return; } // idx will be the smallest positive index ( first % or + ) if( (idx2 >= 0 && idx2 < idx) || idx < 0 ) { idx=idx2; } final boolean noSlash = !(ALLOW_ENCODED_SLASH || query); for( int j=idx; j<cend; j++, idx++ ) { if( buff[ j ] == '+' && query ) { buff[idx]=( ' ' ); } else if( buff[ j ] != '%' ) { buff[idx]=buff[j]; } else { // read next 2 digits if( j+2 >= cend ) { // invalid throw EXCEPTION_EOF; } char b1= buff[j+1]; char b2=buff[j+2]; if( !isHexDigit( b1 ) || ! isHexDigit(b2 )) { throw EXCEPTION_NOT_HEX_DIGIT; } j+=2; int res=x2c( b1, b2 ); if (noSlash && (res == '/')) { throw EXCEPTION_SLASH; } buff[idx]=(char)res; } } mb.setEnd( idx ); }
// in java/org/apache/tomcat/util/buf/UDecoder.java
public void convert(MessageBytes mb, boolean query) throws IOException { switch (mb.getType()) { case MessageBytes.T_STR: String strValue=mb.toString(); if( strValue==null ) { return; } try { mb.setString( convert( strValue, query )); } catch (RuntimeException ex) { throw new DecodeException(ex.getMessage()); } break; case MessageBytes.T_CHARS: CharChunk charC=mb.getCharChunk(); convert( charC, query ); break; case MessageBytes.T_BYTES: ByteChunk bytesC=mb.getByteChunk(); convert( bytesC, query ); break; } }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
private void init() throws IOException { ios = new IntermediateOutputStream(bb); conv = new WriteConvertor(ios, B2CConverter.getCharset(encoding)); writer = new BufferedWriter(conv); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
public final void convert(char c[], int off, int len) throws IOException { writer.write(c, off, len); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
public final void convert(String s, int off, int len) throws IOException { writer.write(s, off, len); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
public final void convert(String s) throws IOException { writer.write(s); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
public final void convert(char c) throws IOException { writer.write(c); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
public final void flushBuffer() throws IOException { writer.flush(); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void close() throws IOException { // NOTHING // Calling super.close() would reset out and cb. }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void flush() throws IOException { // Will flushBuffer and out() // flushBuffer put any remaining chars in the byte[] super.flush(); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void write(char cbuf[], int off, int len) throws IOException { // Will do the conversion and call write on the output stream super.write( cbuf, off, len ); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void close() throws IOException { // shouldn't be called - we filter it out in writer throw new IOException("close() called - shouldn't happen "); }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void flush() throws IOException { // nothing - write will go directly to the buffer, // we don't keep any state }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void write(byte cbuf[], int off, int len) throws IOException { // will do the conversion and call write on the output stream if( enabled ) { tbuff.append( cbuf, off, len ); } }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
Override public final void write(int i) throws IOException { throw new IOException("write( int ) called - shouldn't happen "); }
// in java/org/apache/tomcat/util/buf/UEncoder.java
public void urlEncode( Writer buf, String s ) throws IOException { if( c2b==null ) { bb=new ByteChunk(16); // small enough. c2b=new C2BConverter( bb, ENCODING ); } for (int i = 0; i < s.length(); i++) { int c = s.charAt(i); if( safeChars.get( c ) ) { if(log.isDebugEnabled()) { log.debug("Encoder: Safe: " + (char)c); } buf.write((char)c); } else { if(log.isDebugEnabled()) { log.debug("Encoder: Unsafe: " + (char)c); } c2b.convert( (char)c ); // "surrogate" - UTF is _not_ 16 bit, but 21 !!!! // ( while UCS is 31 ). Amazing... if (c >= 0xD800 && c <= 0xDBFF) { if ( (i+1) < s.length()) { int d = s.charAt(i+1); if (d >= 0xDC00 && d <= 0xDFFF) { if(log.isDebugEnabled()) { log.debug("Encoder: Unsafe: " + c); } c2b.convert( (char)d); i++; } } } c2b.flushBuffer(); urlEncode( buf, bb.getBuffer(), bb.getOffset(), bb.getLength() ); bb.recycle(); } } }
// in java/org/apache/tomcat/util/buf/UEncoder.java
public void urlEncode( Writer buf, byte bytes[], int off, int len) throws IOException { for( int j=off; j< len; j++ ) { buf.write( '%' ); char ch = Character.forDigit((bytes[j] >> 4) & 0xF, 16); if(log.isDebugEnabled()) { log.debug("Encoder: Encode: " + ch); } buf.write(ch); ch = Character.forDigit(bytes[j] & 0xF, 16); if(log.isDebugEnabled()) { log.debug("Encoder: Encode: " + ch); } buf.write(ch); } }
// in java/org/apache/tomcat/util/buf/ByteChunk.java
public void append( byte b ) throws IOException { makeSpace( 1 ); // couldn't make space if( limit >0 && end >= limit ) { flushBuffer(); } buff[end++]=b; }
// in java/org/apache/tomcat/util/buf/ByteChunk.java
public void append( ByteChunk src ) throws IOException { append( src.getBytes(), src.getStart(), src.getLength()); }
// in java/org/apache/tomcat/util/buf/ByteChunk.java
public void append( byte src[], int off, int len ) throws IOException { // will grow, up to limit makeSpace( len ); // if we don't have limit: makeSpace can grow as it wants if( limit < 0 ) { // assert: makeSpace made enough space System.arraycopy( src, off, buff, end, len ); end+=len; return; } // Optimize on a common case. // If the buffer is empty and the source is going to fill up all the // space in buffer, may as well write it directly to the output, // and avoid an extra copy if ( len == limit && end == start && out != null ) { out.realWriteBytes( src, off, len ); return; } // if we have limit and we're below if( len <= limit - end ) { // makeSpace will grow the buffer to the limit, // so we have space System.arraycopy( src, off, buff, end, len ); end+=len; return; } // need more space than we can afford, need to flush // buffer // the buffer is already at ( or bigger than ) limit // We chunk the data into slices fitting in the buffer limit, although // if the data is written directly if it doesn't fit int avail=limit-end; System.arraycopy(src, off, buff, end, avail); end += avail; flushBuffer(); int remain = len - avail; while (remain > (limit - end)) { out.realWriteBytes( src, (off + len) - remain, limit - end ); remain = remain - (limit - end); } System.arraycopy(src, (off + len) - remain, buff, end, remain); end += remain; }
// in java/org/apache/tomcat/util/buf/ByteChunk.java
public int substract() throws IOException { if ((end - start) == 0) { if (in == null) { return -1; } int n = in.realReadBytes( buff, 0, buff.length ); if (n < 0) { return -1; } } return (buff[start++] & 0xFF); }
// in java/org/apache/tomcat/util/buf/ByteChunk.java
public int substract( byte src[], int off, int len ) throws IOException { if ((end - start) == 0) { if (in == null) { return -1; } int n = in.realReadBytes( buff, 0, buff.length ); if (n < 0) { return -1; } } int n = len; if (len > getLength()) { n = getLength(); } System.arraycopy(buff, start, src, off, n); start += n; return n; }
// in java/org/apache/tomcat/util/buf/ByteChunk.java
public void flushBuffer() throws IOException { //assert out!=null if( out==null ) { throw new IOException( "Buffer overflow, no sink " + limit + " " + buff.length ); } out.realWriteBytes( buff, start, end-start ); end=start; }
// in java/org/apache/tomcat/util/scan/NonClosingJarInputStream.java
Override public void close() throws IOException { // Make this a NO-OP so that further entries can be read from the stream }
// in java/org/apache/tomcat/util/scan/NonClosingJarInputStream.java
public void reallyClose() throws IOException { super.close(); }
// in java/org/apache/tomcat/util/scan/JarFactory.java
public static Jar newInstance(URL url) throws IOException { String jarUrl = url.toString(); if (jarUrl.startsWith("jar:file:")) { return new FileUrlJar(url); } else { return new UrlJar(url); } }
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
private void process(JarScannerCallback callback, URL url) throws IOException { if (log.isTraceEnabled()) { log.trace(sm.getString("jarScan.jarUrlStart", url)); } URLConnection conn = url.openConnection(); if (conn instanceof JarURLConnection) { callback.scan((JarURLConnection) conn); } else { String urlStr = url.toString(); if (urlStr.startsWith("file:") || urlStr.startsWith("jndi:")) { if (urlStr.endsWith(Constants.JAR_EXT)) { URL jarURL = new URL("jar:" + urlStr + "!/"); callback.scan((JarURLConnection) jarURL.openConnection()); } else { File f; try { f = new File(url.toURI()); if (f.isFile() && scanAllFiles) { // Treat this file as a JAR URL jarURL = new URL("jar:" + urlStr + "!/"); callback.scan((JarURLConnection) jarURL.openConnection()); } else if (f.isDirectory() && scanAllDirectories) { File metainf = new File(f.getAbsoluteFile() + File.separator + "META-INF"); if (metainf.isDirectory()) { callback.scan(f); } } } catch (URISyntaxException e) { // Wrap the exception and re-throw IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } } } } }
// in java/org/apache/tomcat/util/scan/UrlJar.java
Override public boolean entryExists(String name) throws IOException { JarEntry entry = jarInputStream.getNextJarEntry(); while (entry != null) { if (name.equals(entry.getName())) { break; } entry = jarInputStream.getNextJarEntry(); } return entry != null; }
// in java/org/apache/tomcat/util/scan/UrlJar.java
Override public InputStream getInputStream(String name) throws IOException { JarEntry entry = jarInputStream.getNextJarEntry(); while (entry != null) { if (name.equals(entry.getName())) { break; } entry = jarInputStream.getNextJarEntry(); } if (entry == null) { return null; } else { return jarInputStream; } }
// in java/org/apache/tomcat/util/scan/UrlJar.java
private NonClosingJarInputStream createJarInputStream() throws IOException { JarURLConnection jarConn = (JarURLConnection) url.openConnection(); URL resourceURL = jarConn.getJarFileURL(); URLConnection resourceConn = resourceURL.openConnection(); resourceConn.setUseCaches(false); return new NonClosingJarInputStream(resourceConn.getInputStream()); }
// in java/org/apache/tomcat/util/scan/UrlJar.java
Override public InputStream getEntryInputStream() throws IOException { return jarInputStream; }
// in java/org/apache/tomcat/util/scan/UrlJar.java
Override public void reset() throws IOException { close(); jarInputStream = createJarInputStream(); }
// in java/org/apache/tomcat/util/scan/FileUrlJar.java
Override public InputStream getInputStream(String name) throws IOException { ZipEntry entry = jarFile.getEntry(name); if (entry == null) { return null; } else { return jarFile.getInputStream(entry); } }
// in java/org/apache/tomcat/util/scan/FileUrlJar.java
Override public InputStream getEntryInputStream() throws IOException { if (entry == null) { return null; } else { return jarFile.getInputStream(entry); } }
// in java/org/apache/tomcat/util/scan/FileUrlJar.java
Override public void reset() throws IOException { entries = null; entry = null; }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(File file) throws IOException, SAXException { configure(); InputSource input = new InputSource(new FileInputStream(file)); input.setSystemId("file://" + file.getAbsolutePath()); getXMLReader().parse(input); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(InputSource input) throws IOException, SAXException { configure(); getXMLReader().parse(input); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(InputStream input) throws IOException, SAXException { configure(); InputSource is = new InputSource(input); getXMLReader().parse(is); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(Reader reader) throws IOException, SAXException { configure(); InputSource is = new InputSource(reader); getXMLReader().parse(is); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(String uri) throws IOException, SAXException { configure(); InputSource is = new InputSource(uri); getXMLReader().parse(is); return (root); }
// in java/org/apache/tomcat/util/log/SystemLogHandler.java
Override public void write(byte[] b) throws IOException { findStream().write(b); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassElementValue.java
Override public void dump(DataOutputStream dos) throws IOException { dos.writeByte(type); // u1 kind of value dos.writeShort(idx); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantFloat.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeFloat(bytes); }
// in java/org/apache/tomcat/util/bcel/classfile/RuntimeInvisibleAnnotations.java
Override public final void dump(DataOutputStream dos) throws IOException { super.dump(dos); writeAnnotations(dos); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantNameAndType.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeShort(name_index); file.writeShort(signature_index); }
// in java/org/apache/tomcat/util/bcel/classfile/Synthetic.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); if (length > 0) { file.write(bytes, 0, length); } }
// in java/org/apache/tomcat/util/bcel/classfile/ExceptionTable.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(number_of_exceptions); for (int i = 0; i < number_of_exceptions; i++) { file.writeShort(exception_index_table[i]); } }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
public static final String codeToString( ByteSequence bytes, ConstantPool constant_pool, boolean verbose ) throws IOException { short opcode = (short) bytes.readUnsignedByte(); int default_offset = 0, low, high, npairs; int index, vindex, constant; int[] match, jump_table; int no_pad_bytes = 0, offset; StringBuilder buf = new StringBuilder(Constants.OPCODE_NAMES[opcode]); /* Special case: Skip (0-3) padding bytes, i.e., the * following bytes are 4-byte-aligned */ if ((opcode == Constants.TABLESWITCH) || (opcode == Constants.LOOKUPSWITCH)) { int remainder = bytes.getIndex() % 4; no_pad_bytes = (remainder == 0) ? 0 : 4 - remainder; for (int i = 0; i < no_pad_bytes; i++) { byte b; if ((b = bytes.readByte()) != 0) { System.err.println("Warning: Padding byte != 0 in " + Constants.OPCODE_NAMES[opcode] + ":" + b); } } // Both cases have a field default_offset in common default_offset = bytes.readInt(); } switch (opcode) { /* Table switch has variable length arguments. */ case Constants.TABLESWITCH: low = bytes.readInt(); high = bytes.readInt(); offset = bytes.getIndex() - 12 - no_pad_bytes - 1; default_offset += offset; buf.append("\tdefault = ").append(default_offset).append(", low = ").append(low) .append(", high = ").append(high).append("("); jump_table = new int[high - low + 1]; for (int i = 0; i < jump_table.length; i++) { jump_table[i] = offset + bytes.readInt(); buf.append(jump_table[i]); if (i < jump_table.length - 1) { buf.append(", "); } } buf.append(")"); break; /* Lookup switch has variable length arguments. */ case Constants.LOOKUPSWITCH: { npairs = bytes.readInt(); offset = bytes.getIndex() - 8 - no_pad_bytes - 1; match = new int[npairs]; jump_table = new int[npairs]; default_offset += offset; buf.append("\tdefault = ").append(default_offset).append(", npairs = ").append( npairs).append(" ("); for (int i = 0; i < npairs; i++) { match[i] = bytes.readInt(); jump_table[i] = offset + bytes.readInt(); buf.append("(").append(match[i]).append(", ").append(jump_table[i]).append(")"); if (i < npairs - 1) { buf.append(", "); } } buf.append(")"); } break; /* Two address bytes + offset from start of byte stream form the * jump target */ case Constants.GOTO: case Constants.IFEQ: case Constants.IFGE: case Constants.IFGT: case Constants.IFLE: case Constants.IFLT: case Constants.JSR: case Constants.IFNE: case Constants.IFNONNULL: case Constants.IFNULL: case Constants.IF_ACMPEQ: case Constants.IF_ACMPNE: case Constants.IF_ICMPEQ: case Constants.IF_ICMPGE: case Constants.IF_ICMPGT: case Constants.IF_ICMPLE: case Constants.IF_ICMPLT: case Constants.IF_ICMPNE: buf.append("\t\t#").append((bytes.getIndex() - 1) + bytes.readShort()); break; /* 32-bit wide jumps */ case Constants.GOTO_W: case Constants.JSR_W: buf.append("\t\t#").append(((bytes.getIndex() - 1) + bytes.readInt())); break; /* Index byte references local variable (register) */ case Constants.ALOAD: case Constants.ASTORE: case Constants.DLOAD: case Constants.DSTORE: case Constants.FLOAD: case Constants.FSTORE: case Constants.ILOAD: case Constants.ISTORE: case Constants.LLOAD: case Constants.LSTORE: case Constants.RET: if (wide) { vindex = bytes.readUnsignedShort(); wide = false; // Clear flag } else { vindex = bytes.readUnsignedByte(); } buf.append("\t\t%").append(vindex); break; /* * Remember wide byte which is used to form a 16-bit address in the * following instruction. Relies on that the method is called again with * the following opcode. */ case Constants.WIDE: wide = true; buf.append("\t(wide)"); break; /* Array of basic type. */ case Constants.NEWARRAY: buf.append("\t\t<").append(Constants.TYPE_NAMES[bytes.readByte()]).append(">"); break; /* Access object/class fields. */ case Constants.GETFIELD: case Constants.GETSTATIC: case Constants.PUTFIELD: case Constants.PUTSTATIC: index = bytes.readUnsignedShort(); buf.append("\t\t").append( constant_pool.constantToString(index, Constants.CONSTANT_Fieldref)).append( (verbose ? " (" + index + ")" : "")); break; /* Operands are references to classes in constant pool */ case Constants.NEW: case Constants.CHECKCAST: buf.append("\t"); //$FALL-THROUGH$ case Constants.INSTANCEOF: index = bytes.readUnsignedShort(); buf.append("\t<").append( constant_pool.constantToString(index, Constants.CONSTANT_Class)) .append(">").append((verbose ? " (" + index + ")" : "")); break; /* Operands are references to methods in constant pool */ case Constants.INVOKESPECIAL: case Constants.INVOKESTATIC: case Constants.INVOKEVIRTUAL: index = bytes.readUnsignedShort(); buf.append("\t").append( constant_pool.constantToString(index, Constants.CONSTANT_Methodref)) .append((verbose ? " (" + index + ")" : "")); break; case Constants.INVOKEINTERFACE: index = bytes.readUnsignedShort(); int nargs = bytes.readUnsignedByte(); // historical, redundant buf.append("\t").append( constant_pool .constantToString(index, Constants.CONSTANT_InterfaceMethodref)) .append(verbose ? " (" + index + ")\t" : "").append(nargs).append("\t") .append(bytes.readUnsignedByte()); // Last byte is a reserved space break; /* Operands are references to items in constant pool */ case Constants.LDC_W: case Constants.LDC2_W: index = bytes.readUnsignedShort(); buf.append("\t\t").append( constant_pool.constantToString(index, constant_pool.getConstant(index) .getTag())).append((verbose ? " (" + index + ")" : "")); break; case Constants.LDC: index = bytes.readUnsignedByte(); buf.append("\t\t").append( constant_pool.constantToString(index, constant_pool.getConstant(index) .getTag())).append((verbose ? " (" + index + ")" : "")); break; /* Array of references. */ case Constants.ANEWARRAY: index = bytes.readUnsignedShort(); buf.append("\t\t<").append( compactClassName(constant_pool.getConstantString(index, Constants.CONSTANT_Class), false)).append(">").append( (verbose ? " (" + index + ")" : "")); break; /* Multidimensional array of references. */ case Constants.MULTIANEWARRAY: { index = bytes.readUnsignedShort(); int dimensions = bytes.readUnsignedByte(); buf.append("\t<").append( compactClassName(constant_pool.getConstantString(index, Constants.CONSTANT_Class), false)).append(">\t").append(dimensions) .append((verbose ? " (" + index + ")" : "")); } break; /* Increment local variable. */ case Constants.IINC: if (wide) { vindex = bytes.readUnsignedShort(); constant = bytes.readShort(); wide = false; } else { vindex = bytes.readUnsignedByte(); constant = bytes.readByte(); } buf.append("\t\t%").append(vindex).append("\t").append(constant); break; default: if (Constants.NO_OF_OPERANDS[opcode] > 0) { for (int i = 0; i < Constants.TYPE_OF_OPERANDS[opcode].length; i++) { buf.append("\t\t"); switch (Constants.TYPE_OF_OPERANDS[opcode][i]) { case Constants.T_BYTE: buf.append(bytes.readByte()); break; case Constants.T_SHORT: buf.append(bytes.readShort()); break; case Constants.T_INT: buf.append(bytes.readInt()); break; default: // Never reached System.err.println("Unreachable default case reached!"); System.exit(-1); } } } } return buf.toString(); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantInteger.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeInt(bytes); }
// in java/org/apache/tomcat/util/bcel/classfile/Deprecated.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); if (length > 0) { file.write(bytes, 0, length); } }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantValue.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(constantvalue_index); }
// in java/org/apache/tomcat/util/bcel/classfile/InnerClasses.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(number_of_classes); for (int i = 0; i < number_of_classes; i++) { inner_classes[i].dump(file); } }
// in java/org/apache/tomcat/util/bcel/classfile/ElementValue.java
public static ElementValue readElementValue(DataInputStream dis, ConstantPool cpool) throws IOException { byte type = dis.readByte(); switch (type) { case 'B': // byte return new SimpleElementValue(PRIMITIVE_BYTE, dis .readUnsignedShort(), cpool); case 'C': // char return new SimpleElementValue(PRIMITIVE_CHAR, dis .readUnsignedShort(), cpool); case 'D': // double return new SimpleElementValue(PRIMITIVE_DOUBLE, dis .readUnsignedShort(), cpool); case 'F': // float return new SimpleElementValue(PRIMITIVE_FLOAT, dis .readUnsignedShort(), cpool); case 'I': // int return new SimpleElementValue(PRIMITIVE_INT, dis .readUnsignedShort(), cpool); case 'J': // long return new SimpleElementValue(PRIMITIVE_LONG, dis .readUnsignedShort(), cpool); case 'S': // short return new SimpleElementValue(PRIMITIVE_SHORT, dis .readUnsignedShort(), cpool); case 'Z': // boolean return new SimpleElementValue(PRIMITIVE_BOOLEAN, dis .readUnsignedShort(), cpool); case 's': // String return new SimpleElementValue(STRING, dis.readUnsignedShort(), cpool); case 'e': // Enum constant return new EnumElementValue(ENUM_CONSTANT, dis.readUnsignedShort(), dis.readUnsignedShort(), cpool); case 'c': // Class return new ClassElementValue(CLASS, dis.readUnsignedShort(), cpool); case '@': // Annotation // TODO isRuntimeVisible return new AnnotationElementValue(ANNOTATION, AnnotationEntry.read( dis, cpool), cpool); case '[': // Array int numArrayVals = dis.readUnsignedShort(); ElementValue[] evalues = new ElementValue[numArrayVals]; for (int j = 0; j < numArrayVals; j++) { evalues[j] = ElementValue.readElementValue(dis, cpool); } return new ArrayElementValue(ARRAY, evalues, cpool); default: throw new RuntimeException( "Unexpected element value kind in annotation: " + type); } }
// in java/org/apache/tomcat/util/bcel/classfile/StackMap.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(map_length); for (int i = 0; i < map_length; i++) { map[i].dump(file); } }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantString.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeShort(string_index); }
// in java/org/apache/tomcat/util/bcel/classfile/SourceFile.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(sourcefile_index); }
// in java/org/apache/tomcat/util/bcel/classfile/Constant.java
static final Constant readConstant( DataInputStream file ) throws IOException, ClassFormatException { byte b = file.readByte(); // Read tag byte switch (b) { case Constants.CONSTANT_Class: return new ConstantClass(file); case Constants.CONSTANT_Fieldref: return new ConstantFieldref(file); case Constants.CONSTANT_Methodref: return new ConstantMethodref(file); case Constants.CONSTANT_InterfaceMethodref: return new ConstantInterfaceMethodref(file); case Constants.CONSTANT_String: return new ConstantString(file); case Constants.CONSTANT_Integer: return new ConstantInteger(file); case Constants.CONSTANT_Float: return new ConstantFloat(file); case Constants.CONSTANT_Long: return new ConstantLong(file); case Constants.CONSTANT_Double: return new ConstantDouble(file); case Constants.CONSTANT_NameAndType: return new ConstantNameAndType(file); case Constants.CONSTANT_Utf8: return new ConstantUtf8(file); default: throw new ClassFormatException("Invalid byte tag in constant pool: " + b); } }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantLong.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeLong(bytes); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantDouble.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeDouble(bytes); }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapEntry.java
public final void dump( DataOutputStream file ) throws IOException { file.writeShort(byte_code_offset); file.writeShort(number_of_locals); for (int i = 0; i < number_of_locals; i++) { types_of_locals[i].dump(file); } file.writeShort(number_of_stack_items); for (int i = 0; i < number_of_stack_items; i++) { types_of_stack_items[i].dump(file); } }
// in java/org/apache/tomcat/util/bcel/classfile/Annotations.java
protected void writeAnnotations(DataOutputStream dos) throws IOException { if (annotation_table == null) { return; } dos.writeShort(annotation_table.length); for (int i = 0; i < annotation_table.length; i++) { annotation_table[i].dump(dos); } }
// in java/org/apache/tomcat/util/bcel/classfile/LocalVariableTable.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(local_variable_table_length); for (int i = 0; i < local_variable_table_length; i++) { local_variable_table[i].dump(file); } }
// in java/org/apache/tomcat/util/bcel/classfile/EnumElementValue.java
Override public void dump(DataOutputStream dos) throws IOException { dos.writeByte(type); // u1 type of value (ENUM_CONSTANT == 'e') dos.writeShort(typeIdx); // u2 dos.writeShort(valueIdx); // u2 }
// in java/org/apache/tomcat/util/bcel/classfile/Unknown.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); if (length > 0) { file.write(bytes, 0, length); } }
// in java/org/apache/tomcat/util/bcel/classfile/Attribute.java
public void dump(DataOutputStream file) throws IOException { file.writeShort(name_index); file.writeInt(length); }
// in java/org/apache/tomcat/util/bcel/classfile/Attribute.java
public static final Attribute readAttribute(DataInputStream file, ConstantPool constant_pool) throws IOException, ClassFormatException { ConstantUtf8 c; String name; int name_index; int length; byte tag = Constants.ATTR_UNKNOWN; // Unknown attribute // Get class name from constant pool via `name_index' indirection name_index = file.readUnsignedShort(); c = (ConstantUtf8) constant_pool.getConstant(name_index, Constants.CONSTANT_Utf8); name = c.getBytes(); // Length of data in bytes length = file.readInt(); // Compare strings to find known attribute // System.out.println(name); for (byte i = 0; i < Constants.KNOWN_ATTRIBUTES; i++) { if (name.equals(Constants.ATTRIBUTE_NAMES[i])) { tag = i; // found! break; } } // Call proper constructor, depending on `tag' switch (tag) { case Constants.ATTR_UNKNOWN: AttributeReader r = readers.get(name); if (r != null) { return r.createAttribute(name_index, length, file, constant_pool); } return new Unknown(name_index, length, file, constant_pool); case Constants.ATTR_CONSTANT_VALUE: return new ConstantValue(name_index, length, file, constant_pool); case Constants.ATTR_SOURCE_FILE: return new SourceFile(name_index, length, file, constant_pool); case Constants.ATTR_CODE: return new Code(name_index, length, file, constant_pool); case Constants.ATTR_EXCEPTIONS: return new ExceptionTable(name_index, length, file, constant_pool); case Constants.ATTR_LINE_NUMBER_TABLE: return new LineNumberTable(name_index, length, file, constant_pool); case Constants.ATTR_LOCAL_VARIABLE_TABLE: return new LocalVariableTable(name_index, length, file, constant_pool); case Constants.ATTR_INNER_CLASSES: return new InnerClasses(name_index, length, file, constant_pool); case Constants.ATTR_SYNTHETIC: return new Synthetic(name_index, length, file, constant_pool); case Constants.ATTR_DEPRECATED: return new Deprecated(name_index, length, file, constant_pool); case Constants.ATTR_PMG: return new PMGClass(name_index, length, file, constant_pool); case Constants.ATTR_SIGNATURE: return new Signature(name_index, length, file, constant_pool); case Constants.ATTR_STACK_MAP: return new StackMap(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIME_VISIBLE_ANNOTATIONS: return new RuntimeVisibleAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIMEIN_VISIBLE_ANNOTATIONS: return new RuntimeInvisibleAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS: return new RuntimeVisibleParameterAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIMEIN_VISIBLE_PARAMETER_ANNOTATIONS: return new RuntimeInvisibleParameterAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_ANNOTATION_DEFAULT: return new AnnotationDefault(name_index, length, file, constant_pool); case Constants.ATTR_LOCAL_VARIABLE_TYPE_TABLE: return new LocalVariableTypeTable(name_index, length, file, constant_pool); case Constants.ATTR_ENCLOSING_METHOD: return new EnclosingMethod(name_index, length, file, constant_pool); case Constants.ATTR_STACK_MAP_TABLE: return new StackMapTable(name_index, length, file, constant_pool); default: // Never reached throw new IllegalStateException("Unrecognized attribute type tag parsed: " + tag); } }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantUtf8.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeUTF(bytes); }
// in java/org/apache/tomcat/util/bcel/classfile/LocalVariable.java
public final void dump( DataOutputStream file ) throws IOException { file.writeShort(start_pc); file.writeShort(length); file.writeShort(name_index); file.writeShort(signature_index); file.writeShort(index); }
// in java/org/apache/tomcat/util/bcel/classfile/AnnotationDefault.java
Override public final void dump(DataOutputStream dos) throws IOException { super.dump(dos); default_value.dump(dos); }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapTable.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(map_length); for (int i = 0; i < map_length; i++) { map[i].dump(file); } }
// in java/org/apache/tomcat/util/bcel/classfile/AnnotationElementValue.java
Override public void dump(DataOutputStream dos) throws IOException { dos.writeByte(type); // u1 type of value (ANNOTATION == '@') annotationEntry.dump(dos); }
// in java/org/apache/tomcat/util/bcel/classfile/Signature.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(signature_index); }
// in java/org/apache/tomcat/util/bcel/classfile/EnclosingMethod.java
Override public final void dump(DataOutputStream file) throws IOException { super.dump(file); file.writeShort(classIndex); file.writeShort(methodIndex); }
// in java/org/apache/tomcat/util/bcel/classfile/InnerClass.java
public final void dump( DataOutputStream file ) throws IOException { file.writeShort(inner_class_index); file.writeShort(outer_class_index); file.writeShort(inner_name_index); file.writeShort(inner_access_flags); }
// in java/org/apache/tomcat/util/bcel/classfile/ArrayElementValue.java
Override public void dump(DataOutputStream dos) throws IOException { dos.writeByte(type); // u1 type of value (ARRAY == '[') dos.writeShort(evalues.length); for (int i = 0; i < evalues.length; i++) { evalues[i].dump(dos); } }
// in java/org/apache/tomcat/util/bcel/classfile/PMGClass.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(pmg_index); file.writeShort(pmg_class_index); }
// in java/org/apache/tomcat/util/bcel/classfile/AnnotationEntry.java
public static AnnotationEntry read(DataInputStream file, ConstantPool constant_pool) throws IOException { final AnnotationEntry annotationEntry = new AnnotationEntry(file.readUnsignedShort(), constant_pool); final int num_element_value_pairs = (file.readUnsignedShort()); annotationEntry.element_value_pairs = new ArrayList<ElementValuePair>(); for (int i = 0; i < num_element_value_pairs; i++) { annotationEntry.element_value_pairs.add(new ElementValuePair(file.readUnsignedShort(), ElementValue.readElementValue(file, constant_pool), constant_pool)); } return annotationEntry; }
// in java/org/apache/tomcat/util/bcel/classfile/AnnotationEntry.java
public void dump(DataOutputStream dos) throws IOException { dos.writeShort(type_index); // u2 index of type name in cpool dos.writeShort(element_value_pairs.size()); // u2 element_value pair // count for (int i = 0; i < element_value_pairs.size(); i++) { final ElementValuePair envp = element_value_pairs.get(i); envp.dump(dos); } }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapTableEntry.java
public final void dump( DataOutputStream file ) throws IOException { file.write(frame_type); if (frame_type >= Constants.SAME_FRAME && frame_type <= Constants.SAME_FRAME_MAX) { // nothing to be done } else if (frame_type >= Constants.SAME_LOCALS_1_STACK_ITEM_FRAME && frame_type <= Constants.SAME_LOCALS_1_STACK_ITEM_FRAME_MAX) { types_of_stack_items[0].dump(file); } else if (frame_type == Constants.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { file.writeShort(byte_code_offset_delta); types_of_stack_items[0].dump(file); } else if (frame_type >= Constants.CHOP_FRAME && frame_type <= Constants.CHOP_FRAME_MAX) { file.writeShort(byte_code_offset_delta); } else if (frame_type == Constants.SAME_FRAME_EXTENDED) { file.writeShort(byte_code_offset_delta); } else if (frame_type >= Constants.APPEND_FRAME && frame_type <= Constants.APPEND_FRAME_MAX) { file.writeShort(byte_code_offset_delta); for (int i = 0; i < number_of_locals; i++) { types_of_locals[i].dump(file); } } else if (frame_type == Constants.FULL_FRAME) { file.writeShort(byte_code_offset_delta); file.writeShort(number_of_locals); for (int i = 0; i < number_of_locals; i++) { types_of_locals[i].dump(file); } file.writeShort(number_of_stack_items); for (int i = 0; i < number_of_stack_items; i++) { types_of_stack_items[i].dump(file); } } else { /* Can't happen */ throw new ClassFormatException ("Invalid Stack map table tag: " + frame_type); } }
// in java/org/apache/tomcat/util/bcel/classfile/LineNumberTable.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(line_number_table_length); for (int i = 0; i < line_number_table_length; i++) { line_number_table[i].dump(file); } }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapType.java
public final void dump( DataOutputStream file ) throws IOException { file.writeByte(type); if (hasIndex()) { file.writeShort(getIndex()); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
public JavaClass parse() throws IOException, ClassFormatException { /****************** Read headers ********************************/ // Check magic tag of class file readID(); // Get compiler version readVersion(); /****************** Read constant pool and related **************/ // Read constant pool entries readConstantPool(); // Get class information readClassInfo(); // Get interface information, i.e., implemented interfaces readInterfaces(); /****************** Read class fields and methods ***************/ // Read class fields, i.e., the variables of the class readFields(); // Read class methods, i.e., the functions in the class readMethods(); // Read class attributes readAttributes(); // Check for unknown variables //Unknown[] u = Unknown.getUnknownAttributes(); //for(int i=0; i < u.length; i++) // System.err.println("WARNING: " + u[i]); // Everything should have been read now // if(file.available() > 0) { // int bytes = file.available(); // byte[] buf = new byte[bytes]; // file.read(buf); // if(!(is_zip && (buf.length == 1))) { // System.err.println("WARNING: Trailing garbage at end of " + file_name); // System.err.println(bytes + " extra bytes: " + Utility.toHexString(buf)); // } // } // Return the information we have gathered in a new object return new JavaClass(class_name_index, superclass_name_index, file_name, major, minor, access_flags, constant_pool, interfaces, fields, methods, attributes); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readAttributes() throws IOException, ClassFormatException { int attributes_count; attributes_count = file.readUnsignedShort(); attributes = new Attribute[attributes_count]; for (int i = 0; i < attributes_count; i++) { attributes[i] = Attribute.readAttribute(file, constant_pool); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readClassInfo() throws IOException, ClassFormatException { access_flags = file.readUnsignedShort(); /* Interfaces are implicitely abstract, the flag should be set * according to the JVM specification. */ if ((access_flags & Constants.ACC_INTERFACE) != 0) { access_flags |= Constants.ACC_ABSTRACT; } if (((access_flags & Constants.ACC_ABSTRACT) != 0) && ((access_flags & Constants.ACC_FINAL) != 0)) { throw new ClassFormatException("Class " + file_name + " can't be both final and abstract"); } class_name_index = file.readUnsignedShort(); superclass_name_index = file.readUnsignedShort(); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readConstantPool() throws IOException, ClassFormatException { constant_pool = new ConstantPool(file); }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readFields() throws IOException, ClassFormatException { int fields_count; fields_count = file.readUnsignedShort(); fields = new Field[fields_count]; for (int i = 0; i < fields_count; i++) { fields[i] = new Field(file, constant_pool); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readID() throws IOException, ClassFormatException { int magic = 0xCAFEBABE; if (file.readInt() != magic) { throw new ClassFormatException(file_name + " is not a Java .class file"); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readInterfaces() throws IOException, ClassFormatException { int interfaces_count; interfaces_count = file.readUnsignedShort(); interfaces = new int[interfaces_count]; for (int i = 0; i < interfaces_count; i++) { interfaces[i] = file.readUnsignedShort(); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readMethods() throws IOException, ClassFormatException { int methods_count; methods_count = file.readUnsignedShort(); methods = new Method[methods_count]; for (int i = 0; i < methods_count; i++) { methods[i] = new Method(file, constant_pool); } }
// in java/org/apache/tomcat/util/bcel/classfile/ClassParser.java
private final void readVersion() throws IOException, ClassFormatException { minor = file.readUnsignedShort(); major = file.readUnsignedShort(); }
// in java/org/apache/tomcat/util/bcel/classfile/LocalVariableTypeTable.java
Override public final void dump(DataOutputStream file) throws IOException { super.dump(file); file.writeShort(local_variable_type_table_length); for(int i=0; i < local_variable_type_table_length; i++) local_variable_type_table[i].dump(file); }
// in java/org/apache/tomcat/util/bcel/classfile/SimpleElementValue.java
Override public void dump(DataOutputStream dos) throws IOException { dos.writeByte(type); // u1 kind of value switch (type) { case PRIMITIVE_INT: case PRIMITIVE_BYTE: case PRIMITIVE_CHAR: case PRIMITIVE_FLOAT: case PRIMITIVE_LONG: case PRIMITIVE_BOOLEAN: case PRIMITIVE_SHORT: case PRIMITIVE_DOUBLE: case STRING: dos.writeShort(getIndex()); break; default: throw new RuntimeException( "SimpleElementValue doesnt know how to write out type " + type); } }
// in java/org/apache/tomcat/util/bcel/classfile/CodeException.java
public final void dump( DataOutputStream file ) throws IOException { file.writeShort(start_pc); file.writeShort(end_pc); file.writeShort(handler_pc); file.writeShort(catch_type); }
// in java/org/apache/tomcat/util/bcel/classfile/RuntimeVisibleAnnotations.java
Override public final void dump(DataOutputStream dos) throws IOException { super.dump(dos); writeAnnotations(dos); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantClass.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeShort(name_index); }
// in java/org/apache/tomcat/util/bcel/classfile/Code.java
Override public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(max_stack); file.writeShort(max_locals); file.writeInt(code_length); file.write(code, 0, code_length); file.writeShort(exception_table_length); for (int i = 0; i < exception_table_length; i++) { exception_table[i].dump(file); } file.writeShort(attributes_count); for (int i = 0; i < attributes_count; i++) { attributes[i].dump(file); } }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantCP.java
Override public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeShort(class_index); file.writeShort(name_and_type_index); }
// in java/org/apache/tomcat/util/bcel/classfile/ElementValuePair.java
protected void dump(DataOutputStream dos) throws IOException { dos.writeShort(elementNameIndex); // u2 name of the element elementValue.dump(dos); }
// in java/org/apache/tomcat/util/bcel/classfile/LineNumber.java
public final void dump( DataOutputStream file ) throws IOException { file.writeShort(start_pc); file.writeShort(line_number); }
// in java/org/apache/el/lang/FunctionMapperImpl.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(this.functions); }
// in java/org/apache/el/lang/FunctionMapperImpl.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF((this.prefix != null) ? this.prefix : ""); out.writeUTF(this.localName); // make sure m isn't null getMethod(); out.writeUTF((this.owner != null) ? this.owner : this.m.getDeclaringClass().getName()); out.writeUTF((this.name != null) ? this.name : this.m.getName()); out.writeObject((this.types != null) ? this.types : ReflectionUtil.toTypeNameArray(this.m.getParameterTypes())); }
// in java/org/apache/el/lang/FunctionMapperImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.prefix = in.readUTF(); if ("".equals(this.prefix)) this.prefix = null; this.localName = in.readUTF(); this.owner = in.readUTF(); this.name = in.readUTF(); this.types = (String[]) in.readObject(); }
// in java/org/apache/el/MethodExpressionImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.expr = in.readUTF(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } this.paramTypes = ReflectionUtil.toTypeArray(((String[]) in .readObject())); this.fnMapper = (FunctionMapper) in.readObject(); this.varMapper = (VariableMapper) in.readObject(); }
// in java/org/apache/el/MethodExpressionImpl.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(this.expr); out.writeUTF((this.expectedType != null) ? this.expectedType.getName() : ""); out.writeObject(ReflectionUtil.toTypeNameArray(this.paramTypes)); out.writeObject(this.fnMapper); out.writeObject(this.varMapper); }
// in java/org/apache/el/MethodExpressionLiteral.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.expr = in.readUTF(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } this.paramTypes = ReflectionUtil.toTypeArray(((String[]) in .readObject())); }
// in java/org/apache/el/MethodExpressionLiteral.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(this.expr); out.writeUTF((this.expectedType != null) ? this.expectedType.getName() : ""); out.writeObject(ReflectionUtil.toTypeNameArray(this.paramTypes)); }
// in java/org/apache/el/parser/SimpleCharStream.java
protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
// in java/org/apache/el/parser/SimpleCharStream.java
public char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); tokenBegin = bufpos; return c; }
// in java/org/apache/el/parser/SimpleCharStream.java
public char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; return buffer[bufpos]; } if (++bufpos >= maxNextCharInd) FillBuff(); char c = buffer[bufpos]; UpdateLineColumn(c); return c; }
// in java/org/apache/el/ValueExpressionLiteral.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(this.value); out.writeUTF((this.expectedType != null) ? this.expectedType.getName() : ""); }
// in java/org/apache/el/ValueExpressionLiteral.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.value = in.readObject(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } }
// in java/org/apache/el/ValueExpressionImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.expr = in.readUTF(); String type = in.readUTF(); if (!"".equals(type)) { this.expectedType = ReflectionUtil.forName(type); } this.fnMapper = (FunctionMapper) in.readObject(); this.varMapper = (VariableMapper) in.readObject(); }
// in java/org/apache/el/ValueExpressionImpl.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(this.expr); out.writeUTF((this.expectedType != null) ? this.expectedType.getName() : ""); out.writeObject(this.fnMapper); out.writeObject(this.varMapper); }
// in java/org/apache/catalina/startup/ContextConfig.java
protected void fixDocBase() throws IOException { Host host = (Host) context.getParent(); File appBase = host.getAppBaseFile(); String docBase = context.getDocBase(); if (docBase == null) { // Trying to guess the docBase according to the path String path = context.getPath(); if (path == null) { return; } ContextName cn = new ContextName(path, context.getWebappVersion()); docBase = cn.getBaseName(); } File file = new File(docBase); if (!file.isAbsolute()) { docBase = (new File(appBase, docBase)).getPath(); } else { docBase = file.getCanonicalPath(); } file = new File(docBase); String origDocBase = docBase; ContextName cn = new ContextName(context.getPath(), context.getWebappVersion()); String pathName = cn.getBaseName(); boolean unpackWARs = true; if (host instanceof StandardHost && context instanceof StandardContext) { unpackWARs = ((StandardHost) host).isUnpackWARs() && ((StandardContext) context).getUnpackWAR() && (docBase.startsWith(host.getAppBaseFile().getPath())); } if (docBase.toLowerCase(Locale.ENGLISH).endsWith(".war") && !file.isDirectory() && unpackWARs) { URL war = new URL("jar:" + (new File(docBase)).toURI().toURL() + "!/"); docBase = ExpandWar.expand(host, war, pathName); file = new File(docBase); docBase = file.getCanonicalPath(); if (context instanceof StandardContext) { ((StandardContext) context).setOriginalDocBase(origDocBase); } } else if (docBase.toLowerCase(Locale.ENGLISH).endsWith(".war") && !file.isDirectory() && !unpackWARs) { URL war = new URL("jar:" + (new File (docBase)).toURI().toURL() + "!/"); ExpandWar.validate(host, war, pathName); } else { File docDir = new File(docBase); if (!docDir.exists()) { File warFile = new File(docBase + ".war"); if (warFile.exists()) { URL war = new URL("jar:" + warFile.toURI().toURL() + "!/"); if (unpackWARs) { docBase = ExpandWar.expand(host, war, pathName); file = new File(docBase); docBase = file.getCanonicalPath(); } else { docBase = warFile.getCanonicalPath(); ExpandWar.validate(host, war, pathName); } } if (context instanceof StandardContext) { ((StandardContext) context).setOriginalDocBase(origDocBase); } } } if (docBase.startsWith(appBase.getPath() + File.separatorChar)) { docBase = docBase.substring(appBase.getPath().length()); docBase = docBase.replace(File.separatorChar, '/'); if (docBase.startsWith("/")) { docBase = docBase.substring(1); } } else { docBase = docBase.replace(File.separatorChar, '/'); } context.setDocBase(docBase); }
// in java/org/apache/catalina/startup/ContextConfig.java
protected ServletContainerInitializer getServletContainerInitializer( InputStream is) throws IOException { String className = null; if (is != null) { String line = null; try { BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); line = br.readLine(); if (line != null && line.trim().length() > 0) { className = line.trim(); } } catch (UnsupportedEncodingException e) { // Should never happen with UTF-8 // If it does - ignore & return null } } ServletContainerInitializer sci = null; try { Class<?> clazz = Class.forName(className,true, context.getLoader().getClassLoader()); sci = (ServletContainerInitializer) clazz.newInstance(); } catch (ClassNotFoundException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); } catch (InstantiationException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); } catch (IllegalAccessException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); } return sci; }
// in java/org/apache/catalina/startup/ContextConfig.java
protected void processAnnotationsStream(InputStream is, WebXml fragment) throws ClassFormatException, IOException { ClassParser parser = new ClassParser(is, null); JavaClass clazz = parser.parse(); checkHandlesTypes(clazz); String className = clazz.getClassName(); AnnotationEntry[] annotationsEntries = clazz.getAnnotationEntries(); for (AnnotationEntry ae : annotationsEntries) { String type = ae.getAnnotationType(); if ("Ljavax/servlet/annotation/WebServlet;".equals(type)) { processAnnotationWebServlet(className, ae, fragment); }else if ("Ljavax/servlet/annotation/WebFilter;".equals(type)) { processAnnotationWebFilter(className, ae, fragment); }else if ("Ljavax/servlet/annotation/WebListener;".equals(type)) { fragment.addListener(className); } else { // Unknown annotation - ignore } } }
// in java/org/apache/catalina/startup/ContextConfig.java
Override public void scan(JarURLConnection jarConn) throws IOException { URL url = jarConn.getURL(); URL resourceURL = jarConn.getJarFileURL(); Jar jar = null; InputStream is = null; WebXml fragment = new WebXml(); try { jar = JarFactory.newInstance(url); is = jar.getInputStream(FRAGMENT_LOCATION); if (is == null) { // If there is no web.xml, normal JAR no impact on // distributable fragment.setDistributable(true); } else { InputSource source = new InputSource( resourceURL.toString() + "!/" + FRAGMENT_LOCATION); source.setByteStream(is); parseWebXml(source, fragment, true); } } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } if (jar != null) { jar.close(); } fragment.setURL(url); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); } }
// in java/org/apache/catalina/startup/ContextConfig.java
Override public void scan(File file) throws IOException { InputStream stream = null; WebXml fragment = new WebXml(); try { File fragmentFile = new File(file, FRAGMENT_LOCATION); if (fragmentFile.isFile()) { stream = new FileInputStream(fragmentFile); InputSource source = new InputSource(fragmentFile.toURI().toURL().toString()); source.setByteStream(stream); parseWebXml(source, fragment, true); } } finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } fragment.setURL(file.toURI().toURL()); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragments.put(fragment.getName(), fragment); } }
// in java/org/apache/catalina/startup/TldConfig.java
Override public void scan(JarURLConnection urlConn) throws IOException { tldScanJar(urlConn); }
// in java/org/apache/catalina/startup/TldConfig.java
private XmlErrorHandler tldScanStream(InputStream resourceStream) throws IOException { InputSource source = new InputSource(resourceStream); XmlErrorHandler result = new XmlErrorHandler(); synchronized (tldDigester) { try { tldDigester.setErrorHandler(result); tldDigester.push(this); tldDigester.parse(source); } catch (SAXException s) { // Hack - makes exception handling simpler throw new IOException(s); } finally { tldDigester.reset(); } return result; } }
// in java/org/apache/catalina/startup/ClassLoaderFactory.java
private static boolean validateFile(File file, RepositoryType type) throws IOException { if (RepositoryType.DIR == type || RepositoryType.GLOB == type) { if (!file.exists() || !file.isDirectory() || !file.canRead()) { String msg = "Problem with directory [" + file + "], exists: [" + file.exists() + "], isDirectory: [" + file.isDirectory() + "], canRead: [" + file.canRead() + "]"; File home = new File (Bootstrap.getCatalinaHome()); home = home.getCanonicalFile(); File base = new File (Bootstrap.getCatalinaBase()); base = base.getCanonicalFile(); File defaultValue = new File(base, "lib"); // Existence of ${catalina.base}/lib directory is optional. // Hide the warning if Tomcat runs with separate catalina.home // and catalina.base and that directory is absent. if (!home.getPath().equals(base.getPath()) && file.getPath().equals(defaultValue.getPath()) && !file.exists()) { log.debug(msg); } else { log.warn(msg); } return false; } } else if (RepositoryType.JAR == type) { if (!file.exists() || !file.canRead()) { log.warn("Problem with JAR file [" + file + "], exists: [" + file.exists() + "], canRead: [" + file.canRead() + "]"); return false; } } return true; }
// in java/org/apache/catalina/startup/ExpandWar.java
public static String expand(Host host, URL war, String pathname) throws IOException { // Make sure that there is no such directory already existing File docBase = new File(host.getAppBaseFile(), pathname); if (docBase.exists()) { // War file is already installed return (docBase.getAbsolutePath()); } // Create the new document base directory docBase.mkdir(); // Expand the WAR into the new document base directory String canonicalDocBasePrefix = docBase.getCanonicalPath(); if (!canonicalDocBasePrefix.endsWith(File.separator)) { canonicalDocBasePrefix += File.separator; } JarURLConnection juc = (JarURLConnection) war.openConnection(); juc.setUseCaches(false); JarFile jarFile = null; InputStream input = null; boolean success = false; try { jarFile = juc.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String name = jarEntry.getName(); File expandedFile = new File(docBase, name); if (!expandedFile.getCanonicalPath().startsWith( canonicalDocBasePrefix)) { // Trying to expand outside the docBase // Throw an exception to stop the deployment throw new IllegalArgumentException( sm.getString("expandWar.illegalPath",war, name, expandedFile.getCanonicalPath(), canonicalDocBasePrefix)); } int last = name.lastIndexOf('/'); if (last >= 0) { File parent = new File(docBase, name.substring(0, last)); if (!parent.mkdirs() && !parent.isDirectory()) { throw new IOException( sm.getString("expandWar.createFailed", parent)); } } if (name.endsWith("/")) { continue; } input = jarFile.getInputStream(jarEntry); if(null == input) throw new ZipException(sm.getString("expandWar.missingJarEntry", jarEntry.getName())); // Bugzilla 33636 expand(input, expandedFile); long lastModified = jarEntry.getTime(); if ((lastModified != -1) && (lastModified != 0)) { expandedFile.setLastModified(lastModified); } input.close(); input = null; } success = true; } catch (IOException e) { throw e; } finally { if (!success) { // If something went wrong, delete expanded dir to keep things // clean deleteDir(docBase); } if (input != null) { try { input.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } input = null; } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } } // Return the absolute path to our new document base directory return (docBase.getAbsolutePath()); }
// in java/org/apache/catalina/startup/ExpandWar.java
public static void validate(Host host, URL war, String pathname) throws IOException { File docBase = new File(host.getAppBaseFile(), pathname); // Calculate the document base directory String canonicalDocBasePrefix = docBase.getCanonicalPath(); if (!canonicalDocBasePrefix.endsWith(File.separator)) { canonicalDocBasePrefix += File.separator; } JarURLConnection juc = (JarURLConnection) war.openConnection(); juc.setUseCaches(false); JarFile jarFile = null; try { jarFile = juc.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String name = jarEntry.getName(); File expandedFile = new File(docBase, name); if (!expandedFile.getCanonicalPath().startsWith( canonicalDocBasePrefix)) { // Entry located outside the docBase // Throw an exception to stop the deployment throw new IllegalArgumentException( sm.getString("expandWar.illegalPath",war, name, expandedFile.getCanonicalPath(), canonicalDocBasePrefix)); } } } catch (IOException e) { throw e; } finally { if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } } }
// in java/org/apache/catalina/startup/ExpandWar.java
private static void expand(InputStream input, File file) throws IOException { BufferedOutputStream output = null; try { output = new BufferedOutputStream(new FileOutputStream(file)); byte buffer[] = new byte[2048]; while (true) { int n = input.read(buffer); if (n <= 0) break; output.write(buffer, 0, n); } } finally { if (output != null) { try { output.close(); } catch (IOException e) { // Ignore } } } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
synchronized void addJar(String jar, JarFile jarFile, File file) throws IOException { if (jar == null) return; if (jarFile == null) return; if (file == null) return; if (log.isDebugEnabled()) log.debug("addJar(" + jar + ")"); int i; if ((jarPath != null) && (jar.startsWith(jarPath))) { String jarName = jar.substring(jarPath.length()); while (jarName.startsWith("/")) jarName = jarName.substring(1); String[] result = new String[jarNames.length + 1]; for (i = 0; i < jarNames.length; i++) { result[i] = jarNames[i]; } result[jarNames.length] = jarName; jarNames = result; } try { // Register the JAR for tracking long lastModified = ((ResourceAttributes) resources.getAttributes(jar)) .getLastModified(); String[] result = new String[paths.length + 1]; for (i = 0; i < paths.length; i++) { result[i] = paths[i]; } result[paths.length] = jar; paths = result; long[] result3 = new long[lastModifiedDates.length + 1]; for (i = 0; i < lastModifiedDates.length; i++) { result3[i] = lastModifiedDates[i]; } result3[lastModifiedDates.length] = lastModified; lastModifiedDates = result3; } catch (NamingException e) { // Ignore } // If the JAR currently contains invalid classes, don't actually use it // for classloading if (!validateJarFile(file)) return; JarFile[] result2 = new JarFile[jarFiles.length + 1]; for (i = 0; i < jarFiles.length; i++) { result2[i] = jarFiles[i]; } result2[jarFiles.length] = jarFile; jarFiles = result2; // Add the file to the list File[] result4 = new File[jarRealFiles.length + 1]; for (i = 0; i < jarRealFiles.length; i++) { result4[i] = jarRealFiles[i]; } result4[jarRealFiles.length] = file; jarRealFiles = result4; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public Enumeration<URL> findResources(String name) throws IOException { if (log.isDebugEnabled()) log.debug(" findResources(" + name + ")"); //we use a LinkedHashSet instead of a Vector to avoid duplicates with virtualmappings LinkedHashSet<URL> result = new LinkedHashSet<URL>(); int jarFilesLength = jarFiles.length; int repositoriesLength = repositories.length; int i; // Adding the results of a call to the superclass if (hasExternalRepositories && searchExternalFirst) { Enumeration<URL> otherResourcePaths = super.findResources(name); while (otherResourcePaths.hasMoreElements()) { result.add(otherResourcePaths.nextElement()); } } // Looking at the repositories for (i = 0; i < repositoriesLength; i++) { try { String fullPath = repositories[i] + name; resources.lookup(fullPath); // Note : Not getting an exception here means the resource was // found try { result.add(getURI(new File(files[i], name))); } catch (MalformedURLException e) { // Ignore } } catch (NamingException e) { // Ignore } } // Looking at the JAR files synchronized (jarFiles) { if (openJARs()) { for (i = 0; i < jarFilesLength; i++) { JarEntry jarEntry = jarFiles[i].getJarEntry(name); if (jarEntry != null) { try { String jarFakeUrl = getURI(jarRealFiles[i]).toString(); jarFakeUrl = "jar:" + jarFakeUrl + "!/" + name; result.add(new URL(jarFakeUrl)); } catch (MalformedURLException e) { // Ignore } } } } } // Adding the results of a call to the superclass if (hasExternalRepositories && !searchExternalFirst) { Enumeration<URL> otherResourcePaths = super.findResources(name); while (otherResourcePaths.hasMoreElements()) { result.add(otherResourcePaths.nextElement()); } } final Iterator<URL> iterator = result.iterator(); return new Enumeration<URL>() { @Override public boolean hasMoreElements() { return iterator.hasNext(); } @Override public URL nextElement() { return iterator.next(); } }; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
protected boolean validateJarFile(File file) throws IOException { if (triggers == null) return (true); JarFile jarFile = null; try { jarFile = new JarFile(file); for (int i = 0; i < triggers.length; i++) { Class<?> clazz = null; try { if (parent != null) { clazz = parent.loadClass(triggers[i]); } else { clazz = Class.forName(triggers[i]); } } catch (Exception e) { clazz = null; } if (clazz == null) continue; String name = triggers[i].replace('.', '/') + ".class"; if (log.isDebugEnabled()) log.debug(" Checking for " + name); JarEntry jarEntry = jarFile.getJarEntry(name); if (jarEntry != null) { log.info("validateJarFile(" + file + ") - jar not loaded. See Servlet Spec 2.3, " + "section 9.7.2. Offending class: " + name); return false; } } return true; } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException ioe) { // Ignore } } } }
// in java/org/apache/catalina/loader/WebappLoader.java
private void setRepositories() throws IOException { if (!(container instanceof Context)) return; ServletContext servletContext = ((Context) container).getServletContext(); if (servletContext == null) return; loaderRepositories=new ArrayList<String>(); // Loading the work directory File workDir = (File) servletContext.getAttribute(ServletContext.TEMPDIR); if (workDir == null) { log.info("No work dir for " + servletContext); } if( log.isDebugEnabled() && workDir != null) log.debug(sm.getString("webappLoader.deploy", workDir.getAbsolutePath())); classLoader.setWorkDir(workDir); DirContext resources = container.getResources(); // Setting up the class repository (/WEB-INF/classes), if it exists String classesPath = "/WEB-INF/classes"; DirContext classes = null; try { Object object = resources.lookup(classesPath); if (object instanceof DirContext) { classes = (DirContext) object; } } catch(NamingException e) { // Silent catch: it's valid that no /WEB-INF/classes collection // exists } if (classes != null) { File classRepository = null; String absoluteClassesPath = servletContext.getRealPath(classesPath); if (absoluteClassesPath != null) { classRepository = new File(absoluteClassesPath); } else { classRepository = new File(workDir, classesPath); if (!classRepository.mkdirs() && !classRepository.isDirectory()) { throw new IOException( sm.getString("webappLoader.mkdirFailure")); } if (!copyDir(classes, classRepository)) { throw new IOException( sm.getString("webappLoader.copyFailure")); } } if(log.isDebugEnabled()) log.debug(sm.getString("webappLoader.classDeploy", classesPath, classRepository.getAbsolutePath())); // Adding the repository to the class loader classLoader.addRepository(classesPath + "/", classRepository); loaderRepositories.add(classesPath + "/" ); } // Setting up the JAR repository (/WEB-INF/lib), if it exists String libPath = "/WEB-INF/lib"; classLoader.setJarPath(libPath); DirContext libDir = null; // Looking up directory /WEB-INF/lib in the context try { Object object = resources.lookup(libPath); if (object instanceof DirContext) libDir = (DirContext) object; } catch(NamingException e) { // Silent catch: it's valid that no /WEB-INF/lib collection // exists } if (libDir != null) { boolean copyJars = false; String absoluteLibPath = servletContext.getRealPath(libPath); File destDir = null; if (absoluteLibPath != null) { destDir = new File(absoluteLibPath); } else { copyJars = true; destDir = new File(workDir, libPath); if (!destDir.mkdirs() && !destDir.isDirectory()) { throw new IOException( sm.getString("webappLoader.mkdirFailure")); } } // Looking up directory /WEB-INF/lib in the context NamingEnumeration<NameClassPair> enumeration = null; try { enumeration = libDir.list(""); } catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", libPath)); ioe.initCause(e); throw ioe; } while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String filename = libPath + "/" + ncPair.getName(); if (!filename.endsWith(".jar")) continue; // Copy JAR in the work directory, always (the JAR file // would get locked otherwise, which would make it // impossible to update it or remove it at runtime) File destFile = new File(destDir, ncPair.getName()); if( log.isDebugEnabled()) log.debug(sm.getString("webappLoader.jarDeploy", filename, destFile.getAbsolutePath())); // Bug 45403 - Explicitly call lookup() on the name to check // that the resource is readable. We cannot use resources // returned by listBindings(), because that lists all of them, // but does not perform the necessary checks on each. Object obj = null; try { obj = libDir.lookup(ncPair.getName()); } catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", filename)); ioe.initCause(e); throw ioe; } if (!(obj instanceof Resource)) continue; Resource jarResource = (Resource) obj; if (copyJars) { if (!copy(jarResource.streamContent(), new FileOutputStream(destFile))) { throw new IOException( sm.getString("webappLoader.copyFailure")); } } try { JarFile jarFile = new JarFile(destFile); classLoader.addJar(filename, jarFile, destFile); } catch (Exception ex) { // Catch the exception if there is an empty jar file // Should ignore and continue loading other jar files // in the dir } loaderRepositories.add( filename ); } } }
// in java/org/apache/catalina/realm/RealmBase.java
Override public boolean hasResourcePermission(Request request, Response response, SecurityConstraint []constraints, Context context) throws IOException { if (constraints == null || constraints.length == 0) return (true); // Specifically allow access to the form login and form error pages // and the "j_security_check" action LoginConfig config = context.getLoginConfig(); if ((config != null) && (Constants.FORM_METHOD.equals(config.getAuthMethod()))) { String requestURI = request.getRequestPathMB().toString(); String loginPage = config.getLoginPage(); if (loginPage.equals(requestURI)) { if (log.isDebugEnabled()) log.debug(" Allow access to login page " + loginPage); return (true); } String errorPage = config.getErrorPage(); if (errorPage.equals(requestURI)) { if (log.isDebugEnabled()) log.debug(" Allow access to error page " + errorPage); return (true); } if (requestURI.endsWith(Constants.FORM_ACTION)) { if (log.isDebugEnabled()) log.debug(" Allow access to username/password submission"); return (true); } } // Which user principal have we already authenticated? Principal principal = request.getPrincipal(); boolean status = false; boolean denyfromall = false; for(int i=0; i < constraints.length; i++) { SecurityConstraint constraint = constraints[i]; String roles[]; if (constraint.getAllRoles()) { // * means all roles defined in web.xml roles = request.getContext().findSecurityRoles(); } else { roles = constraint.findAuthRoles(); } if (roles == null) roles = new String[0]; if (log.isDebugEnabled()) log.debug(" Checking roles " + principal); if (roles.length == 0 && !constraint.getAllRoles()) { if(constraint.getAuthConstraint()) { if( log.isDebugEnabled() ) log.debug("No roles"); status = false; // No listed roles means no access at all denyfromall = true; break; } if(log.isDebugEnabled()) log.debug("Passing all access"); status = true; } else if (principal == null) { if (log.isDebugEnabled()) log.debug(" No user authenticated, cannot grant access"); } else { for (int j = 0; j < roles.length; j++) { if (hasRole(null, principal, roles[j])) { status = true; if( log.isDebugEnabled() ) log.debug( "Role found: " + roles[j]); } else if( log.isDebugEnabled() ) log.debug( "No role found: " + roles[j]); } } } if (!denyfromall && allRolesMode != AllRolesMode.STRICT_MODE && !status && principal != null) { if (log.isDebugEnabled()) { log.debug("Checking for all roles mode: " + allRolesMode); } // Check for an all roles(role-name="*") for (int i = 0; i < constraints.length; i++) { SecurityConstraint constraint = constraints[i]; String roles[]; // If the all roles mode exists, sets if (constraint.getAllRoles()) { if (allRolesMode == AllRolesMode.AUTH_ONLY_MODE) { if (log.isDebugEnabled()) { log.debug("Granting access for role-name=*, auth-only"); } status = true; break; } // For AllRolesMode.STRICT_AUTH_ONLY_MODE there must be zero roles roles = request.getContext().findSecurityRoles(); if (roles.length == 0 && allRolesMode == AllRolesMode.STRICT_AUTH_ONLY_MODE) { if (log.isDebugEnabled()) { log.debug("Granting access for role-name=*, strict auth-only"); } status = true; break; } } } } // Return a "Forbidden" message denying access to this resource if(!status) { response.sendError (HttpServletResponse.SC_FORBIDDEN, sm.getString("realmBase.forbidden")); } return status; }
// in java/org/apache/catalina/realm/RealmBase.java
Override public boolean hasUserDataPermission(Request request, Response response, SecurityConstraint []constraints) throws IOException { // Is there a relevant user data constraint? if (constraints == null || constraints.length == 0) { if (log.isDebugEnabled()) log.debug(" No applicable security constraint defined"); return (true); } for(int i=0; i < constraints.length; i++) { SecurityConstraint constraint = constraints[i]; String userConstraint = constraint.getUserConstraint(); if (userConstraint == null) { if (log.isDebugEnabled()) log.debug(" No applicable user data constraint defined"); return (true); } if (userConstraint.equals(Constants.NONE_TRANSPORT)) { if (log.isDebugEnabled()) log.debug(" User data constraint has no restrictions"); return (true); } } // Validate the request against the user data constraint if (request.getRequest().isSecure()) { if (log.isDebugEnabled()) log.debug(" User data constraint already satisfied"); return (true); } // Initialize variables we need to determine the appropriate action int redirectPort = request.getConnector().getRedirectPort(); // Is redirecting disabled? if (redirectPort <= 0) { if (log.isDebugEnabled()) log.debug(" SSL redirect is disabled"); response.sendError (HttpServletResponse.SC_FORBIDDEN, request.getRequestURI()); return (false); } // Redirect to the corresponding SSL port StringBuilder file = new StringBuilder(); String protocol = "https"; String host = request.getServerName(); // Protocol file.append(protocol).append("://").append(host); // Host with port if(redirectPort != 443) { file.append(":").append(redirectPort); } // URI file.append(request.getRequestURI()); String requestedSessionId = request.getRequestedSessionId(); if ((requestedSessionId != null) && request.isRequestedSessionIdFromURL()) { file.append(";"); file.append(SessionConfig.getSessionUriParamName( request.getContext())); file.append("="); file.append(requestedSessionId); } String queryString = request.getQueryString(); if (queryString != null) { file.append('?'); file.append(queryString); } if (log.isDebugEnabled()) log.debug(" Redirecting to " + file.toString()); response.sendRedirect(file.toString()); return (false); }
// in java/org/apache/catalina/realm/JAASCallbackHandler.java
Override public void handle(Callback callbacks[]) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof NameCallback) { if (realm.getContainer().getLogger().isTraceEnabled()) realm.getContainer().getLogger().trace(sm.getString("jaasCallback.username", username)); ((NameCallback) callbacks[i]).setName(username); } else if (callbacks[i] instanceof PasswordCallback) { final char[] passwordcontents; if (password != null) { passwordcontents = password.toCharArray(); } else { passwordcontents = new char[0]; } ((PasswordCallback) callbacks[i]).setPassword (passwordcontents); } else if (callbacks[i] instanceof TextInputCallback) { TextInputCallback cb = ((TextInputCallback) callbacks[i]); if (cb.getPrompt().equals("nonce")) { cb.setText(nonce); } else if (cb.getPrompt().equals("nc")) { cb.setText(nc); } else if (cb.getPrompt().equals("cnonce")) { cb.setText(cnonce); } else if (cb.getPrompt().equals("qop")) { cb.setText(qop); } else if (cb.getPrompt().equals("realmName")) { cb.setText(realmName); } else if (cb.getPrompt().equals("md5a2")) { cb.setText(md5a2); } else if (cb.getPrompt().equals("authMethod")) { cb.setText(authMethod); } else { throw new UnsupportedCallbackException(callbacks[i]); } } else { throw new UnsupportedCallbackException(callbacks[i]); } } }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
Override public Socket createSocket(String host, int port) throws IOException { if (factory == null) { return new Socket(FORCED_HOST, port); } else { return factory.createSocket(FORCED_HOST, port); } }
// in java/org/apache/catalina/filters/SetCharacterEncodingFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Conditionally select and set the character encoding to be used if (ignore || (request.getCharacterEncoding() == null)) { String characterEncoding = selectEncoding(request); if (characterEncoding != null) { request.setCharacterEncoding(characterEncoding); } } // Pass control on to the next filter chain.doFilter(request, response); }
// in java/org/apache/catalina/filters/RequestDumperFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest hRequest = null; HttpServletResponse hResponse = null; if (request instanceof HttpServletRequest) { hRequest = (HttpServletRequest) request; } if (response instanceof HttpServletResponse) { hResponse = (HttpServletResponse) response; } // Log pre-service information doLog("START TIME ", getTimestamp()); if (hRequest == null) { doLog(" requestURI", NON_HTTP_REQ_MSG); doLog(" authType", NON_HTTP_REQ_MSG); } else { doLog(" requestURI", hRequest.getRequestURI()); doLog(" authType", hRequest.getAuthType()); } doLog(" characterEncoding", request.getCharacterEncoding()); doLog(" contentLength", Integer.valueOf(request.getContentLength()).toString()); doLog(" contentType", request.getContentType()); if (hRequest == null) { doLog(" contextPath", NON_HTTP_REQ_MSG); doLog(" cookie", NON_HTTP_REQ_MSG); doLog(" header", NON_HTTP_REQ_MSG); } else { doLog(" contextPath", hRequest.getContextPath()); Cookie cookies[] = hRequest.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { doLog(" cookie", cookies[i].getName() + "=" + cookies[i].getValue()); } } Enumeration<String> hnames = hRequest.getHeaderNames(); while (hnames.hasMoreElements()) { String hname = hnames.nextElement(); Enumeration<String> hvalues = hRequest.getHeaders(hname); while (hvalues.hasMoreElements()) { String hvalue = hvalues.nextElement(); doLog(" header", hname + "=" + hvalue); } } } doLog(" locale", request.getLocale().toString()); if (hRequest == null) { doLog(" method", NON_HTTP_REQ_MSG); } else { doLog(" method", hRequest.getMethod()); } Enumeration<String> pnames = request.getParameterNames(); while (pnames.hasMoreElements()) { String pname = pnames.nextElement(); String pvalues[] = request.getParameterValues(pname); StringBuilder result = new StringBuilder(pname); result.append('='); for (int i = 0; i < pvalues.length; i++) { if (i > 0) { result.append(", "); } result.append(pvalues[i]); } doLog(" parameter", result.toString()); } if (hRequest == null) { doLog(" pathInfo", NON_HTTP_REQ_MSG); } else { doLog(" pathInfo", hRequest.getPathInfo()); } doLog(" protocol", request.getProtocol()); if (hRequest == null) { doLog(" queryString", NON_HTTP_REQ_MSG); } else { doLog(" queryString", hRequest.getQueryString()); } doLog(" remoteAddr", request.getRemoteAddr()); doLog(" remoteHost", request.getRemoteHost()); if (hRequest == null) { doLog(" remoteUser", NON_HTTP_REQ_MSG); doLog("requestedSessionId", NON_HTTP_REQ_MSG); } else { doLog(" remoteUser", hRequest.getRemoteUser()); doLog("requestedSessionId", hRequest.getRequestedSessionId()); } doLog(" scheme", request.getScheme()); doLog(" serverName", request.getServerName()); doLog(" serverPort", Integer.valueOf(request.getServerPort()).toString()); if (hRequest == null) { doLog(" servletPath", NON_HTTP_REQ_MSG); } else { doLog(" servletPath", hRequest.getServletPath()); } doLog(" isSecure", Boolean.valueOf(request.isSecure()).toString()); doLog("------------------", "--------------------------------------------"); // Perform the request chain.doFilter(request, response); // Log post-service information doLog("------------------", "--------------------------------------------"); if (hRequest == null) { doLog(" authType", NON_HTTP_REQ_MSG); } else { doLog(" authType", hRequest.getAuthType()); } doLog(" contentType", response.getContentType()); if (hResponse == null) { doLog(" header", NON_HTTP_RES_MSG); } else { Iterable<String> rhnames = hResponse.getHeaderNames(); for (String rhname : rhnames) { Iterable<String> rhvalues = hResponse.getHeaders(rhname); for (String rhvalue : rhvalues) { doLog(" header", rhname + "=" + rhvalue); } } } if (hRequest == null) { doLog(" remoteUser", NON_HTTP_REQ_MSG); } else { doLog(" remoteUser", hRequest.getRemoteUser()); } if (hResponse == null) { doLog(" remoteUser", NON_HTTP_RES_MSG); } else { doLog(" status", Integer.valueOf(hResponse.getStatus()).toString()); } doLog("END TIME ", getTimestamp()); doLog("==================", "============================================"); }
// in java/org/apache/catalina/filters/RequestFilter.java
protected void process(String property, ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (isAllowed(property)) { chain.doFilter(request, response); } else { if (response instanceof HttpServletResponse) { ((HttpServletResponse) response).sendError(denyStatus); } else { sendErrorWhenNotHttp(response); } } }
// in java/org/apache/catalina/filters/RequestFilter.java
protected void processCometEvent(String property, CometEvent event, CometFilterChain chain) throws IOException, ServletException { HttpServletResponse response = event.getHttpServletResponse(); if (isAllowed(property)) { chain.doFilterEvent(event); } else { response.sendError(denyStatus); event.close(); } }
// in java/org/apache/catalina/filters/RequestFilter.java
private void sendErrorWhenNotHttp(ServletResponse response) throws IOException { response.setContentType(PLAIN_TEXT_MIME_TYPE); response.getWriter().write(sm.getString("http.403")); response.getWriter().flush(); }
// in java/org/apache/catalina/filters/AddDefaultCharsetFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Wrap the response if (response instanceof HttpServletResponse) { ResponseWrapper wrapped = new ResponseWrapper((HttpServletResponse)response, encoding); chain.doFilter(request, wrapped); } else { chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/RemoteHostFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { process(request.getRemoteHost(), request, response, chain); }
// in java/org/apache/catalina/filters/RemoteHostFilter.java
Override public void doFilterEvent(CometEvent event, CometFilterChain chain) throws IOException, ServletException { processCometEvent(event.getHttpServletRequest().getRemoteHost(), event, chain); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public ServletOutputStream getOutputStream() throws IOException { if (servletOutputStream == null) { servletOutputStream = new XServletOutputStream( super.getOutputStream(), request, this); } return servletOutputStream; }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public PrintWriter getWriter() throws IOException { if (printWriter == null) { printWriter = new XPrintWriter(super.getWriter(), request, this); } return printWriter; }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void close() throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.close(); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void flush() throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.flush(); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void print(boolean b) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.print(b); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void print(char c) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.print(c); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void print(double d) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.print(d); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void print(float f) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.print(f); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void print(int i) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.print(i); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void print(long l) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.print(l); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void print(String s) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.print(s); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println() throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println(boolean b) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(b); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println(char c) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(c); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println(double d) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(d); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println(float f) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(f); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println(int i) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(i); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println(long l) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(l); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void println(String s) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.println(s); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void write(byte[] b) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.write(b); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void write(byte[] b, int off, int len) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.write(b, off, len); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void write(int b) throws IOException { fireOnBeforeWriteResponseBodyEvent(); servletOutputStream.write(b); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (response.isCommitted()) { if (log.isDebugEnabled()) { log.debug(sm.getString( "expiresFilter.responseAlreadyCommited", httpRequest.getRequestURL())); } chain.doFilter(request, response); } else { XHttpServletResponse xResponse = new XHttpServletResponse( httpRequest, httpResponse); chain.doFilter(request, xResponse); if (!xResponse.isWriteResponseBodyStarted()) { // Empty response, manually trigger // onBeforeWriteResponseBody() onBeforeWriteResponseBody(httpRequest, xResponse); } } } else { chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (internalProxies != null && internalProxies.matcher(request.getRemoteAddr()).matches()) { String remoteIp = null; // In java 6, proxiesHeaderValue should be declared as a java.util.Deque LinkedList<String> proxiesHeaderValue = new LinkedList<String>(); StringBuilder concatRemoteIpHeaderValue = new StringBuilder(); for (Enumeration<String> e = request.getHeaders(remoteIpHeader); e.hasMoreElements();) { if (concatRemoteIpHeaderValue.length() > 0) { concatRemoteIpHeaderValue.append(", "); } concatRemoteIpHeaderValue.append(e.nextElement()); } String[] remoteIpHeaderValue = commaDelimitedListToStringArray(concatRemoteIpHeaderValue.toString()); int idx; // loop on remoteIpHeaderValue to find the first trusted remote ip and to build the proxies chain for (idx = remoteIpHeaderValue.length - 1; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; remoteIp = currentRemoteIp; if (internalProxies.matcher(currentRemoteIp).matches()) { // do nothing, internalProxies IPs are not appended to the } else if (trustedProxies != null && trustedProxies.matcher(currentRemoteIp).matches()) { proxiesHeaderValue.addFirst(currentRemoteIp); } else { idx--; // decrement idx because break statement doesn't do it break; } } // continue to loop on remoteIpHeaderValue to build the new value of the remoteIpHeader LinkedList<String> newRemoteIpHeaderValue = new LinkedList<String>(); for (; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; newRemoteIpHeaderValue.addFirst(currentRemoteIp); } XForwardedRequest xRequest = new XForwardedRequest(request); if (remoteIp != null) { xRequest.setRemoteAddr(remoteIp); xRequest.setRemoteHost(remoteIp); if (proxiesHeaderValue.size() == 0) { xRequest.removeHeader(proxiesHeader); } else { String commaDelimitedListOfProxies = listToCommaDelimitedString(proxiesHeaderValue); xRequest.setHeader(proxiesHeader, commaDelimitedListOfProxies); } if (newRemoteIpHeaderValue.size() == 0) { xRequest.removeHeader(remoteIpHeader); } else { String commaDelimitedRemoteIpHeaderValue = listToCommaDelimitedString(newRemoteIpHeaderValue); xRequest.setHeader(remoteIpHeader, commaDelimitedRemoteIpHeaderValue); } } if (protocolHeader != null) { String protocolHeaderValue = request.getHeader(protocolHeader); if (protocolHeaderValue == null) { // don't modify the secure,scheme and serverPort attributes of the request } else if (protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue)) { xRequest.setSecure(true); xRequest.setScheme("https"); setPorts(xRequest, httpsServerPort); } else { xRequest.setSecure(false); xRequest.setScheme("http"); setPorts(xRequest, httpServerPort); } } if (log.isDebugEnabled()) { log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "', originalRemoteHost='" + request.getRemoteHost() + "', originalSecure='" + request.isSecure() + "', originalScheme='" + request.getScheme() + "', original[" + remoteIpHeader + "]='" + concatRemoteIpHeaderValue + "', original[" + protocolHeader + "]='" + (protocolHeader == null ? null : request.getHeader(protocolHeader)) + "' will be seen as newRemoteAddr='" + xRequest.getRemoteAddr() + "', newRemoteHost='" + xRequest.getRemoteHost() + "', newScheme='" + xRequest.getScheme() + "', newSecure='" + xRequest.isSecure() + "', new[" + remoteIpHeader + "]='" + xRequest.getHeader(remoteIpHeader) + "', new[" + proxiesHeader + "]='" + xRequest.getHeader(proxiesHeader) + "'"); } if (requestAttributesEnabled) { request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE, request.getRemoteAddr()); request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE, request.getRemoteHost()); request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE, request.getProtocol()); request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE, Integer.valueOf(request.getServerPort())); } chain.doFilter(xRequest, response); } else { if (log.isDebugEnabled()) { log.debug("Skip RemoteIpFilter for request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "'"); } chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { doFilter((HttpServletRequest)request, (HttpServletResponse)response, chain); } else { chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/WebdavFixFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { chain.doFilter(request, response); return; } HttpServletRequest httpRequest = ((HttpServletRequest) request); HttpServletResponse httpResponse = ((HttpServletResponse) response); String ua = httpRequest.getHeader("User-Agent"); if (ua == null || ua.length() == 0 || !ua.startsWith(UA_MINIDIR_START)) { // No UA or starts with non MS value // Hope everything just works... chain.doFilter(request, response); } else if (ua.startsWith(UA_MINIDIR_5_1_2600)) { // XP 32-bit SP3 - needs redirect with explicit port httpResponse.sendRedirect(buildRedirect(httpRequest)); } else if (ua.startsWith(UA_MINIDIR_5_2_3790)) { // XP 64-bit SP2 if (!"".equals(httpRequest.getContextPath())) { log(request, "XP-x64-SP2 clients only work with the root context"); } // Namespace issue maybe // see http://greenbytes.de/tech/webdav/webdav-redirector-list.html log(request, "XP-x64-SP2 is known not to work with WebDAV Servlet"); chain.doFilter(request, response); } else { // Don't know which MS client it is - try the redirect with an // explicit port in the hope that it moves the client to a different // WebDAV implementation that works httpResponse.sendRedirect(buildRedirect(httpRequest)); } }
// in java/org/apache/catalina/filters/RemoteAddrFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { process(request.getRemoteAddr(), request, response, chain); }
// in java/org/apache/catalina/filters/RemoteAddrFilter.java
Override public void doFilterEvent(CometEvent event, CometFilterChain chain) throws IOException, ServletException { processCometEvent(event.getHttpServletRequest().getRemoteAddr(), event, chain); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ServletResponse wResponse = null; if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; boolean skipNonceCheck = false; if (Constants.METHOD_GET.equals(req.getMethod())) { String path = req.getServletPath(); if (req.getPathInfo() != null) { path = path + req.getPathInfo(); } if (entryPoints.contains(path)) { skipNonceCheck = true; } } @SuppressWarnings("unchecked") LruCache<String> nonceCache = (LruCache<String>) req.getSession(true).getAttribute( Constants.CSRF_NONCE_SESSION_ATTR_NAME); if (!skipNonceCheck) { String previousNonce = req.getParameter(Constants.CSRF_NONCE_REQUEST_PARAM); if (nonceCache != null && !nonceCache.contains(previousNonce)) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } if (nonceCache == null) { nonceCache = new LruCache<String>(nonceCacheSize); req.getSession().setAttribute( Constants.CSRF_NONCE_SESSION_ATTR_NAME, nonceCache); } String newNonce = generateNonce(); nonceCache.add(newNonce); wResponse = new CsrfResponseWrapper(res, newNonce); } else { wResponse = response; } chain.doFilter(request, wResponse); }
// in java/org/apache/catalina/filters/FailedRequestFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!isGoodRequest(request)) { ((HttpServletResponse) response) .sendError(HttpServletResponse.SC_BAD_REQUEST); return; } chain.doFilter(request, response); }
// in java/org/apache/catalina/filters/FailedRequestFilter.java
Override public void doFilterEvent(CometEvent event, CometFilterChain chain) throws IOException, ServletException { if (event.getEventType() == CometEvent.EventType.BEGIN && !isGoodRequest(event.getHttpServletRequest())) { event.getHttpServletResponse().sendError( HttpServletResponse.SC_BAD_REQUEST); event.close(); return; } chain.doFilterEvent(event); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
public static MBeanServerConnection createJMXConnection(String url, String host, String port, String username, String password) throws MalformedURLException, IOException { String urlForJMX; if (url != null) urlForJMX = url; else urlForJMX = JMX_SERVICE_PREFIX + host + ":" + port + JMX_SERVICE_SUFFIX; Map<String, String[]> environment = null; if (username != null && password != null) { String[] credentials = new String[2]; credentials[0] = username; credentials[1] = password; environment = new HashMap<String, String[]>(); environment.put(JMXConnector.CREDENTIALS, credentials); } return JMXConnectorFactory.connect(new JMXServiceURL(urlForJMX), environment).getMBeanServerConnection(); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
protected MBeanServerConnection getJMXConnection() throws MalformedURLException, IOException { MBeanServerConnection jmxServerConnection = null; if (isUseRef()) { Object pref = null ; if(getProject() != null) { pref = getProject().getReference(getRef()); if (pref != null) { try { jmxServerConnection = (MBeanServerConnection) pref; } catch (ClassCastException cce) { getProject().log( "Wrong object reference " + getRef() + " - " + pref.getClass()); return null; } } } if (jmxServerConnection == null) { jmxServerConnection = accessJMXConnection(getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), getRef()); } } else { jmxServerConnection = accessJMXConnection(getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), null); } return jmxServerConnection; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorEqualsCondition.java
protected MBeanServerConnection getJMXConnection() throws MalformedURLException, IOException { return JMXAccessorTask.accessJMXConnection( getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), ref); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorCondition.java
protected MBeanServerConnection getJMXConnection() throws MalformedURLException, IOException { return JMXAccessorTask.accessJMXConnection( getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), ref); }
// in java/org/apache/catalina/websocket/WebSocketServlet.java
Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Information required to send the server handshake message String key; String subProtocol = null; List<String> extensions = Collections.emptyList(); if (!headerContainsToken(req, "upgrade", "websocket")) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (!headerContainsToken(req, "connection", "upgrade")) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (!headerContainsToken(req, "sec-websocket-version", "13")) { resp.setStatus(426); resp.setHeader("Sec-WebSocket-Version", "13"); return; } key = req.getHeader("Sec-WebSocket-Key"); if (key == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } String origin = req.getHeader("Origin"); if (!verifyOrigin(origin)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } List<String> subProtocols = getTokensFromHeader(req, "Sec-WebSocket-Protocol-Client"); if (!subProtocols.isEmpty()) { subProtocol = selectSubProtocol(subProtocols); } // TODO Read client handshake - Sec-WebSocket-Extensions // TODO Extensions require the ability to specify something (API TBD) // that can be passed to the Tomcat internals and process extension // data present when the frame is fragmented. // If we got this far, all is good. Accept the connection. resp.setHeader("Upgrade", "websocket"); resp.setHeader("Connection", "upgrade"); resp.setHeader("Sec-WebSocket-Accept", getWebSocketAccept(key)); if (subProtocol != null) { resp.setHeader("Sec-WebSocket-Protocol", subProtocol); } if (!extensions.isEmpty()) { // TODO } // Small hack until the Servlet API provides a way to do this. StreamInbound inbound = createWebSocketInbound(subProtocol); ((RequestFacade) req).doUpgrade(inbound); }
// in java/org/apache/catalina/websocket/MessageInbound.java
Override protected final void onBinaryData(InputStream is) throws IOException { int read = 0; while (read > -1) { bb.position(bb.position() + read); if (bb.remaining() == 0) { resizeByteBuffer(); } read = is.read(bb.array(), bb.position(), bb.remaining()); } bb.flip(); onBinaryMessage(bb); bb.clear(); }
// in java/org/apache/catalina/websocket/MessageInbound.java
Override protected final void onTextData(Reader r) throws IOException { int read = 0; while (read > -1) { cb.position(cb.position() + read); if (cb.remaining() == 0) { resizeCharBuffer(); } read = r.read(cb.array(), cb.position(), cb.remaining()); } cb.flip(); onTextMessage(cb); cb.clear(); }
// in java/org/apache/catalina/websocket/MessageInbound.java
private void resizeByteBuffer() throws IOException { int maxSize = getByteBufferMaxSize(); if (bb.limit() >= maxSize) { throw new IOException(sm.getString("message.bufferTooSmall")); } long newSize = bb.limit() * 2; if (newSize > maxSize) { newSize = maxSize; } // Cast is safe. newSize < maxSize and maxSize is an int ByteBuffer newBuffer = ByteBuffer.allocate((int) newSize); bb.rewind(); newBuffer.put(bb); bb = newBuffer; }
// in java/org/apache/catalina/websocket/MessageInbound.java
private void resizeCharBuffer() throws IOException { int maxSize = getCharBufferMaxSize(); if (cb.limit() >= maxSize) { throw new IOException(sm.getString("message.bufferTooSmall")); } long newSize = cb.limit() * 2; if (newSize > maxSize) { newSize = maxSize; } // Cast is safe. newSize < maxSize and maxSize is an int CharBuffer newBuffer = CharBuffer.allocate((int) newSize); cb.rewind(); newBuffer.put(cb); cb = newBuffer; }
// in java/org/apache/catalina/websocket/StreamInbound.java
Override public final SocketState onData() throws IOException { // Must be start the start of a message (which may consist of multiple // frames) WsInputStream wsIs = new WsInputStream(processor, getWsOutbound()); try { WsFrame frame = wsIs.nextFrame(true); while (frame != null) { // TODO User defined extensions may define values for rsv if (frame.getRsv() > 0) { closeOutboundConnection( Constants.STATUS_PROTOCOL_ERROR, null); return SocketState.CLOSED; } byte opCode = frame.getOpCode(); if (opCode == Constants.OPCODE_BINARY) { onBinaryData(wsIs); } else if (opCode == Constants.OPCODE_TEXT) { InputStreamReader r = new InputStreamReader(wsIs, new Utf8Decoder()); onTextData(r); } else if (opCode == Constants.OPCODE_CLOSE){ closeOutboundConnection(frame); return SocketState.CLOSED; } else if (opCode == Constants.OPCODE_PING) { getWsOutbound().pong(frame.getPayLoad()); } else if (opCode == Constants.OPCODE_PONG) { // NO-OP } else { // Unknown OpCode closeOutboundConnection( Constants.STATUS_PROTOCOL_ERROR, null); return SocketState.CLOSED; } frame = wsIs.nextFrame(false); } } catch (MalformedInputException mie) { // Invalid UTF-8 closeOutboundConnection(Constants.STATUS_BAD_DATA, null); return SocketState.CLOSED; } catch (UnmappableCharacterException uce) { // Invalid UTF-8 closeOutboundConnection(Constants.STATUS_BAD_DATA, null); return SocketState.CLOSED; } catch (IOException ioe) { // Given something must have gone to reach this point, this // might not work but try it anyway. closeOutboundConnection(Constants.STATUS_PROTOCOL_ERROR, null); return SocketState.CLOSED; } return SocketState.UPGRADED; }
// in java/org/apache/catalina/websocket/StreamInbound.java
private void closeOutboundConnection(int status, ByteBuffer data) throws IOException { try { getWsOutbound().close(status, data); } finally { onClose(status); } }
// in java/org/apache/catalina/websocket/StreamInbound.java
private void closeOutboundConnection(WsFrame frame) throws IOException { try { getWsOutbound().close(frame); } finally { onClose(Constants.OPCODE_CLOSE); } }
// in java/org/apache/catalina/websocket/WsInputStream.java
public WsFrame nextFrame(boolean block) throws IOException { frame = WsFrame.nextFrame(processor, block); if (frame != null) { readThisFragment = 0; remaining = frame.getPayLoadLength(); } return frame; }
// in java/org/apache/catalina/websocket/WsInputStream.java
Override public int read() throws IOException { makePayloadDataAvailable(); if (remaining == 0) { return -1; } remaining--; readThisFragment++; int masked = processor.read(); if(masked == -1) { return -1; } return masked ^ (frame.getMask()[(int) ((readThisFragment - 1) % 4)] & 0xFF); }
// in java/org/apache/catalina/websocket/WsInputStream.java
Override public int read(byte b[], int off, int len) throws IOException { makePayloadDataAvailable(); if (remaining == 0) { return -1; } if (len > remaining) { len = (int) remaining; } int result = processor.read(true, b, off, len); if(result == -1) { return -1; } for (int i = off; i < off + result; i++) { b[i] = (byte) (b[i] ^ frame.getMask()[(int) ((readThisFragment + i - off) % 4)]); } remaining -= result; readThisFragment += result; return result; }
// in java/org/apache/catalina/websocket/WsInputStream.java
private void makePayloadDataAvailable() throws IOException { if (error != null) { throw new IOException(error); } while (remaining == 0 && !frame.getFin()) { // Need more data - process next frame nextFrame(true); while (frame.isControl()) { if (frame.getOpCode() == Constants.OPCODE_PING) { outbound.pong(frame.getPayLoad()); } else if (frame.getOpCode() == Constants.OPCODE_PONG) { // NO-OP. Swallow it. } else if (frame.getOpCode() == Constants.OPCODE_CLOSE) { outbound.close(frame); } else{ throw new IOException(sm.getString("is.unknownOpCode", Byte.valueOf(frame.getOpCode()))); } nextFrame(true); } if (frame.getOpCode() != Constants.OPCODE_CONTINUATION) { error = sm.getString("is.notContinuation", Byte.valueOf(frame.getOpCode())); throw new IOException(error); } } }
// in java/org/apache/catalina/websocket/WsFrame.java
private int blockingRead(UpgradeProcessor<?> processor) throws IOException { int result = processor.read(); if (result == -1) { throw new IOException(sm.getString("frame.eos")); } return result; }
// in java/org/apache/catalina/websocket/WsFrame.java
private void blockingRead(UpgradeProcessor<?> processor, byte[] bytes) throws IOException { int read = 0; int last = 0; while (read < bytes.length) { last = processor.read(true, bytes, read, bytes.length - read); if (last == -1) { throw new IOException(sm.getString("frame.eos")); } read += last; } }
// in java/org/apache/catalina/websocket/WsFrame.java
private void blockingRead(UpgradeProcessor<?> processor, ByteBuffer bb) throws IOException { int last = 0; while (bb.hasRemaining()) { last = processor.read(); if (last == -1) { throw new IOException(sm.getString("frame.eos")); } bb.put((byte) (last ^ mask[bb.position() % 4])); } bb.flip(); }
// in java/org/apache/catalina/websocket/WsFrame.java
public static WsFrame nextFrame(UpgradeProcessor<?> processor, boolean block) throws IOException { byte[] first = new byte[1]; int read = processor.read(block, first, 0, 1); if (read == 1) { return new WsFrame(first[0], processor); } else if (read == 0) { return null; } else if (read == -1) { throw new EOFException(sm.getString("frame.readEos")); } else { throw new IOException( sm.getString("frame.readFailed", Integer.valueOf(read))); } }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeBinaryData(int b) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (bb.position() == bb.capacity()) { doFlush(false); } if (text == null) { text = Boolean.FALSE; } else if (text == Boolean.TRUE) { // Flush the character data flush(); text = Boolean.FALSE; } bb.put((byte) (b & 0xFF)); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeTextData(char c) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (cb.position() == cb.capacity()) { doFlush(false); } if (text == null) { text = Boolean.TRUE; } else if (text == Boolean.FALSE) { // Flush the binary data flush(); text = Boolean.TRUE; } cb.append(c); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeBinaryMessage(ByteBuffer msgBb) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (text != null) { // Empty the buffer flush(); } text = Boolean.FALSE; doWriteBytes(msgBb, true); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void writeTextMessage(CharBuffer msgCb) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (text != null) { // Empty the buffer flush(); } text = Boolean.TRUE; doWriteText(msgCb, true); }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void flush() throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } doFlush(true); }
// in java/org/apache/catalina/websocket/WsOutbound.java
private void doFlush(boolean finalFragment) throws IOException { if (text == null) { // No data return; } if (text.booleanValue()) { cb.flip(); doWriteText(cb, finalFragment); } else { bb.flip(); doWriteBytes(bb, finalFragment); } }
// in java/org/apache/catalina/websocket/WsOutbound.java
protected void close(WsFrame frame) throws IOException { if (frame.getPayLoadLength() > 0) { // Must be status (2 bytes) plus optional message if (frame.getPayLoadLength() == 1) { throw new IOException(); } int status = (frame.getPayLoad().get() & 0xFF) << 8; status += frame.getPayLoad().get() & 0xFF; if (validateCloseStatus(status)) { // Echo the status back to the client close(status, frame.getPayLoad()); } else { // Invalid close code close(Constants.STATUS_PROTOCOL_ERROR, null); } } else { // No status close(0, null); } }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void close(int status, ByteBuffer data) throws IOException { if (closed) { return; } closed = true; upgradeOutbound.write(0x88); if (status == 0) { upgradeOutbound.write(0); } else if (data == null || data.position() == data.limit()) { upgradeOutbound.write(2); upgradeOutbound.write(status >>> 8); upgradeOutbound.write(status); } else { upgradeOutbound.write(2 + data.limit() - data.position()); upgradeOutbound.write(status >>> 8); upgradeOutbound.write(status); upgradeOutbound.write(data.array(), data.position(), data.limit() - data.position()); } upgradeOutbound.flush(); bb = null; cb = null; upgradeOutbound = null; }
// in java/org/apache/catalina/websocket/WsOutbound.java
public synchronized void pong(ByteBuffer data) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } doFlush(true); upgradeOutbound.write(0x8A); if (data == null) { upgradeOutbound.write(0); } else { upgradeOutbound.write(data.limit() - data.position()); upgradeOutbound.write(data.array(), data.position(), data.limit() - data.position()); } upgradeOutbound.flush(); }
// in java/org/apache/catalina/websocket/WsOutbound.java
private void doWriteBytes(ByteBuffer buffer, boolean finalFragment) throws IOException { // Work out the first byte int first = 0x00; if (finalFragment) { first = first + 0x80; } if (firstFrame) { if (text.booleanValue()) { first = first + 0x1; } else { first = first + 0x2; } } // Continuation frame is OpCode 0 upgradeOutbound.write(first); if (buffer.limit() < 126) { upgradeOutbound.write(buffer.limit()); } else if (buffer.limit() < 65536) { upgradeOutbound.write(126); upgradeOutbound.write(buffer.limit() >>> 8); upgradeOutbound.write(buffer.limit() & 0xFF); } else { // Will never be more than 2^31-1 upgradeOutbound.write(127); upgradeOutbound.write(0); upgradeOutbound.write(0); upgradeOutbound.write(0); upgradeOutbound.write(0); upgradeOutbound.write(buffer.limit() >>> 24); upgradeOutbound.write(buffer.limit() >>> 16); upgradeOutbound.write(buffer.limit() >>> 8); upgradeOutbound.write(buffer.limit() & 0xFF); } // Write the content upgradeOutbound.write(buffer.array(), 0, buffer.limit()); upgradeOutbound.flush(); // Reset if (finalFragment) { text = null; firstFrame = true; } else { firstFrame = false; } bb.clear(); }
// in java/org/apache/catalina/websocket/WsOutbound.java
private void doWriteText(CharBuffer buffer, boolean finalFragment) throws IOException { CharsetEncoder encoder = B2CConverter.UTF_8.newEncoder(); do { CoderResult cr = encoder.encode(buffer, bb, true); if (cr.isError()) { cr.throwException(); } bb.flip(); if (buffer.hasRemaining()) { doWriteBytes(bb, false); } else { doWriteBytes(bb, finalFragment); } } while (buffer.hasRemaining()); // Reset - bb will be cleared in doWriteBytes() cb.clear(); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need // By obtaining the command from the pathInfo, per-command security can // be configured in web.xml String command = request.getPathInfo(); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Process the requested command if (command == null || command.equals("/")) { // No command == list } else if (command.equals("/list")) { // List always displayed - nothing to do here } else if (command.equals("/sessions")) { try { doSessions(cn, request, response, smClient); return; } catch (Exception e) { log("HTMLManagerServlet.sessions[" + cn + "]", e); message = smClient.getString("managerServlet.exception", e.toString()); } } else if (command.equals("/upload") || command.equals("/deploy") || command.equals("/reload") || command.equals("/undeploy") || command.equals("/expire") || command.equals("/start") || command.equals("/stop")) { message = smClient.getString("managerServlet.postCommand", command); } else { message = smClient.getString("managerServlet.unknownCommand", command); } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need // By obtaining the command from the pathInfo, per-command security can // be configured in web.xml String command = request.getPathInfo(); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } String deployPath = request.getParameter("deployPath"); ContextName deployCn = null; if (deployPath != null) { deployCn = new ContextName(deployPath, request.getParameter("deployVersion")); } String deployConfig = request.getParameter("deployConfig"); String deployWar = request.getParameter("deployWar"); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; if (command == null || command.length() == 0) { // No command == list // List always displayed -> do nothing } else if (command.equals("/upload")) { message = upload(request, smClient); } else if (command.equals("/deploy")) { message = deployInternal(deployConfig, deployCn, deployWar, smClient); } else if (command.equals("/reload")) { message = reload(cn, smClient); } else if (command.equals("/undeploy")) { message = undeploy(cn, smClient); } else if (command.equals("/expire")) { message = expireSessions(cn, request, smClient); } else if (command.equals("/start")) { message = start(cn, smClient); } else if (command.equals("/stop")) { message = stop(cn, smClient); } else if (command.equals("/findleaks")) { message = findleaks(smClient); } else { // Try GET doGet(request,response); return; } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected String upload(HttpServletRequest request, StringManager smClient) throws IOException, ServletException { String message = ""; Part warPart = null; String filename = null; Collection<Part> parts = request.getParts(); Iterator<Part> iter = parts.iterator(); try { while (iter.hasNext()) { Part part = iter.next(); if (part.getName().equals("deployWar") && warPart == null) { warPart = part; } else { part.delete(); } } while (true) { if (warPart == null) { message = smClient.getString( "htmlManagerServlet.deployUploadNoFile"); break; } filename = extractFilename(warPart.getHeader("Content-Disposition")); if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) { message = smClient.getString( "htmlManagerServlet.deployUploadNotWar", filename); break; } // Get the filename if uploaded name includes a path if (filename.lastIndexOf('\\') >= 0) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (filename.lastIndexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } // Identify the appBase of the owning Host of this Context // (if any) File file = new File(host.getAppBaseFile(), filename); if (file.exists()) { message = smClient.getString( "htmlManagerServlet.deployUploadWarExists", filename); break; } ContextName cn = new ContextName(filename); String name = cn.getName(); if ((host.findChild(name) != null) && !isDeployed(name)) { message = smClient.getString( "htmlManagerServlet.deployUploadInServerXml", filename); break; } if (!isServiced(name)) { addServiced(name); try { warPart.write(file.getAbsolutePath()); // Perform new deployment check(name); } finally { removeServiced(name); } } break; } } catch(Exception e) { message = smClient.getString ("htmlManagerServlet.deployUploadFail", e.getMessage()); log(message, e); } finally { if (warPart != null) { warPart.delete(); } warPart = null; } return message; }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected void list(HttpServletRequest request, HttpServletResponse response, String message, StringManager smClient) throws IOException { if (debug >= 1) log("list: Listing contexts for virtual host '" + host.getName() + "'"); PrintWriter writer = response.getWriter(); // HTML Header Section writer.print(Constants.HTML_HEADER_SECTION); // Body Header Section Object[] args = new Object[2]; args[0] = request.getContextPath(); args[1] = smClient.getString("htmlManagerServlet.title"); writer.print(MessageFormat.format (Constants.BODY_HEADER_SECTION, args)); // Message Section args = new Object[3]; args[0] = smClient.getString("htmlManagerServlet.messageLabel"); if (message == null || message.length() == 0) { args[1] = "OK"; } else { args[1] = RequestUtil.filter(message); } writer.print(MessageFormat.format(Constants.MESSAGE_SECTION, args)); // Manager Section args = new Object[9]; args[0] = smClient.getString("htmlManagerServlet.manager"); args[1] = response.encodeURL(request.getContextPath() + "/html/list"); args[2] = smClient.getString("htmlManagerServlet.list"); args[3] = response.encodeURL (request.getContextPath() + "/" + smClient.getString("htmlManagerServlet.helpHtmlManagerFile")); args[4] = smClient.getString("htmlManagerServlet.helpHtmlManager"); args[5] = response.encodeURL (request.getContextPath() + "/" + smClient.getString("htmlManagerServlet.helpManagerFile")); args[6] = smClient.getString("htmlManagerServlet.helpManager"); args[7] = response.encodeURL (request.getContextPath() + "/status"); args[8] = smClient.getString("statusServlet.title"); writer.print(MessageFormat.format(Constants.MANAGER_SECTION, args)); // Apps Header Section args = new Object[7]; args[0] = smClient.getString("htmlManagerServlet.appsTitle"); args[1] = smClient.getString("htmlManagerServlet.appsPath"); args[2] = smClient.getString("htmlManagerServlet.appsVersion"); args[3] = smClient.getString("htmlManagerServlet.appsName"); args[4] = smClient.getString("htmlManagerServlet.appsAvailable"); args[5] = smClient.getString("htmlManagerServlet.appsSessions"); args[6] = smClient.getString("htmlManagerServlet.appsTasks"); writer.print(MessageFormat.format(APPS_HEADER_SECTION, args)); // Apps Row Section // Create sorted map of deployed applications by context name. Container children[] = host.findChildren(); String contextNames[] = new String[children.length]; for (int i = 0; i < children.length; i++) contextNames[i] = children[i].getName(); Arrays.sort(contextNames); String appsStart = smClient.getString("htmlManagerServlet.appsStart"); String appsStop = smClient.getString("htmlManagerServlet.appsStop"); String appsReload = smClient.getString("htmlManagerServlet.appsReload"); String appsUndeploy = smClient.getString("htmlManagerServlet.appsUndeploy"); String appsExpire = smClient.getString("htmlManagerServlet.appsExpire"); String noVersion = "<i>" + smClient.getString("htmlManagerServlet.noVersion") + "</i>"; boolean isHighlighted = true; boolean isDeployed = true; String highlightColor = null; for (String contextName : contextNames) { Context ctxt = (Context) host.findChild(contextName); if (ctxt != null) { // Bugzilla 34818, alternating row colors isHighlighted = !isHighlighted; if(isHighlighted) { highlightColor = "#C3F3C3"; } else { highlightColor = "#FFFFFF"; } String contextPath = ctxt.getPath(); String displayPath = contextPath; if (displayPath.equals("")) { displayPath = "/"; } StringBuilder tmp = new StringBuilder(); tmp.append("path="); tmp.append(URL_ENCODER.encode(displayPath)); if (ctxt.getWebappVersion().length() > 0) { tmp.append("&version="); tmp.append(URL_ENCODER.encode(ctxt.getWebappVersion())); } String pathVersion = tmp.toString(); try { isDeployed = isDeployed(contextName); } catch (Exception e) { // Assume false on failure for safety isDeployed = false; } args = new Object[7]; args[0] = "<a href=\"" + URL_ENCODER.encode(displayPath) + "\">" + RequestUtil.filter(displayPath) + "</a>"; if ("".equals(ctxt.getWebappVersion())) { args[1] = noVersion; } else { args[1] = RequestUtil.filter(ctxt.getWebappVersion()); } if (ctxt.getDisplayName() == null) { args[2] = "&nbsp;"; } else { args[2] = RequestUtil.filter(ctxt.getDisplayName()); } args[3] = Boolean.valueOf(ctxt.getAvailable()); args[4] = RequestUtil.filter(response.encodeURL(request.getContextPath() + "/html/sessions?" + pathVersion)); Manager manager = ctxt.getManager(); if (manager instanceof DistributedManager && showProxySessions) { args[5] = Integer.valueOf( ((DistributedManager)manager).getActiveSessionsFull()); } else if (ctxt.getManager() != null){ args[5] = Integer.valueOf(manager.getActiveSessions()); } else { args[5] = Integer.valueOf(0); } args[6] = highlightColor; writer.print (MessageFormat.format(APPS_ROW_DETAILS_SECTION, args)); args = new Object[14]; args[0] = RequestUtil.filter(response.encodeURL(request .getContextPath() + "/html/start?" + pathVersion)); args[1] = appsStart; args[2] = RequestUtil.filter(response.encodeURL(request .getContextPath() + "/html/stop?" + pathVersion)); args[3] = appsStop; args[4] = RequestUtil.filter(response.encodeURL(request .getContextPath() + "/html/reload?" + pathVersion)); args[5] = appsReload; args[6] = RequestUtil.filter(response.encodeURL(request .getContextPath() + "/html/undeploy?" + pathVersion)); args[7] = appsUndeploy; args[8] = RequestUtil.filter(response.encodeURL(request .getContextPath() + "/html/expire?" + pathVersion)); args[9] = appsExpire; args[10] = smClient.getString( "htmlManagerServlet.expire.explain"); if (manager == null) { args[11] = smClient.getString( "htmlManagerServlet.noManager"); } else { args[11] = Integer.valueOf( ctxt.getManager().getMaxInactiveInterval()/60); } args[12] = smClient.getString("htmlManagerServlet.expire.unit"); args[13] = highlightColor; if (ctxt.getName().equals(this.context.getName())) { writer.print(MessageFormat.format( MANAGER_APP_ROW_BUTTON_SECTION, args)); } else if (ctxt.getAvailable() && isDeployed) { writer.print(MessageFormat.format( STARTED_DEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } else if (ctxt.getAvailable() && !isDeployed) { writer.print(MessageFormat.format( STARTED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } else if (!ctxt.getAvailable() && isDeployed) { writer.print(MessageFormat.format( STOPPED_DEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } else { writer.print(MessageFormat.format( STOPPED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } } } // Deploy Section args = new Object[7]; args[0] = smClient.getString("htmlManagerServlet.deployTitle"); args[1] = smClient.getString("htmlManagerServlet.deployServer"); args[2] = response.encodeURL(request.getContextPath() + "/html/deploy"); args[3] = smClient.getString("htmlManagerServlet.deployPath"); args[4] = smClient.getString("htmlManagerServlet.deployConfig"); args[5] = smClient.getString("htmlManagerServlet.deployWar"); args[6] = smClient.getString("htmlManagerServlet.deployButton"); writer.print(MessageFormat.format(DEPLOY_SECTION, args)); args = new Object[4]; args[0] = smClient.getString("htmlManagerServlet.deployUpload"); args[1] = response.encodeURL(request.getContextPath() + "/html/upload"); args[2] = smClient.getString("htmlManagerServlet.deployUploadFile"); args[3] = smClient.getString("htmlManagerServlet.deployButton"); writer.print(MessageFormat.format(UPLOAD_SECTION, args)); // Diagnostics section args = new Object[5]; args[0] = smClient.getString("htmlManagerServlet.diagnosticsTitle"); args[1] = smClient.getString("htmlManagerServlet.diagnosticsLeak"); args[2] = response.encodeURL( request.getContextPath() + "/html/findleaks"); args[3] = smClient.getString("htmlManagerServlet.diagnosticsLeakWarning"); args[4] = smClient.getString("htmlManagerServlet.diagnosticsLeakButton"); writer.print(MessageFormat.format(DIAGNOSTICS_SECTION, args)); // Server Header Section args = new Object[9]; args[0] = smClient.getString("htmlManagerServlet.serverTitle"); args[1] = smClient.getString("htmlManagerServlet.serverVersion"); args[2] = smClient.getString("htmlManagerServlet.serverJVMVersion"); args[3] = smClient.getString("htmlManagerServlet.serverJVMVendor"); args[4] = smClient.getString("htmlManagerServlet.serverOSName"); args[5] = smClient.getString("htmlManagerServlet.serverOSVersion"); args[6] = smClient.getString("htmlManagerServlet.serverOSArch"); args[7] = sm.getString("htmlManagerServlet.serverHostname"); args[8] = sm.getString("htmlManagerServlet.serverIPAddress"); writer.print(MessageFormat.format (Constants.SERVER_HEADER_SECTION, args)); // Server Row Section args = new Object[8]; args[0] = ServerInfo.getServerInfo(); args[1] = System.getProperty("java.runtime.version"); args[2] = System.getProperty("java.vm.vendor"); args[3] = System.getProperty("os.name"); args[4] = System.getProperty("os.version"); args[5] = System.getProperty("os.arch"); try { InetAddress address = InetAddress.getLocalHost(); args[6] = address.getHostName(); args[7] = address.getHostAddress(); } catch (UnknownHostException e) { args[6] = "-"; args[7] = "-"; } writer.print(MessageFormat.format(Constants.SERVER_ROW_SECTION, args)); // HTML Tail Section writer.print(Constants.HTML_TAIL_SECTION); // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected void doSessions(ContextName cn, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { req.setAttribute("path", cn.getPath()); req.setAttribute("version", cn.getVersion()); String action = req.getParameter("action"); if (debug >= 1) { log("sessions: Session action '" + action + "' for web application '" + cn.getDisplayName() + "'"); } if ("sessionDetail".equals(action)) { String sessionId = req.getParameter("sessionId"); displaySessionDetailPage(req, resp, cn, sessionId, smClient); return; } else if ("invalidateSessions".equals(action)) { String[] sessionIds = req.getParameterValues("sessionIds"); int i = invalidateSessions(cn, sessionIds, smClient); req.setAttribute(APPLICATION_MESSAGE, "" + i + " sessions invalidated."); } else if ("removeSessionAttribute".equals(action)) { String sessionId = req.getParameter("sessionId"); String name = req.getParameter("attributeName"); boolean removed = removeSessionAttribute(cn, sessionId, name, smClient); String outMessage = removed ? "Session attribute '" + name + "' removed." : "Session did not contain any attribute named '" + name + "'"; req.setAttribute(APPLICATION_MESSAGE, outMessage); displaySessionDetailPage(req, resp, cn, sessionId, smClient); return; } // else displaySessionsListPage(cn, req, resp, smClient); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected void displaySessionsListPage(ContextName cn, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { List<Session> sessions = getSessionsForName(cn, smClient); String sortBy = req.getParameter("sort"); String orderBy = null; if (null != sortBy && !"".equals(sortBy.trim())) { Comparator<Session> comparator = getComparator(sortBy); if (comparator != null) { orderBy = req.getParameter("order"); if ("DESC".equalsIgnoreCase(orderBy)) { comparator = new ReverseComparator(comparator); orderBy = "ASC"; } else { orderBy = "DESC"; } try { Collections.sort(sessions, comparator); } catch (IllegalStateException ise) { // at least 1 of the sessions is invalidated req.setAttribute(APPLICATION_ERROR, "Can't sort session list: one session is invalidated"); } } else { log("WARNING: unknown sort order: " + sortBy); } } // keep sort order req.setAttribute("sort", sortBy); req.setAttribute("order", orderBy); req.setAttribute("activeSessions", sessions); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now getServletContext().getRequestDispatcher(sessionsListJspPath).include(req, resp); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected void displaySessionDetailPage(HttpServletRequest req, HttpServletResponse resp, ContextName cn, String sessionId, StringManager smClient) throws ServletException, IOException { Session session = getSessionForNameAndId(cn, sessionId, smClient); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now req.setAttribute("currentSession", session); getServletContext().getRequestDispatcher(resp.encodeURL(sessionDetailJspPath)).include(req, resp); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected int invalidateSessions(ContextName cn, String[] sessionIds, StringManager smClient) throws IOException { if (null == sessionIds) { return 0; } int nbAffectedSessions = 0; for (int i = 0; i < sessionIds.length; ++i) { String sessionId = sessionIds[i]; HttpSession session = getSessionForNameAndId(cn, sessionId, smClient).getSession(); if (null == session) { // Shouldn't happen, but let's play nice... if (debug >= 1) { log("WARNING: can't invalidate null session " + sessionId); } continue; } try { session.invalidate(); ++nbAffectedSessions; if (debug >= 1) { log("Invalidating session id " + sessionId); } } catch (IllegalStateException ise) { if (debug >= 1) { log("Can't invalidate already invalidated session id " + sessionId); } } } return nbAffectedSessions; }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected boolean removeSessionAttribute(ContextName cn, String sessionId, String attributeName, StringManager smClient) throws IOException { HttpSession session = getSessionForNameAndId(cn, sessionId, smClient).getSession(); if (null == session) { // Shouldn't happen, but let's play nice... if (debug >= 1) { log("WARNING: can't remove attribute '" + attributeName + "' for null session " + sessionId); } return false; } boolean wasPresent = (null != session.getAttribute(attributeName)); try { session.removeAttribute(attributeName); } catch (IllegalStateException ise) { if (debug >= 1) { log("Can't remote attribute '" + attributeName + "' for invalidated session id " + sessionId); } } return wasPresent; }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); PrintWriter writer = response.getWriter(); if( mBeanServer==null ) { writer.println("Error - No mbean server"); return; } String qry=request.getParameter("set"); if( qry!= null ) { String name=request.getParameter("att"); String val=request.getParameter("val"); setAttribute( writer, qry, name, val ); return; } qry=request.getParameter("get"); if( qry!= null ) { String name=request.getParameter("att"); getAttribute( writer, qry, name, request.getParameter("key") ); return; } qry = request.getParameter("invoke"); if(qry != null) { String opName=request.getParameter("op"); String ps = request.getParameter("ps"); String[] valuesStr; if (ps == null) { valuesStr = new String[0]; } else { valuesStr = ps.split(","); } invokeOperation( writer, qry, opName,valuesStr ); return; } qry=request.getParameter("qry"); if( qry == null ) { qry = "*:*"; } listBeans( writer, qry ); }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null) command = request.getServletPath(); String name = request.getParameter("name"); // Prepare our output writer to generate the response message response.setContentType("text/plain; charset=" + Constants.CHARSET); PrintWriter writer = response.getWriter(); // Process the requested command if (command == null) { writer.println(sm.getString("hostManagerServlet.noCommand")); } else if (command.equals("/add")) { add(request, writer, name, false, smClient); } else if (command.equals("/remove")) { remove(writer, name, smClient); } else if (command.equals("/list")) { list(writer, smClient); } else if (command.equals("/start")) { start(writer, name, smClient); } else if (command.equals("/stop")) { stop(writer, name, smClient); } else { writer.println(sm.getString("hostManagerServlet.unknownCommand", command)); } // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/host/HTMLHostManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Process the requested command if (command == null) { // No command == list } else if (command.equals("/list")) { // Nothing to do - always generate list } else if (command.equals("/add") || command.equals("/remove") || command.equals("/start") || command.equals("/stop")) { message = smClient.getString( "hostManagerServlet.postCommand", command); } else { message = smClient.getString( "hostManagerServlet.unknownCommand", command); } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/host/HTMLHostManagerServlet.java
Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); String name = request.getParameter("name"); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Process the requested command if (command == null) { // No command == list } else if (command.equals("/add")) { message = add(request, name, smClient); } else if (command.equals("/remove")) { message = remove(name, smClient); } else if (command.equals("/start")) { message = start(name, smClient); } else if (command.equals("/stop")) { message = stop(name, smClient); } else { //Try GET doGet(request, response); } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/host/HTMLHostManagerServlet.java
public void list(HttpServletRequest request, HttpServletResponse response, String message, StringManager smClient) throws IOException { if (debug >= 1) { log(sm.getString("hostManagerServlet.list", engine.getName())); } PrintWriter writer = response.getWriter(); // HTML Header Section writer.print(org.apache.catalina.manager.Constants.HTML_HEADER_SECTION); // Body Header Section Object[] args = new Object[2]; args[0] = request.getContextPath(); args[1] = smClient.getString("htmlHostManagerServlet.title"); writer.print(MessageFormat.format (Constants.BODY_HEADER_SECTION, args)); // Message Section args = new Object[3]; args[0] = smClient.getString("htmlHostManagerServlet.messageLabel"); if (message == null || message.length() == 0) { args[1] = "OK"; } else { args[1] = RequestUtil.filter(message); } writer.print(MessageFormat.format(Constants.MESSAGE_SECTION, args)); // Manager Section args = new Object[9]; args[0] = smClient.getString("htmlHostManagerServlet.manager"); args[1] = response.encodeURL(request.getContextPath() + "/html/list"); args[2] = smClient.getString("htmlHostManagerServlet.list"); args[3] = response.encodeURL (request.getContextPath() + "/" + smClient.getString("htmlHostManagerServlet.helpHtmlManagerFile")); args[4] = smClient.getString("htmlHostManagerServlet.helpHtmlManager"); args[5] = response.encodeURL (request.getContextPath() + "/" + smClient.getString("htmlHostManagerServlet.helpManagerFile")); args[6] = smClient.getString("htmlHostManagerServlet.helpManager"); args[7] = response.encodeURL("/manager/status"); args[8] = smClient.getString("statusServlet.title"); writer.print(MessageFormat.format(Constants.MANAGER_SECTION, args)); // Hosts Header Section args = new Object[3]; args[0] = smClient.getString("htmlHostManagerServlet.hostName"); args[1] = smClient.getString("htmlHostManagerServlet.hostAliases"); args[2] = smClient.getString("htmlHostManagerServlet.hostTasks"); writer.print(MessageFormat.format(HOSTS_HEADER_SECTION, args)); // Hosts Row Section // Create sorted map of host names. Container[] children = engine.findChildren(); String hostNames[] = new String[children.length]; for (int i = 0; i < children.length; i++) hostNames[i] = children[i].getName(); TreeMap<String,String> sortedHostNamesMap = new TreeMap<String,String>(); for (int i = 0; i < hostNames.length; i++) { String displayPath = hostNames[i]; sortedHostNamesMap.put(displayPath, hostNames[i]); } String hostsStart = smClient.getString("htmlHostManagerServlet.hostsStart"); String hostsStop = smClient.getString("htmlHostManagerServlet.hostsStop"); String hostsRemove = smClient.getString("htmlHostManagerServlet.hostsRemove"); Iterator<Map.Entry<String,String>> iterator = sortedHostNamesMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String,String> entry = iterator.next(); String hostName = entry.getKey(); Host host = (Host) engine.findChild(hostName); if (host != null ) { args = new Object[2]; args[0] = RequestUtil.filter(hostName); String[] aliases = host.findAliases(); StringBuilder buf = new StringBuilder(); if (aliases.length > 0) { buf.append(aliases[0]); for (int j = 1; j < aliases.length; j++) { buf.append(", ").append(aliases[j]); } } if (buf.length() == 0) { buf.append("&nbsp;"); args[1] = buf.toString(); } else { args[1] = RequestUtil.filter(buf.toString()); } writer.print (MessageFormat.format(HOSTS_ROW_DETAILS_SECTION, args)); args = new Object[4]; if (host.getState().isAvailable()) { args[0] = response.encodeURL (request.getContextPath() + "/html/stop?name=" + URLEncoder.encode(hostName, "UTF-8")); args[1] = hostsStop; } else { args[0] = response.encodeURL (request.getContextPath() + "/html/start?name=" + URLEncoder.encode(hostName, "UTF-8")); args[1] = hostsStart; } args[2] = response.encodeURL (request.getContextPath() + "/html/remove?name=" + URLEncoder.encode(hostName, "UTF-8")); args[3] = hostsRemove; if (host == this.installedHost) { writer.print(MessageFormat.format( MANAGER_HOST_ROW_BUTTON_SECTION, args)); } else { writer.print(MessageFormat.format( HOSTS_ROW_BUTTON_SECTION, args)); } } } // Add Section args = new Object[6]; args[0] = smClient.getString("htmlHostManagerServlet.addTitle"); args[1] = smClient.getString("htmlHostManagerServlet.addHost"); args[2] = response.encodeURL(request.getContextPath() + "/html/add"); args[3] = smClient.getString("htmlHostManagerServlet.addName"); args[4] = smClient.getString("htmlHostManagerServlet.addAliases"); args[5] = smClient.getString("htmlHostManagerServlet.addAppBase"); writer.print(MessageFormat.format(ADD_SECTION_START, args)); args = new Object[3]; args[0] = smClient.getString("htmlHostManagerServlet.addAutoDeploy"); args[1] = "autoDeploy"; args[2] = "checked"; writer.print(MessageFormat.format(ADD_SECTION_BOOLEAN, args)); args[0] = smClient.getString( "htmlHostManagerServlet.addDeployOnStartup"); args[1] = "deployOnStartup"; args[2] = "checked"; writer.print(MessageFormat.format(ADD_SECTION_BOOLEAN, args)); args[0] = smClient.getString("htmlHostManagerServlet.addDeployXML"); args[1] = "deployXML"; args[2] = "checked"; writer.print(MessageFormat.format(ADD_SECTION_BOOLEAN, args)); args[0] = smClient.getString("htmlHostManagerServlet.addUnpackWARs"); args[1] = "unpackWARs"; args[2] = "checked"; writer.print(MessageFormat.format(ADD_SECTION_BOOLEAN, args)); args[0] = smClient.getString("htmlHostManagerServlet.addManager"); args[1] = "manager"; args[2] = "checked"; writer.print(MessageFormat.format(ADD_SECTION_BOOLEAN, args)); args = new Object[1]; args[0] = smClient.getString("htmlHostManagerServlet.addButton"); writer.print(MessageFormat.format(ADD_SECTION_END, args)); // Server Header Section args = new Object[7]; args[0] = smClient.getString("htmlHostManagerServlet.serverTitle"); args[1] = smClient.getString("htmlHostManagerServlet.serverVersion"); args[2] = smClient.getString("htmlHostManagerServlet.serverJVMVersion"); args[3] = smClient.getString("htmlHostManagerServlet.serverJVMVendor"); args[4] = smClient.getString("htmlHostManagerServlet.serverOSName"); args[5] = smClient.getString("htmlHostManagerServlet.serverOSVersion"); args[6] = smClient.getString("htmlHostManagerServlet.serverOSArch"); writer.print(MessageFormat.format (Constants.SERVER_HEADER_SECTION, args)); // Server Row Section args = new Object[6]; args[0] = ServerInfo.getServerInfo(); args[1] = System.getProperty("java.runtime.version"); args[2] = System.getProperty("java.vm.vendor"); args[3] = System.getProperty("os.name"); args[4] = System.getProperty("os.version"); args[5] = System.getProperty("os.arch"); writer.print(MessageFormat.format(Constants.SERVER_ROW_SECTION, args)); // HTML Tail Section writer.print(Constants.HTML_TAIL_SECTION); // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // mode is flag for HTML or XML output int mode = 0; // if ?XML=true, set the mode to XML if (request.getParameter("XML") != null && request.getParameter("XML").equals("true")) { mode = 1; } StatusTransformer.setContentType(response, mode); PrintWriter writer = response.getWriter(); boolean completeStatus = false; if ((request.getPathInfo() != null) && (request.getPathInfo().equals("/all"))) { completeStatus = true; } // use StatusTransformer to output status Object[] args = new Object[1]; args[0] = request.getContextPath(); StatusTransformer.writeHeader(writer,args,mode); // Body Header Section args = new Object[2]; args[0] = request.getContextPath(); if (completeStatus) { args[1] = sm.getString("statusServlet.complete"); } else { args[1] = sm.getString("statusServlet.title"); } // use StatusTransformer to output status StatusTransformer.writeBody(writer,args,mode); // Manager Section args = new Object[9]; args[0] = sm.getString("htmlManagerServlet.manager"); args[1] = response.encodeURL(request.getContextPath() + "/html/list"); args[2] = sm.getString("htmlManagerServlet.list"); args[3] = response.encodeURL (request.getContextPath() + "/" + sm.getString("htmlManagerServlet.helpHtmlManagerFile")); args[4] = sm.getString("htmlManagerServlet.helpHtmlManager"); args[5] = response.encodeURL (request.getContextPath() + "/" + sm.getString("htmlManagerServlet.helpManagerFile")); args[6] = sm.getString("htmlManagerServlet.helpManager"); if (completeStatus) { args[7] = response.encodeURL (request.getContextPath() + "/status"); args[8] = sm.getString("statusServlet.title"); } else { args[7] = response.encodeURL (request.getContextPath() + "/status/all"); args[8] = sm.getString("statusServlet.complete"); } // use StatusTransformer to output status StatusTransformer.writeManager(writer,args,mode); // Server Header Section args = new Object[9]; args[0] = sm.getString("htmlManagerServlet.serverTitle"); args[1] = sm.getString("htmlManagerServlet.serverVersion"); args[2] = sm.getString("htmlManagerServlet.serverJVMVersion"); args[3] = sm.getString("htmlManagerServlet.serverJVMVendor"); args[4] = sm.getString("htmlManagerServlet.serverOSName"); args[5] = sm.getString("htmlManagerServlet.serverOSVersion"); args[6] = sm.getString("htmlManagerServlet.serverOSArch"); args[7] = sm.getString("htmlManagerServlet.serverHostname"); args[8] = sm.getString("htmlManagerServlet.serverIPAddress"); // use StatusTransformer to output status StatusTransformer.writePageHeading(writer,args,mode); // Server Row Section args = new Object[8]; args[0] = ServerInfo.getServerInfo(); args[1] = System.getProperty("java.runtime.version"); args[2] = System.getProperty("java.vm.vendor"); args[3] = System.getProperty("os.name"); args[4] = System.getProperty("os.version"); args[5] = System.getProperty("os.arch"); try { InetAddress address = InetAddress.getLocalHost(); args[6] = address.getHostName(); args[7] = address.getHostAddress(); } catch (UnknownHostException e) { args[6] = "-"; args[7] = "-"; } // use StatusTransformer to output status StatusTransformer.writeServerInfo(writer, args, mode); try { // Display operating system statistics using APR if available StatusTransformer.writeOSState(writer,mode); // Display virtual machine statistics StatusTransformer.writeVMState(writer,mode); Enumeration<ObjectName> enumeration = threadPools.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); String name = objectName.getKeyProperty("name"); // use StatusTransformer to output status StatusTransformer.writeConnectorState (writer, objectName, name, mBeanServer, globalRequestProcessors, requestProcessors, mode); } if ((request.getPathInfo() != null) && (request.getPathInfo().equals("/all"))) { // Note: Retrieving the full status is much slower // use StatusTransformer to output status StatusTransformer.writeDetailedState (writer, mBeanServer, mode); } } catch (Exception e) { throw new ServletException(e); } // use StatusTransformer to output status StatusTransformer.writeFooter(writer, mode); }
// in java/org/apache/catalina/manager/ManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null) command = request.getServletPath(); String config = request.getParameter("config"); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } String type = request.getParameter("type"); String war = request.getParameter("war"); String tag = request.getParameter("tag"); boolean update = false; if ((request.getParameter("update") != null) && (request.getParameter("update").equals("true"))) { update = true; } boolean statusLine = false; if ("true".equals(request.getParameter("statusLine"))) { statusLine = true; } // Prepare our output writer to generate the response message response.setContentType("text/plain; charset=" + Constants.CHARSET); PrintWriter writer = response.getWriter(); // Process the requested command (note - "/deploy" is not listed here) if (command == null) { writer.println(smClient.getString("managerServlet.noCommand")); } else if (command.equals("/deploy")) { if (war != null || config != null) { deploy(writer, config, cn, war, update, smClient); } else { deploy(writer, cn, tag, smClient); } } else if (command.equals("/list")) { list(writer, smClient); } else if (command.equals("/reload")) { reload(writer, cn, smClient); } else if (command.equals("/resources")) { resources(writer, type, smClient); } else if (command.equals("/save")) { save(writer, path, smClient); } else if (command.equals("/serverinfo")) { serverinfo(writer, smClient); } else if (command.equals("/sessions")) { expireSessions(writer, cn, request, smClient); } else if (command.equals("/expire")) { expireSessions(writer, cn, request, smClient); } else if (command.equals("/start")) { start(writer, cn, smClient); } else if (command.equals("/stop")) { stop(writer, cn, smClient); } else if (command.equals("/undeploy")) { undeploy(writer, cn, smClient); } else if (command.equals("/findleaks")) { findleaks(statusLine, writer, smClient); } else { writer.println(smClient.getString("managerServlet.unknownCommand", command)); } // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
Override public void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null) command = request.getServletPath(); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } String tag = request.getParameter("tag"); boolean update = false; if ((request.getParameter("update") != null) && (request.getParameter("update").equals("true"))) { update = true; } // Prepare our output writer to generate the response message response.setContentType("text/plain;charset="+Constants.CHARSET); PrintWriter writer = response.getWriter(); // Process the requested command if (command == null) { writer.println(smClient.getString("managerServlet.noCommand")); } else if (command.equals("/deploy")) { deploy(writer, cn, tag, update, request, smClient); } else { writer.println(smClient.getString("managerServlet.unknownCommand", command)); } // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
protected void uploadWar(PrintWriter writer, HttpServletRequest request, File war, StringManager smClient) throws IOException { if (war.exists() && !war.delete()) { String msg = smClient.getString("managerServlet.deleteFail", war); throw new IOException(msg); } ServletInputStream istream = null; BufferedOutputStream ostream = null; try { istream = request.getInputStream(); ostream = new BufferedOutputStream(new FileOutputStream(war), 1024); byte buffer[] = new byte[1024]; while (true) { int n = istream.read(buffer); if (n < 0) { break; } ostream.write(buffer, 0, n); } ostream.flush(); ostream.close(); ostream = null; istream.close(); istream = null; } catch (IOException e) { if (war.exists() && !war.delete()) { writer.println( smClient.getString("managerServlet.deleteFail", war)); } throw e; } finally { if (ostream != null) { try { ostream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } ostream = null; } if (istream != null) { try { istream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } istream = null; } } }
// in java/org/apache/catalina/tribes/group/RpcMessage.java
Override public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException { reply = in.readBoolean(); int length = in.readInt(); uuid = new byte[length]; in.readFully(uuid); length = in.readInt(); rpcId = new byte[length]; in.readFully(rpcId); message = (Serializable)in.readObject(); }
// in java/org/apache/catalina/tribes/group/RpcMessage.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeBoolean(reply); out.writeInt(uuid.length); out.write(uuid, 0, uuid.length); out.writeInt(rpcId.length); out.write(rpcId, 0, rpcId.length); out.writeObject(message); }
// in java/org/apache/catalina/tribes/group/RpcMessage.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { reply = true; int length = in.readInt(); uuid = new byte[length]; in.readFully(uuid); length = in.readInt(); rpcId = new byte[length]; in.readFully(rpcId); }
// in java/org/apache/catalina/tribes/group/RpcMessage.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(uuid.length); out.write(uuid, 0, uuid.length); out.writeInt(rpcId.length); out.write(rpcId, 0, rpcId.length); }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
public static byte[] compress(byte[] data) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); GZIPOutputStream gout = new GZIPOutputStream(bout); gout.write(data); gout.flush(); gout.close(); return bout.toByteArray(); }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
public static byte[] decompress(byte[] data) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE); ByteArrayInputStream bin = new ByteArrayInputStream(data); GZIPInputStream gin = new GZIPInputStream(bin); byte[] tmp = new byte[DEFAULT_BUFFER_SIZE]; int length = gin.read(tmp); while (length > -1) { bout.write(tmp, 0, length); length = gin.read(tmp); } return bout.toByteArray(); }
// in java/org/apache/catalina/tribes/ByteMessage.java
Override public void readExternal(ObjectInput in ) throws IOException { int length = in.readInt(); message = new byte[length]; in.readFully(message); }
// in java/org/apache/catalina/tribes/ByteMessage.java
Override public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(message!=null?message.length:0); if ( message!=null ) out.write(message,0,message.length); }
// in java/org/apache/catalina/tribes/io/ObjectReader.java
public int append(ByteBuffer data, int len, boolean count) throws java.io.IOException { buffer.append(data,len); int pkgCnt = -1; if ( count ) pkgCnt = buffer.countPackages(); return pkgCnt; }
// in java/org/apache/catalina/tribes/io/ObjectReader.java
public ChannelMessage[] execute() throws java.io.IOException { int pkgCnt = buffer.countPackages(); ChannelMessage[] result = new ChannelMessage[pkgCnt]; for (int i=0; i<pkgCnt; i++) { ChannelMessage data = buffer.extractPackage(true); result[i] = data; } return result; }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data) throws IOException, ClassNotFoundException, ClassCastException { return deserialize(data,0,data.length); }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data, int offset, int length) throws IOException, ClassNotFoundException, ClassCastException { return deserialize(data,offset,length,null); }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static Serializable deserialize(byte[] data, int offset, int length, ClassLoader[] cls) throws IOException, ClassNotFoundException, ClassCastException { invokecount.addAndGet(1); Object message = null; if ( cls == null ) cls = new ClassLoader[0]; if (data != null && length > 0) { InputStream instream = new ByteArrayInputStream(data,offset,length); ObjectInputStream stream = null; stream = (cls.length>0)? new ReplicationStream(instream,cls):new ObjectInputStream(instream); message = stream.readObject(); instream.close(); stream.close(); } if ( message == null ) { return null; } else if (message instanceof Serializable) return (Serializable) message; else { throw new ClassCastException("Message has the wrong class. It should implement Serializable, instead it is:"+message.getClass().getName()); } }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public static byte[] serialize(Serializable msg) throws IOException { ByteArrayOutputStream outs = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(outs); out.writeObject(msg); out.flush(); byte[] data = outs.toByteArray(); return data; }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
Override public Class<?> resolveClass(ObjectStreamClass classDesc) throws ClassNotFoundException, IOException { String name = classDesc.getName(); try { return resolveClass(name); } catch (ClassNotFoundException e) { return super.resolveClass(classDesc); } }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
Override protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { ClassLoader latestLoader = (classLoaders!=null && classLoaders.length==0)?null:classLoaders[0]; ClassLoader nonPublicLoader = null; boolean hasNonPublicInterface = false; // define proxy in class loader of non-public interface(s), if any Class<?>[] classObjs = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { Class<?> cl = this.resolveClass(interfaces[i]); if (latestLoader==null) latestLoader = cl.getClassLoader(); if ((cl.getModifiers() & Modifier.PUBLIC) == 0) { if (hasNonPublicInterface) { if (nonPublicLoader != cl.getClassLoader()) { throw new IllegalAccessError( "conflicting non-public interface class loaders"); } } else { nonPublicLoader = cl.getClassLoader(); hasNonPublicInterface = true; } } classObjs[i] = cl; } try { return Proxy.getProxyClass(hasNonPublicInterface ? nonPublicLoader : latestLoader, classObjs); } catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); } }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
Override public void close() throws IOException { this.classLoaders = null; super.close(); }
// in java/org/apache/catalina/tribes/io/DirectByteArrayOutputStream.java
Override public void write(int b) throws IOException { buffer.append((byte)b); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
Override public void connect() throws IOException { openSocket(); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
public void sendMessage(byte[] data, boolean waitForAck) throws IOException { IOException exception = null; setAttempt(0); try { // first try with existing connection pushMessage(data,false,waitForAck); } catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } } finally { setRequestCount(getRequestCount()+1); keepalive(); if ( exception != null ) throw exception; } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
protected void openSocket() throws IOException { if(isConnected()) return ; try { socket = new Socket(); InetSocketAddress sockaddr = new InetSocketAddress(getAddress(), getPort()); socket.connect(sockaddr,(int)getTimeout()); socket.setSendBufferSize(getTxBufSize()); socket.setReceiveBufferSize(getRxBufSize()); socket.setSoTimeout( (int) getTimeout()); socket.setTcpNoDelay(getTcpNoDelay()); socket.setKeepAlive(getSoKeepAlive()); socket.setReuseAddress(getSoReuseAddress()); socket.setOOBInline(getOoBInline()); socket.setSoLinger(getSoLingerOn(),getSoLingerTime()); socket.setTrafficClass(getSoTrafficClass()); setConnected(true); soOut = socket.getOutputStream(); soIn = socket.getInputStream(); setRequestCount(0); setConnectTime(System.currentTimeMillis()); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket", getAddress().getHostAddress(), new Integer(getPort()), new Long(0))); } catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
protected void pushMessage(byte[] data, boolean reconnect, boolean waitForAck) throws IOException { keepalive(); if ( reconnect ) closeSocket(); if (!isConnected()) openSocket(); soOut.write(data); soOut.flush(); if (waitForAck) waitForAck(); SenderState.getSenderState(getDestination()).setReady(); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
protected void waitForAck() throws java.io.IOException { try { boolean ackReceived = false; boolean failAckReceived = false; ackbuf.clear(); int bytesRead = 0; int i = soIn.read(); while ((i != -1) && (bytesRead < Constants.ACK_COMMAND.length)) { bytesRead++; byte d = (byte)i; ackbuf.append(d); if (ackbuf.doesPackageExist() ) { byte[] ackcmd = ackbuf.extractDataPackage(true).getBytes(); ackReceived = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.ACK_DATA); failAckReceived = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA); ackReceived = ackReceived || failAckReceived; break; } i = soIn.read(); } if (!ackReceived) { if (i == -1) throw new IOException(sm.getString("IDataSender.ack.eof",getAddress(), new Integer(socket.getLocalPort()))); else throw new IOException(sm.getString("IDataSender.ack.wrong",getAddress(), new Integer(socket.getLocalPort()))); } else if ( failAckReceived && getThrowOnFailedAck()) { throw new RemoteProcessException("Received a failed ack:org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA"); } } catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; } finally { ackbuf.clear(); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
Override public void start() throws IOException { super.start(); try { setPool(new RxTaskPool(getMaxThreads(),getMinThreads(),this)); } catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } try { getBind(); bind(); Thread t = new Thread(this, "BioReceiver"); t.setDaemon(true); t.start(); } catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } }
// in java/org/apache/catalina/tribes/transport/bio/BioReceiver.java
protected void bind() throws IOException { // allocate an unbound server socket channel serverSocket = new ServerSocket(); // set the port the server channel will listen to //serverSocket.bind(new InetSocketAddress(getBind(), getTcpListenPort())); bind(serverSocket,getPort(),getAutoBind()); }
// in java/org/apache/catalina/tribes/transport/bio/MultipointBioSender.java
Override public void connect() throws IOException { //do nothing, we connect on demand setConnected(true); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
Override public void start() throws IOException { if ( executor == null ) { //executor = new ThreadPoolExecutor(minThreads,maxThreads,60,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>()); TaskThreadFactory tf = new TaskThreadFactory("Tribes-Task-Receiver-"); executor = ExecutorFactory.newThreadPool(minThreads, maxThreads, maxIdleTime, TimeUnit.MILLISECONDS, tf); } }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
protected void bind(ServerSocket socket, int portstart, int retries) throws IOException { synchronized (bindLock) { InetSocketAddress addr = null; int port = portstart; while (retries > 0) { try { addr = new InetSocketAddress(getBind(), port); socket.bind(addr); setPort(port); log.info("Receiver Server Socket bound to:"+addr); retries = 0; } catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind server socket to:" + addr + " throwing error."); throw x; } port++; } } } }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
protected int bindUdp(DatagramSocket socket, int portstart, int retries) throws IOException { InetSocketAddress addr = null; while ( retries > 0 ) { try { addr = new InetSocketAddress(getBind(), portstart); socket.bind(addr); setUdpPort(portstart); log.info("UDP Receiver Server Socket bound to:"+addr); return 0; }catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); } } return retries; }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
public boolean process(SelectionKey key, boolean waitForAck) throws IOException { int ops = key.readyOps(); key.interestOps(key.interestOps() & ~ops); //in case disconnect has been called if ((!isConnected()) && (!connecting)) throw new IOException("Sender has been disconnected, can't selection key."); if ( !key.isValid() ) throw new IOException("Key is not valid, it must have been cancelled."); if ( key.isConnectable() ) { if ( socketChannel.finishConnect() ) { completeConnect(); if ( current != null ) key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); return false; } else { //wait for the connection to finish key.interestOps(key.interestOps() | SelectionKey.OP_CONNECT); return false; }//end if } else if ( key.isWritable() ) { boolean writecomplete = write(); if ( writecomplete ) { //we are completed, should we read an ack? if ( waitForAck ) { //register to read the ack key.interestOps(key.interestOps() | SelectionKey.OP_READ); } else { //if not, we are ready, setMessage will reregister us for another write interest //do a health check, we have no way of verify a disconnected //socket since we don't register for OP_READ on waitForAck=false read();//this causes overhead setRequestCount(getRequestCount()+1); return true; } } else { //we are not complete, lets write some more key.interestOps(key.interestOps()|SelectionKey.OP_WRITE); }//end if } else if ( key.isReadable() ) { boolean readcomplete = read(); if ( readcomplete ) { setRequestCount(getRequestCount()+1); return true; } else { key.interestOps(key.interestOps() | SelectionKey.OP_READ); }//end if } else { //unknown state, should never happen log.warn("Data is in unknown state. readyOps="+ops); throw new IOException("Data is in unknown state. readyOps="+ops); }//end if return false; }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
protected boolean read() throws IOException { //if there is no message here, we are done if ( current == null ) return true; int read = isUdpBased()?dataChannel.read(readbuf) : socketChannel.read(readbuf); //end of stream if ( read == -1 ) throw new IOException("Unable to receive an ack message. EOF on socket channel has been reached."); //no data read else if ( read == 0 ) return false; readbuf.flip(); ackbuf.append(readbuf,read); readbuf.clear(); if (ackbuf.doesPackageExist() ) { byte[] ackcmd = ackbuf.extractDataPackage(true).getBytes(); boolean ack = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.ACK_DATA); boolean fack = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA); if ( fack && getThrowOnFailedAck() ) throw new RemoteProcessException("Received a failed ack:org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA"); return ack || fack; } else { return false; } }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
protected boolean write() throws IOException { if ( (!isConnected()) || (this.socketChannel==null && this.dataChannel==null)) { throw new IOException("NioSender is not connected, this should not occur."); } if ( current != null ) { if ( remaining > 0 ) { //we have written everything, or we are starting a new package //protect against buffer overwrite int byteswritten = isUdpBased()?dataChannel.write(writebuf) : socketChannel.write(writebuf); if (byteswritten == -1 ) throw new EOFException(); remaining -= byteswritten; //if the entire message was written from the buffer //reset the position counter if ( remaining < 0 ) { remaining = 0; } } return (remaining==0); } //no message to send, we can consider that complete return true; }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
Override public synchronized void connect() throws IOException { if ( connecting || isConnected()) return; connecting = true; if ( isConnected() ) throw new IOException("NioSender is already in connected state."); if ( readbuf == null ) { readbuf = getReadBuffer(); } else { readbuf.clear(); } if ( writebuf == null ) { writebuf = getWriteBuffer(); } else { writebuf.clear(); } if (isUdpBased()) { InetSocketAddress daddr = new InetSocketAddress(getAddress(),getUdpPort()); if ( dataChannel != null ) throw new IOException("Datagram channel has already been established. Connection might be in progress."); dataChannel = DatagramChannel.open(); dataChannel.configureBlocking(false); dataChannel.connect(daddr); completeConnect(); dataChannel.register(getSelector(),SelectionKey.OP_WRITE, this); } else { InetSocketAddress addr = new InetSocketAddress(getAddress(),getPort()); if ( socketChannel != null ) throw new IOException("Socket channel has already been established. Connection might be in progress."); socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); if ( socketChannel.connect(addr) ) { completeConnect(); socketChannel.register(getSelector(), SelectionKey.OP_WRITE, this); } else { socketChannel.register(getSelector(), SelectionKey.OP_CONNECT, this); } } }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
public synchronized void setMessage(byte[] data) throws IOException { setMessage(data,0,data.length); }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
public synchronized void setMessage(byte[] data,int offset, int length) throws IOException { if ( data != null ) { current = data; remaining = length; ackbuf.clear(); if ( writebuf != null ) writebuf.clear(); else writebuf = getBuffer(length); if ( writebuf.capacity() < length ) writebuf = getBuffer(length); //TODO use ByteBuffer.wrap to avoid copying the data. writebuf.put(data,offset,length); //writebuf.rewind(); //set the limit so that we don't write non wanted data //writebuf.limit(length); writebuf.flip(); if (isConnected()) { if (isUdpBased()) dataChannel.register(getSelector(), SelectionKey.OP_WRITE, this); else socketChannel.register(getSelector(), SelectionKey.OP_WRITE, this); } } }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
Override public synchronized void connect() throws IOException { this.connected = true; super.connect(); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
private int doLoop(long selectTimeOut, int maxAttempts, boolean waitForAck, ChannelMessage msg) throws IOException, ChannelException { int completed = 0; int selectedKeys = selector.select(selectTimeOut); if (selectedKeys == 0) { return 0; } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey sk = it.next(); it.remove(); int readyOps = sk.readyOps(); sk.interestOps(sk.interestOps() & ~readyOps); NioSender sender = (NioSender) sk.attachment(); try { if (sender.process(sk,waitForAck)) { completed++; sender.setComplete(true); if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("ParallelNioSender - Sent msg:" + new UniqueId(msg.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " to "+sender.getDestination().getName()); } SenderState.getSenderState(sender.getDestination()).setReady(); }//end if } catch (Exception x) { if (log.isTraceEnabled()) { log.trace("Error while processing send to " + sender.getDestination().getName(), x); } SenderState state = SenderState.getSenderState(sender.getDestination()); int attempt = sender.getAttempt()+1; boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0); synchronized (state) { //sk.cancel(); if (state.isSuspect()) state.setFailing(); if (state.isReady()) { state.setSuspect(); if ( retry ) log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect and retrying."); else log.warn("Member send is failing for:" + sender.getDestination().getName() +" ; Setting to suspect.", x); } } if ( !isConnected() ) { log.warn("Not retrying send for:" + sender.getDestination().getName() + "; Sender is disconnected."); ChannelException cx = new ChannelException("Send failed, and sender is disconnected. Not retrying.",x); cx.addFaultyMember(sender.getDestination(),x); throw cx; } byte[] data = sender.getMessage(); if ( retry ) { try { sender.disconnect(); sender.connect(); sender.setAttempt(attempt); sender.setMessage(data); }catch ( Exception ignore){ state.setFailing(); } } else { ChannelException cx = new ChannelException("Send failed, attempt:"+sender.getAttempt()+" max:"+maxAttempts,x); cx.addFaultyMember(sender.getDestination(),x); throw cx; }//end if } } return completed; }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
Override public void start() throws IOException { super.start(); try { setPool(new RxTaskPool(getMaxThreads(),getMinThreads(),this)); } catch (Exception x) { log.fatal("ThreadPool can initilzed. Listener not started", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } try { getBind(); bind(); Thread t = new Thread(this, "NioReceiver"); t.setDaemon(true); t.start(); } catch (Exception x) { log.fatal("Unable to start cluster receiver", x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
protected void bind() throws IOException { // allocate an unbound server socket channel serverChannel = ServerSocketChannel.open(); // Get the associated ServerSocket to bind it with ServerSocket serverSocket = serverChannel.socket(); // create a new Selector for use below synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 selector = Selector.open(); } // set the port the server channel will listen to //serverSocket.bind(new InetSocketAddress(getBind(), getTcpListenPort())); bind(serverSocket,getPort(),getAutoBind()); // set non-blocking mode for the listening socket serverChannel.configureBlocking(false); // register the ServerSocketChannel with the Selector serverChannel.register(selector, SelectionKey.OP_ACCEPT); //set up the datagram channel if (this.getUdpPort()>0) { datagramChannel = DatagramChannel.open(); datagramChannel.configureBlocking(false); //bind to the address to avoid security checks bindUdp(datagramChannel.socket(),getUdpPort(),getAutoBind()); } }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
private void closeSelector() throws IOException { Selector selector = this.selector; this.selector = null; if (selector==null) return; try { Iterator<SelectionKey> it = selector.keys().iterator(); // look at each key in the selected set while (it.hasNext()) { SelectionKey key = it.next(); key.channel().close(); key.attach(null); key.cancel(); } }catch ( IOException ignore ){ if (log.isWarnEnabled()) { log.warn("Unable to cleanup on selector close.",ignore); } }catch ( ClosedSelectorException ignore){} selector.close(); }
// in java/org/apache/catalina/tribes/transport/PooledSender.java
Override public synchronized void connect() throws IOException { //do nothing, happens in the socket sender itself queue.open(); setConnected(true); }
// in java/org/apache/catalina/tribes/transport/ReplicationTransmitter.java
Override public void start() throws java.io.IOException { getTransport().connect(); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public void deserialize(ClassLoader[] cls) throws IOException, ClassNotFoundException { key(cls); value(cls); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public Serializable key(ClassLoader[] cls) throws IOException, ClassNotFoundException { if ( key!=null ) return key; if ( keydata == null || keydata.length == 0 ) return null; key = XByteBuffer.deserialize(keydata,0,keydata.length,cls); keydata = null; return key; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public Serializable value(ClassLoader[] cls) throws IOException, ClassNotFoundException { if ( value!=null ) return value; if ( valuedata == null || valuedata.length == 0 ) return null; value = XByteBuffer.deserialize(valuedata,0,valuedata.length,cls); valuedata = null; return value; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
protected Member[] readMembers(ObjectInput in) throws IOException { int nodecount = in.readInt(); Member[] members = new Member[nodecount]; for ( int i=0; i<members.length; i++ ) { byte[] d = new byte[in.readInt()]; in.readFully(d); if (d.length > 0) members[i] = MemberImpl.getMember(d); } return members; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
protected void writeMembers(ObjectOutput out,Member[] members) throws IOException { if ( members == null ) members = new Member[0]; out.writeInt(members.length); for (int i=0; i<members.length; i++ ) { if ( members[i] != null ) { byte[] d = members[i] != null ? ( (MemberImpl)members[i]).getData(false) : new byte[0]; out.writeInt(d.length); out.write(d); } } }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
public void setHostname(String host) throws IOException { hostname = host; this.host = java.net.InetAddress.getByName(host).getAddress(); }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { int length = in.readInt(); byte[] message = new byte[length]; in.readFully(message); getMember(message,this); }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
Override public void writeExternal(ObjectOutput out) throws IOException { byte[] data = this.getData(); out.writeInt(data.length); out.write(data); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public void init() throws IOException { setupSocket(); sendPacket = new DatagramPacket(new byte[MAX_PACKET_SIZE],MAX_PACKET_SIZE); sendPacket.setAddress(address); sendPacket.setPort(port); receivePacket = new DatagramPacket(new byte[MAX_PACKET_SIZE],MAX_PACKET_SIZE); receivePacket.setAddress(address); receivePacket.setPort(port); member.setCommand(new byte[0]); member.getData(true, true); if ( membership == null ) membership = new Membership(member); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
protected void setupSocket() throws IOException { if (mcastBindAddress != null) { try { log.info("Attempting to bind the multicast socket to "+address+":"+port); socket = new MulticastSocket(new InetSocketAddress(address,port)); } catch (BindException e) { /* * On some platforms (e.g. Linux) it is not possible to bind * to the multicast address. In this case only bind to the * port. */ log.info("Binding to multicast address, failed. Binding to port only."); socket = new MulticastSocket(port); } } else { socket = new MulticastSocket(port); } socket.setLoopbackMode(localLoopbackDisabled); //hint if we want disable loop back(local machine) messages if (mcastBindAddress != null) { if(log.isInfoEnabled()) log.info("Setting multihome multicast interface to:" +mcastBindAddress); socket.setInterface(mcastBindAddress); } //end if //force a so timeout so that we don't block forever if ( mcastSoTimeout <= 0 ) mcastSoTimeout = (int)sendFrequency; if(log.isInfoEnabled()) log.info("Setting cluster mcast soTimeout to "+mcastSoTimeout); socket.setSoTimeout(mcastSoTimeout); if ( mcastTTL >= 0 ) { if(log.isInfoEnabled()) log.info("Setting cluster mcast TTL to " + mcastTTL); socket.setTimeToLive(mcastTTL); } }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public synchronized void start(int level) throws IOException { boolean valid = false; if ( (level & Channel.MBR_RX_SEQ)==Channel.MBR_RX_SEQ ) { if ( receiver != null ) throw new IllegalStateException("McastService.receive already running."); try { if ( sender == null ) socket.joinGroup(address); }catch (IOException iox) { log.error("Unable to join multicast group, make sure your system has multicasting enabled."); throw iox; } doRunReceiver = true; receiver = new ReceiverThread(); receiver.setDaemon(true); receiver.start(); valid = true; } if ( (level & Channel.MBR_TX_SEQ)==Channel.MBR_TX_SEQ ) { if ( sender != null ) throw new IllegalStateException("McastService.send already running."); if ( receiver == null ) socket.joinGroup(address); //make sure at least one packet gets out there send(false); doRunSender = true; sender = new SenderThread(sendFrequency); sender.setDaemon(true); sender.start(); //we have started the receiver, but not yet waited for membership to establish valid = true; } if (!valid) { throw new IllegalArgumentException("Invalid start level. Only acceptable levels are Channel.MBR_RX_SEQ and Channel.MBR_TX_SEQ"); } //pause, once or twice waitForMembers(level); startLevel = (startLevel | level); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public synchronized boolean stop(int level) throws IOException { boolean valid = false; if ( (level & Channel.MBR_RX_SEQ)==Channel.MBR_RX_SEQ ) { valid = true; doRunReceiver = false; if ( receiver !=null ) receiver.interrupt(); receiver = null; } if ( (level & Channel.MBR_TX_SEQ)==Channel.MBR_TX_SEQ ) { valid = true; doRunSender = false; if ( sender != null )sender.interrupt(); sender = null; } if (!valid) { throw new IllegalArgumentException("Invalid stop level. Only acceptable levels are Channel.MBR_RX_SEQ and Channel.MBR_TX_SEQ"); } startLevel = (startLevel & (~level)); //we're shutting down, send a shutdown message and close the socket if ( startLevel == 0 ) { //send a stop message member.setCommand(Member.SHUTDOWN_PAYLOAD); member.getData(true, true); send(false); //leave mcast group try {socket.leaveGroup(address);}catch ( Exception ignore){} try {socket.close();}catch ( Exception ignore){} member.setServiceStartTime(-1); } return (startLevel == 0); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public void receive() throws IOException { boolean checkexpired = true; try { socket.receive(receivePacket); if(receivePacket.getLength() > MAX_PACKET_SIZE) { log.error("Multicast packet received was too long, dropping package:"+receivePacket.getLength()); } else { byte[] data = new byte[receivePacket.getLength()]; System.arraycopy(receivePacket.getData(), receivePacket.getOffset(), data, 0, data.length); if (XByteBuffer.firstIndexOf(data,0,MemberImpl.TRIBES_MBR_BEGIN)==0) { memberDataReceived(data); } else { memberBroadcastsReceived(data); } } } catch (SocketTimeoutException x ) { //do nothing, this is normal, we don't want to block forever //since the receive thread is the same thread //that does membership expiration } if (checkexpired) checkExpired(); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public void send(boolean checkexpired) throws IOException{ send(checkexpired,null); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public void send(boolean checkexpired, DatagramPacket packet) throws IOException{ checkexpired = (checkexpired && (packet==null)); //ignore if we haven't started the sender //if ( (startLevel&Channel.MBR_TX_SEQ) != Channel.MBR_TX_SEQ ) return; if (packet==null) { member.inc(); if(log.isTraceEnabled()) { log.trace("Mcast send ping from member " + member); } byte[] data = member.getData(); packet = new DatagramPacket(data,data.length); } else if (log.isTraceEnabled()) { log.trace("Sending message broadcast "+packet.getLength()+ " bytes from "+ member); } packet.setAddress(address); packet.setPort(port); //TODO this operation is not thread safe synchronized (sendLock) { socket.send(packet); } if ( checkexpired ) checkExpired(); }
// in java/org/apache/catalina/session/StandardManager.java
Override public void load() throws ClassNotFoundException, IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ AccessController.doPrivileged( new PrivilegedDoLoad() ); } catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof ClassNotFoundException){ throw (ClassNotFoundException)exception; } else if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in load() " + exception); } } else { doLoad(); } }
// in java/org/apache/catalina/session/StandardManager.java
protected void doLoad() throws ClassNotFoundException, IOException { if (log.isDebugEnabled()) log.debug("Start: Loading persisted sessions"); // Initialize our internal data structures sessions.clear(); // Open an input stream to the specified pathname, if any File file = file(); if (file == null) return; if (log.isDebugEnabled()) log.debug(sm.getString("standardManager.loading", pathname)); FileInputStream fis = null; BufferedInputStream bis = null; ObjectInputStream ois = null; Loader loader = null; ClassLoader classLoader = null; try { fis = new FileInputStream(file.getAbsolutePath()); bis = new BufferedInputStream(fis); if (container != null) loader = container.getLoader(); if (loader != null) classLoader = loader.getClassLoader(); if (classLoader != null) { if (log.isDebugEnabled()) log.debug("Creating custom object input stream for class loader "); ois = new CustomObjectInputStream(bis, classLoader); } else { if (log.isDebugEnabled()) log.debug("Creating standard object input stream"); ois = new ObjectInputStream(bis); } } catch (FileNotFoundException e) { if (log.isDebugEnabled()) log.debug("No persisted data file found"); return; } catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } throw e; } // Load the previously unloaded active sessions synchronized (sessions) { try { Integer count = (Integer) ois.readObject(); int n = count.intValue(); if (log.isDebugEnabled()) log.debug("Loading " + n + " persisted sessions"); for (int i = 0; i < n; i++) { StandardSession session = getNewSession(); session.readObjectData(ois); session.setManager(this); sessions.put(session.getIdInternal(), session); session.activate(); if (!session.isValidInternal()) { // If session is already invalid, // expire session to prevent memory leak. session.setValid(true); session.expire(); } sessionCounter++; } } catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; } catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; } finally { // Close the input stream try { ois.close(); } catch (IOException f) { // ignored } // Delete the persistent storage file if (file.exists() ) file.delete(); } } if (log.isDebugEnabled()) log.debug("Finish: Loading persisted sessions"); }
// in java/org/apache/catalina/session/StandardManager.java
Override public void unload() throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ AccessController.doPrivileged( new PrivilegedDoUnload() ); } catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in unLoad() " + exception); } } else { doUnload(); } }
// in java/org/apache/catalina/session/StandardManager.java
protected void doUnload() throws IOException { if (log.isDebugEnabled()) log.debug(sm.getString("standardManager.unloading.debug")); if (sessions.isEmpty()) { log.debug(sm.getString("standardManager.unloading.nosessions")); return; // nothing to do } // Open an output stream to the specified pathname, if any File file = file(); if (file == null) return; if (log.isDebugEnabled()) log.debug(sm.getString("standardManager.unloading", pathname)); FileOutputStream fos = null; BufferedOutputStream bos = null; ObjectOutputStream oos = null; boolean error = false; try { fos = new FileOutputStream(file.getAbsolutePath()); bos = new BufferedOutputStream(fos); oos = new ObjectOutputStream(bos); } catch (IOException e) { error = true; log.error(sm.getString("standardManager.unloading.ioe", e), e); throw e; } finally { if (error) { if (oos != null) { try { oos.close(); } catch (IOException ioe) { // Ignore } } if (bos != null) { try { bos.close(); } catch (IOException ioe) { // Ignore } } if (fos != null) { try { fos.close(); } catch (IOException ioe) { // Ignore } } } } // Write the number of active sessions, followed by the details ArrayList<StandardSession> list = new ArrayList<StandardSession>(); synchronized (sessions) { if (log.isDebugEnabled()) log.debug("Unloading " + sessions.size() + " sessions"); try { oos.writeObject(new Integer(sessions.size())); Iterator<Session> elements = sessions.values().iterator(); while (elements.hasNext()) { StandardSession session = (StandardSession) elements.next(); list.add(session); session.passivate(); session.writeObjectData(oos); } } catch (IOException e) { log.error(sm.getString("standardManager.unloading.ioe", e), e); try { oos.close(); } catch (IOException f) { // Ignore } throw e; } } // Flush and close the output stream try { oos.flush(); } finally { try { oos.close(); } catch (IOException f) { // Ignore } } // Expire all the sessions we just wrote if (log.isDebugEnabled()) log.debug("Expiring " + list.size() + " persisted sessions"); Iterator<StandardSession> expires = list.iterator(); while (expires.hasNext()) { StandardSession session = expires.next(); try { session.expire(false); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } finally { session.recycle(); } } if (log.isDebugEnabled()) log.debug("Unloading complete"); }
// in java/org/apache/catalina/session/ManagerBase.java
Override public Session findSession(String id) throws IOException { if (id == null) return (null); return sessions.get(id); }
// in java/org/apache/catalina/session/JDBCStore.java
Override public String[] keys() throws IOException { ResultSet rst = null; String keys[] = null; synchronized (this) { int numberOfTries = 2; while (numberOfTries > 0) { Connection _conn = getConnection(); if (_conn == null) { return (new String[0]); } try { if (preparedKeysSql == null) { String keysSql = "SELECT " + sessionIdCol + " FROM " + sessionTable + " WHERE " + sessionAppCol + " = ?"; preparedKeysSql = _conn.prepareStatement(keysSql); } preparedKeysSql.setString(1, getName()); rst = preparedKeysSql.executeQuery(); ArrayList<String> tmpkeys = new ArrayList<String>(); if (rst != null) { while (rst.next()) { tmpkeys.add(rst.getString(1)); } } keys = tmpkeys.toArray(new String[tmpkeys.size()]); // Break out after the finally block numberOfTries = 0; } catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); keys = new String[0]; // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); } finally { try { if (rst != null) { rst.close(); } } catch (SQLException e) { // Ignore } release(_conn); } numberOfTries--; } } return (keys); }
// in java/org/apache/catalina/session/JDBCStore.java
Override public int getSize() throws IOException { int size = 0; ResultSet rst = null; synchronized (this) { int numberOfTries = 2; while (numberOfTries > 0) { Connection _conn = getConnection(); if (_conn == null) { return (size); } try { if (preparedSizeSql == null) { String sizeSql = "SELECT COUNT(" + sessionIdCol + ") FROM " + sessionTable + " WHERE " + sessionAppCol + " = ?"; preparedSizeSql = _conn.prepareStatement(sizeSql); } preparedSizeSql.setString(1, getName()); rst = preparedSizeSql.executeQuery(); if (rst.next()) { size = rst.getInt(1); } // Break out after the finally block numberOfTries = 0; } catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); } finally { try { if (rst != null) rst.close(); } catch (SQLException e) { // Ignore } release(_conn); } numberOfTries--; } } return (size); }
// in java/org/apache/catalina/session/JDBCStore.java
Override public Session load(String id) throws ClassNotFoundException, IOException { ResultSet rst = null; StandardSession _session = null; Loader loader = null; ClassLoader classLoader = null; ObjectInputStream ois = null; BufferedInputStream bis = null; Container container = manager.getContainer(); synchronized (this) { int numberOfTries = 2; while (numberOfTries > 0) { Connection _conn = getConnection(); if (_conn == null) { return (null); } try { if (preparedLoadSql == null) { String loadSql = "SELECT " + sessionIdCol + ", " + sessionDataCol + " FROM " + sessionTable + " WHERE " + sessionIdCol + " = ? AND " + sessionAppCol + " = ?"; preparedLoadSql = _conn.prepareStatement(loadSql); } preparedLoadSql.setString(1, id); preparedLoadSql.setString(2, getName()); rst = preparedLoadSql.executeQuery(); if (rst.next()) { bis = new BufferedInputStream(rst.getBinaryStream(2)); if (container != null) { loader = container.getLoader(); } if (loader != null) { classLoader = loader.getClassLoader(); } if (classLoader != null) { ois = new CustomObjectInputStream(bis, classLoader); } else { ois = new ObjectInputStream(bis); } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName() + ".loading", id, sessionTable)); } _session = (StandardSession) manager.createEmptySession(); _session.readObjectData(ois); _session.setManager(manager); } else if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(getStoreName() + ": No persisted data object found"); } // Break out after the finally block numberOfTries = 0; } catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); } finally { try { if (rst != null) { rst.close(); } } catch (SQLException e) { // Ignore } if (ois != null) { try { ois.close(); } catch (IOException e) { // Ignore } } release(_conn); } numberOfTries--; } } return (_session); }
// in java/org/apache/catalina/session/JDBCStore.java
Override public void remove(String id) throws IOException { synchronized (this) { int numberOfTries = 2; while (numberOfTries > 0) { Connection _conn = getConnection(); if (_conn == null) { return; } try { remove(id, _conn); // Break out after the finally block numberOfTries = 0; } catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); } finally { release(_conn); } numberOfTries--; } } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName() + ".removing", id, sessionTable)); } }
// in java/org/apache/catalina/session/JDBCStore.java
Override public void clear() throws IOException { synchronized (this) { int numberOfTries = 2; while (numberOfTries > 0) { Connection _conn = getConnection(); if (_conn == null) { return; } try { if (preparedClearSql == null) { String clearSql = "DELETE FROM " + sessionTable + " WHERE " + sessionAppCol + " = ?"; preparedClearSql = _conn.prepareStatement(clearSql); } preparedClearSql.setString(1, getName()); preparedClearSql.execute(); // Break out after the finally block numberOfTries = 0; } catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); } finally { release(_conn); } numberOfTries--; } } }
// in java/org/apache/catalina/session/JDBCStore.java
Override public void save(Session session) throws IOException { ObjectOutputStream oos = null; ByteArrayOutputStream bos = null; ByteArrayInputStream bis = null; InputStream in = null; synchronized (this) { int numberOfTries = 2; while (numberOfTries > 0) { Connection _conn = getConnection(); if (_conn == null) { return; } try { // If sessions already exist in DB, remove and insert again. // TODO: // * Check if ID exists in database and if so use UPDATE. remove(session.getIdInternal(), _conn); bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(new BufferedOutputStream(bos)); ((StandardSession) session).writeObjectData(oos); oos.close(); oos = null; byte[] obs = bos.toByteArray(); int size = obs.length; bis = new ByteArrayInputStream(obs, 0, size); in = new BufferedInputStream(bis, size); if (preparedSaveSql == null) { String saveSql = "INSERT INTO " + sessionTable + " (" + sessionIdCol + ", " + sessionAppCol + ", " + sessionDataCol + ", " + sessionValidCol + ", " + sessionMaxInactiveCol + ", " + sessionLastAccessedCol + ") VALUES (?, ?, ?, ?, ?, ?)"; preparedSaveSql = _conn.prepareStatement(saveSql); } preparedSaveSql.setString(1, session.getIdInternal()); preparedSaveSql.setString(2, getName()); preparedSaveSql.setBinaryStream(3, in, size); preparedSaveSql.setString(4, session.isValid() ? "1" : "0"); preparedSaveSql.setInt(5, session.getMaxInactiveInterval()); preparedSaveSql.setLong(6, session.getLastAccessedTime()); preparedSaveSql.execute(); // Break out after the finally block numberOfTries = 0; } catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); } catch (IOException e) { // Ignore } finally { if (oos != null) { oos.close(); } if (bis != null) { bis.close(); } if (in != null) { in.close(); } release(_conn); } numberOfTries--; } } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName() + ".saving", session.getIdInternal(), sessionTable)); } }
// in java/org/apache/catalina/session/FileStore.java
Override public int getSize() throws IOException { // Acquire the list of files in our storage directory File file = directory(); if (file == null) { return (0); } String files[] = file.list(); // Figure out which files are sessions int keycount = 0; for (int i = 0; i < files.length; i++) { if (files[i].endsWith(FILE_EXT)) { keycount++; } } return (keycount); }
// in java/org/apache/catalina/session/FileStore.java
Override public void clear() throws IOException { String[] keys = keys(); for (int i = 0; i < keys.length; i++) { remove(keys[i]); } }
// in java/org/apache/catalina/session/FileStore.java
Override public String[] keys() throws IOException { // Acquire the list of files in our storage directory File file = directory(); if (file == null) { return (new String[0]); } String files[] = file.list(); // Bugzilla 32130 if((files == null) || (files.length < 1)) { return (new String[0]); } // Build and return the list of session identifiers ArrayList<String> list = new ArrayList<String>(); int n = FILE_EXT.length(); for (int i = 0; i < files.length; i++) { if (files[i].endsWith(FILE_EXT)) { list.add(files[i].substring(0, files[i].length() - n)); } } return list.toArray(new String[list.size()]); }
// in java/org/apache/catalina/session/FileStore.java
Override public Session load(String id) throws ClassNotFoundException, IOException { // Open an input stream to the specified pathname, if any File file = file(id); if (file == null) { return (null); } if (! file.exists()) { return (null); } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName()+".loading", id, file.getAbsolutePath())); } FileInputStream fis = null; BufferedInputStream bis = null; ObjectInputStream ois = null; Loader loader = null; ClassLoader classLoader = null; try { fis = new FileInputStream(file.getAbsolutePath()); bis = new BufferedInputStream(fis); Container container = manager.getContainer(); if (container != null) loader = container.getLoader(); if (loader != null) classLoader = loader.getClassLoader(); if (classLoader != null) ois = new CustomObjectInputStream(bis, classLoader); else ois = new ObjectInputStream(bis); } catch (FileNotFoundException e) { if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug("No persisted data file found"); return (null); } catch (IOException e) { if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } throw e; } try { StandardSession session = (StandardSession) manager.createEmptySession(); session.readObjectData(ois); session.setManager(manager); return (session); } finally { // Close the input stream try { ois.close(); } catch (IOException f) { // Ignore } } }
// in java/org/apache/catalina/session/FileStore.java
Override public void remove(String id) throws IOException { File file = file(id); if (file == null) { return; } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName()+".removing", id, file.getAbsolutePath())); } file.delete(); }
// in java/org/apache/catalina/session/FileStore.java
Override public void save(Session session) throws IOException { // Open an output stream to the specified pathname, if any File file = file(session.getIdInternal()); if (file == null) { return; } if (manager.getContainer().getLogger().isDebugEnabled()) { manager.getContainer().getLogger().debug(sm.getString(getStoreName()+".saving", session.getIdInternal(), file.getAbsolutePath())); } FileOutputStream fos = null; ObjectOutputStream oos = null; try { fos = new FileOutputStream(file.getAbsolutePath()); oos = new ObjectOutputStream(new BufferedOutputStream(fos)); } catch (IOException e) { if (fos != null) { try { fos.close(); } catch (IOException f) { // Ignore } } throw e; } try { ((StandardSession)session).writeObjectData(oos); } finally { oos.close(); } }
// in java/org/apache/catalina/session/FileStore.java
private File directory() throws IOException { if (this.directory == null) { return (null); } if (this.directoryFile != null) { // NOTE: Race condition is harmless, so do not synchronize return (this.directoryFile); } File file = new File(this.directory); if (!file.isAbsolute()) { Container container = manager.getContainer(); if (container instanceof Context) { ServletContext servletContext = ((Context) container).getServletContext(); File work = (File) servletContext.getAttribute(ServletContext.TEMPDIR); file = new File(work, this.directory); } else { throw new IllegalArgumentException ("Parent Container is not a Context"); } } if (!file.exists() || !file.isDirectory()) { if (!file.delete() && file.exists()) { throw new IOException( sm.getString("fileStore.deleteFailed", file)); } if (!file.mkdirs() && !file.isDirectory()) { throw new IOException( sm.getString("fileStore.createFailed", file)); } } this.directoryFile = file; return (file); }
// in java/org/apache/catalina/session/FileStore.java
private File file(String id) throws IOException { if (this.directory == null) { return (null); } String filename = id + FILE_EXT; File file = new File(directory(), filename); return (file); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override public Session findSession(String id) throws IOException { Session session = super.findSession(id); // OK, at this point, we're not sure if another thread is trying to // remove the session or not so the only way around this is to lock it // (or attempt to) and then try to get it by this session id again. If // the other code ran swapOut, then we should get a null back during // this run, and if not, we lock it out so we can access the session // safely. if(session != null) { synchronized(session){ session = super.findSession(session.getIdInternal()); if(session != null){ // To keep any external calling code from messing up the // concurrency. session.access(); session.endAccess(); } } } if (session != null) return (session); // See if the Session is in the Store session = swapIn(id); return (session); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
protected Session swapIn(String id) throws IOException { if (store == null) return null; Object swapInLock = null; /* * The purpose of this sync and these locks is to make sure that a * session is only loaded once. It doesn't matter if the lock is removed * and then another thread enters this method and tries to load the same * session. That thread will re-create a swapIn lock for that session, * quickly find that the session is already in sessions, use it and * carry on. */ synchronized (this) { swapInLock = sessionSwapInLocks.get(id); if (swapInLock == null) { swapInLock = new Object(); sessionSwapInLocks.put(id, swapInLock); } } Session session = null; synchronized (swapInLock) { // First check to see if another thread has loaded the session into // the manager session = sessions.get(id); if (session == null) { try { if (SecurityUtil.isPackageProtectionEnabled()){ try { session = AccessController.doPrivileged( new PrivilegedStoreLoad(id)); } catch (PrivilegedActionException ex) { Exception e = ex.getException(); log.error(sm.getString( "persistentManager.swapInException", id), e); if (e instanceof IOException){ throw (IOException)e; } else if (e instanceof ClassNotFoundException) { throw (ClassNotFoundException)e; } } } else { session = store.load(id); } } catch (ClassNotFoundException e) { String msg = sm.getString( "persistentManager.deserializeError", id); log.error(msg, e); throw new IllegalStateException(msg, e); } if (session != null && !session.isValid()) { log.error(sm.getString( "persistentManager.swapInInvalid", id)); session.expire(); removeSession(id); session = null; } if (session != null) { if(log.isDebugEnabled()) log.debug(sm.getString("persistentManager.swapIn", id)); session.setManager(this); // make sure the listeners know about it. ((StandardSession)session).tellNew(); add(session); ((StandardSession)session).activate(); // endAccess() to ensure timeouts happen correctly. // access() to keep access count correct or it will end up // negative session.access(); session.endAccess(); } } } // Make sure the lock is removed synchronized (this) { sessionSwapInLocks.remove(id); } return (session); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
protected void swapOut(Session session) throws IOException { if (store == null || !session.isValid()) { return; } ((StandardSession)session).passivate(); writeSession(session); super.remove(session, true); session.recycle(); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
protected void writeSession(Session session) throws IOException { if (store == null || !session.isValid()) { return; } try { if (SecurityUtil.isPackageProtectionEnabled()){ try{ AccessController.doPrivileged(new PrivilegedStoreSave(session)); }catch(PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException) { throw (IOException) exception; } log.error("Exception in the Store during writeSession: " + exception, exception); } } else { store.save(session); } } catch (IOException e) { log.error(sm.getString ("persistentManager.serializeError", session.getIdInternal(), e)); throw e; } }
// in java/org/apache/catalina/session/StandardSession.java
public void readObjectData(ObjectInputStream stream) throws ClassNotFoundException, IOException { readObject(stream); }
// in java/org/apache/catalina/session/StandardSession.java
public void writeObjectData(ObjectOutputStream stream) throws IOException { writeObject(stream); }
// in java/org/apache/catalina/session/StandardSession.java
protected void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException { // Deserialize the scalar instance variables (except Manager) authType = null; // Transient only creationTime = ((Long) stream.readObject()).longValue(); lastAccessedTime = ((Long) stream.readObject()).longValue(); maxInactiveInterval = ((Integer) stream.readObject()).intValue(); isNew = ((Boolean) stream.readObject()).booleanValue(); isValid = ((Boolean) stream.readObject()).booleanValue(); thisAccessedTime = ((Long) stream.readObject()).longValue(); principal = null; // Transient only // setId((String) stream.readObject()); id = (String) stream.readObject(); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug ("readObject() loading session " + id); // Deserialize the attribute count and attribute values if (attributes == null) attributes = new ConcurrentHashMap<String, Object>(); int n = ((Integer) stream.readObject()).intValue(); boolean isValidSave = isValid; isValid = true; for (int i = 0; i < n; i++) { String name = (String) stream.readObject(); Object value = stream.readObject(); if ((value instanceof String) && (value.equals(NOT_SERIALIZED))) continue; if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug(" loading attribute '" + name + "' with value '" + value + "'"); attributes.put(name, value); } isValid = isValidSave; if (listeners == null) { listeners = new ArrayList<SessionListener>(); } if (notes == null) { notes = new Hashtable<String, Object>(); } }
// in java/org/apache/catalina/session/StandardSession.java
protected void writeObject(ObjectOutputStream stream) throws IOException { // Write the scalar instance variables (except Manager) stream.writeObject(Long.valueOf(creationTime)); stream.writeObject(Long.valueOf(lastAccessedTime)); stream.writeObject(Integer.valueOf(maxInactiveInterval)); stream.writeObject(Boolean.valueOf(isNew)); stream.writeObject(Boolean.valueOf(isValid)); stream.writeObject(Long.valueOf(thisAccessedTime)); stream.writeObject(id); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug ("writeObject() storing session " + id); // Accumulate the names of serializable and non-serializable attributes String keys[] = keys(); ArrayList<String> saveNames = new ArrayList<String>(); ArrayList<Object> saveValues = new ArrayList<Object>(); for (int i = 0; i < keys.length; i++) { Object value = attributes.get(keys[i]); if (value == null) continue; else if ( (value instanceof Serializable) && (!exclude(keys[i]) )) { saveNames.add(keys[i]); saveValues.add(value); } else { removeAttributeInternal(keys[i], true); } } // Serialize the attribute count and the Serializable attributes int n = saveNames.size(); stream.writeObject(Integer.valueOf(n)); for (int i = 0; i < n; i++) { stream.writeObject(saveNames.get(i)); try { stream.writeObject(saveValues.get(i)); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug (" storing attribute '" + saveNames.get(i) + "' with value '" + saveValues.get(i) + "'"); } catch (NotSerializableException e) { manager.getContainer().getLogger().warn (sm.getString("standardSession.notSerializable", saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug (" storing attribute '" + saveNames.get(i) + "' with value NOT_SERIALIZED"); } } }
// in java/org/apache/catalina/valves/RequestFilterValve.java
protected void process(String property, Request request, Response response) throws IOException, ServletException { if (isAllowed(property)) { getNext().invoke(request, response); return; } // Deny this request denyRequest(request, response); }
// in java/org/apache/catalina/valves/RequestFilterValve.java
protected void denyRequest(Request request, Response response) throws IOException, ServletException { response.sendError(denyStatus); }
// in java/org/apache/catalina/valves/RemoteHostValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { process(request.getRequest().getRemoteHost(), request, response); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { // Perform the request getNext().invoke(request, response); if (request.isComet() && !response.isClosed()) { // Start tracking this connection, since this is a // begin event, and Comet mode is on HttpSession session = request.getSession(true); // Track the connection for webapp reload cometRequests.add(request); // Track the connection for session expiration synchronized (session) { Request[] requests = (Request[]) session.getAttribute(cometRequestsAttribute); if (requests == null) { requests = new Request[1]; requests[0] = request; session.setAttribute(cometRequestsAttribute, requests); } else { Request[] newRequests = new Request[requests.length + 1]; for (int i = 0; i < requests.length; i++) { newRequests[i] = requests[i]; } newRequests[requests.length] = request; session.setAttribute(cometRequestsAttribute, newRequests); } } } }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
Override public void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Perform the request boolean ok = false; try { getNext().event(request, response, event); ok = true; } finally { if (!ok || response.isClosed() || (event.getEventType() == CometEvent.EventType.END) || (event.getEventType() == CometEvent.EventType.ERROR && !(event.getEventSubType() == CometEvent.EventSubType.TIMEOUT))) { // Remove the connection from webapp reload tracking cometRequests.remove(request); // Remove connection from session expiration tracking // Note: can't get the session if it has been invalidated but // OK since session listener will have done clean-up HttpSession session = request.getSession(false); if (session != null) { synchronized (session) { Request[] reqs = null; try { reqs = (Request[]) session.getAttribute(cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } if (reqs != null) { boolean found = false; for (int i = 0; !found && (i < reqs.length); i++) { found = (reqs[i] == request); } if (found) { if (reqs.length > 1) { Request[] newConnectionInfos = new Request[reqs.length - 1]; int pos = 0; for (int i = 0; i < reqs.length; i++) { if (reqs[i] != request) { newConnectionInfos[pos++] = reqs[i]; } } try { session.setAttribute( cometRequestsAttribute, newConnectionInfos); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } else { try { session.removeAttribute( cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } } } } } } } }
// in java/org/apache/catalina/valves/CrawlerSessionManagerValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { boolean isBot = false; String sessionId = null; String clientIp = null; if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": ClientIp=" + request.getRemoteAddr() + ", RequestedSessionId=" + request.getRequestedSessionId()); } // If the incoming request has a valid session ID, no action is required if (request.getSession(false) == null) { // Is this a crawler - check the UA headers Enumeration<String> uaHeaders = request.getHeaders("user-agent"); String uaHeader = null; if (uaHeaders.hasMoreElements()) { uaHeader = uaHeaders.nextElement(); } // If more than one UA header - assume not a bot if (uaHeader != null && !uaHeaders.hasMoreElements()) { if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": UserAgent=" + uaHeader); } if (uaPattern.matcher(uaHeader).matches()) { isBot = true; if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": Bot found. UserAgent=" + uaHeader); } } } // If this is a bot, is the session ID known? if (isBot) { clientIp = request.getRemoteAddr(); sessionId = clientIpSessionId.get(clientIp); if (sessionId != null) { request.setRequestedSessionId(sessionId); if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": SessionID=" + sessionId); } } } } getNext().invoke(request, response); if (isBot) { if (sessionId == null) { // Has bot just created a session, if so make a note of it HttpSession s = request.getSession(false); if (s != null) { clientIpSessionId.put(clientIp, s.getId()); sessionIdClientIp.put(s.getId(), clientIp); // #valueUnbound() will be called on session expiration s.setAttribute(this.getClass().getName(), this); s.setMaxInactiveInterval(sessionInactiveInterval); if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": New bot session. SessionID=" + s.getId()); } } } else { if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": Bot session accessed. SessionID=" + sessionId); } } } }
// in java/org/apache/catalina/valves/RemoteAddrValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { process(request.getRequest().getRemoteAddr(), request, response); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { getNext().invoke(request, response); }
// in java/org/apache/catalina/valves/StuckThreadDetectionValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (threshold <= 0) { // short-circuit if not monitoring stuck threads getNext().invoke(request, response); return; } // Save the thread/runnable // Keeping a reference to the thread object here does not prevent // GC'ing, as the reference is removed from the Map in the finally clause Long key = Long.valueOf(Thread.currentThread().getId()); StringBuffer requestUrl = request.getRequestURL(); if(request.getQueryString()!=null) { requestUrl.append("?"); requestUrl.append(request.getQueryString()); } MonitoredThread monitoredThread = new MonitoredThread(Thread.currentThread(), requestUrl.toString()); activeThreads.put(key, monitoredThread); try { getNext().invoke(request, response); } finally { activeThreads.remove(key); if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) { completedStuckThreadsQueue.add( new CompletedStuckThread(monitoredThread.getThread().getName(), monitoredThread.getActiveTimeInMillis())); } } }
// in java/org/apache/catalina/valves/SSLValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { /* mod_header converts the '\n' into ' ' so we have to rebuild the client certificate */ String strcert0 = mygetHeader(request, "ssl_client_cert"); if (strcert0 != null && strcert0.length()>28) { String strcert1 = strcert0.replace(' ', '\n'); String strcert2 = strcert1.substring(28, strcert1.length()-26); String strcert3 = "-----BEGIN CERTIFICATE-----\n"; String strcert4 = strcert3.concat(strcert2); String strcerts = strcert4.concat("\n-----END CERTIFICATE-----\n"); // ByteArrayInputStream bais = new ByteArrayInputStream(strcerts.getBytes("UTF-8")); ByteArrayInputStream bais = new ByteArrayInputStream( strcerts.getBytes(B2CConverter.ISO_8859_1)); X509Certificate jsseCerts[] = null; String providerName = (String) request.getConnector().getProperty( "clientCertProvider"); try { CertificateFactory cf; if (providerName == null) { cf = CertificateFactory.getInstance("X.509"); } else { cf = CertificateFactory.getInstance("X.509", providerName); } X509Certificate cert = (X509Certificate) cf.generateCertificate(bais); jsseCerts = new X509Certificate[1]; jsseCerts[0] = cert; } catch (java.security.cert.CertificateException e) { log.warn(sm.getString("sslValve.certError", strcerts), e); } catch (NoSuchProviderException e) { log.error(sm.getString( "sslValve.invalidProvider", providerName), e); } request.setAttribute(Globals.CERTIFICATES_ATTR, jsseCerts); } strcert0 = mygetHeader(request, "ssl_cipher"); if (strcert0 != null) { request.setAttribute(Globals.CIPHER_SUITE_ATTR, strcert0); } strcert0 = mygetHeader(request, "ssl_session_id"); if (strcert0 != null) { request.setAttribute(Globals.SSL_SESSION_ID_ATTR, strcert0); } strcert0 = mygetHeader(request, "ssl_cipher_usekeysize"); if (strcert0 != null) { request.setAttribute(Globals.KEY_SIZE_ATTR, Integer.valueOf(strcert0)); } getNext().invoke(request, response); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { // Perform the request getNext().invoke(request, response); if (response.isCommitted()) { return; } Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); if (request.isAsyncStarted() && response.getStatus() < 400 && throwable == null) { return; } if (throwable != null) { // The response is an error response.setError(); // Reset the response (if possible) try { response.reset(); } catch (IllegalStateException e) { // Ignore } response.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } response.setSuspended(false); try { report(request, response, throwable); } catch (Throwable tt) { ExceptionUtils.handleThrowable(tt); } if (request.isAsyncStarted()) { request.getAsyncContext().complete(); } }
// in java/org/apache/catalina/valves/SemaphoreValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (controlConcurrency(request, response)) { boolean shouldRelease = true; try { if (block) { if (interruptible) { try { semaphore.acquire(); } catch (InterruptedException e) { shouldRelease = false; permitDenied(request, response); return; } } else { semaphore.acquireUninterruptibly(); } } else { if (!semaphore.tryAcquire()) { shouldRelease = false; permitDenied(request, response); return; } } getNext().invoke(request, response); } finally { if (shouldRelease) { semaphore.release(); } } } else { getNext().invoke(request, response); } }
// in java/org/apache/catalina/valves/SemaphoreValve.java
public void permitDenied(Request request, Response response) throws IOException, ServletException { // NO-OP by default }
// in java/org/apache/catalina/valves/PersistentValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { // Select the Context to be used for this Request Context context = request.getContext(); if (context == null) { response.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, sm.getString("standardHost.noContext")); return; } // Bind the context CL to the current thread Thread.currentThread().setContextClassLoader (context.getLoader().getClassLoader()); // Update the session last access time for our session (if any) String sessionId = request.getRequestedSessionId(); Manager manager = context.getManager(); if (sessionId != null && manager != null) { if (manager instanceof StoreManager) { Store store = ((StoreManager) manager).getStore(); if (store != null) { Session session = null; try { session = store.load(sessionId); } catch (Exception e) { container.getLogger().error("deserializeError"); } if (session != null) { if (!session.isValid() || isSessionStale(session, System.currentTimeMillis())) { if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("session swapped in is invalid or expired"); } session.expire(); store.remove(sessionId); } else { session.setManager(manager); // session.setId(sessionId); Only if new ??? manager.add(session); // ((StandardSession)session).activate(); session.access(); session.endAccess(); } } } } } if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("sessionId: " + sessionId); } // Ask the next valve to process the request. getNext().invoke(request, response); // If still processing async, don't try to store the session // TODO: Are there some async states where it is would be safe to store // the session? if (!request.isAsync()) { // Read the sessionid after the response. // HttpSession hsess = hreq.getSession(false); Session hsess; try { hsess = request.getSessionInternal(); } catch (Exception ex) { hsess = null; } String newsessionId = null; if (hsess!=null) { newsessionId = hsess.getIdInternal(); } if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("newsessionId: " + newsessionId); } if (newsessionId!=null) { /* store the session and remove it from the manager */ if (manager instanceof StoreManager) { Session session = manager.findSession(newsessionId); Store store = ((StoreManager) manager).getStore(); if (store != null && session!=null && session.isValid() && !isSessionStale(session, System.currentTimeMillis())) { // ((StandardSession)session).passivate(); store.save(session); ((StoreManager) manager).removeSuper(session); session.recycle(); } else { if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("newsessionId store: " + store + " session: " + session + " valid: " + (session == null ? "N/A" : Boolean.toString( session.isValid())) + " stale: " + isSessionStale(session, System.currentTimeMillis())); } } } else { if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("newsessionId Manager: " + manager); } } } } }
// in java/org/apache/catalina/valves/AccessLogValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { getNext().invoke(request, response); }
// in java/org/apache/catalina/valves/RemoteIpValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { final String originalRemoteAddr = request.getRemoteAddr(); final String originalRemoteHost = request.getRemoteHost(); final String originalScheme = request.getScheme(); final boolean originalSecure = request.isSecure(); final int originalServerPort = request.getServerPort(); if (internalProxies !=null && internalProxies.matcher(originalRemoteAddr).matches()) { String remoteIp = null; // In java 6, proxiesHeaderValue should be declared as a java.util.Deque LinkedList<String> proxiesHeaderValue = new LinkedList<String>(); StringBuilder concatRemoteIpHeaderValue = new StringBuilder(); for (Enumeration<String> e = request.getHeaders(remoteIpHeader); e.hasMoreElements();) { if (concatRemoteIpHeaderValue.length() > 0) { concatRemoteIpHeaderValue.append(", "); } concatRemoteIpHeaderValue.append(e.nextElement()); } String[] remoteIpHeaderValue = commaDelimitedListToStringArray(concatRemoteIpHeaderValue.toString()); int idx; // loop on remoteIpHeaderValue to find the first trusted remote ip and to build the proxies chain for (idx = remoteIpHeaderValue.length - 1; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; remoteIp = currentRemoteIp; if (internalProxies.matcher(currentRemoteIp).matches()) { // do nothing, internalProxies IPs are not appended to the } else if (trustedProxies != null && trustedProxies.matcher(currentRemoteIp).matches()) { proxiesHeaderValue.addFirst(currentRemoteIp); } else { idx--; // decrement idx because break statement doesn't do it break; } } // continue to loop on remoteIpHeaderValue to build the new value of the remoteIpHeader LinkedList<String> newRemoteIpHeaderValue = new LinkedList<String>(); for (; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; newRemoteIpHeaderValue.addFirst(currentRemoteIp); } if (remoteIp != null) { request.setRemoteAddr(remoteIp); request.setRemoteHost(remoteIp); // use request.coyoteRequest.mimeHeaders.setValue(str).setString(str) because request.addHeader(str, str) is no-op in Tomcat // 6.0 if (proxiesHeaderValue.size() == 0) { request.getCoyoteRequest().getMimeHeaders().removeHeader(proxiesHeader); } else { String commaDelimitedListOfProxies = listToCommaDelimitedString(proxiesHeaderValue); request.getCoyoteRequest().getMimeHeaders().setValue(proxiesHeader).setString(commaDelimitedListOfProxies); } if (newRemoteIpHeaderValue.size() == 0) { request.getCoyoteRequest().getMimeHeaders().removeHeader(remoteIpHeader); } else { String commaDelimitedRemoteIpHeaderValue = listToCommaDelimitedString(newRemoteIpHeaderValue); request.getCoyoteRequest().getMimeHeaders().setValue(remoteIpHeader).setString(commaDelimitedRemoteIpHeaderValue); } } if (protocolHeader != null) { String protocolHeaderValue = request.getHeader(protocolHeader); if (protocolHeaderValue == null) { // don't modify the secure,scheme and serverPort attributes // of the request } else if (protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue)) { request.setSecure(true); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString("https"); setPorts(request, httpsServerPort); } else { request.setSecure(false); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString("http"); setPorts(request, httpServerPort); } } if (log.isDebugEnabled()) { log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr '" + originalRemoteAddr + "', originalRemoteHost='" + originalRemoteHost + "', originalSecure='" + originalSecure + "', originalScheme='" + originalScheme + "' will be seen as newRemoteAddr='" + request.getRemoteAddr() + "', newRemoteHost='" + request.getRemoteHost() + "', newScheme='" + request.getScheme() + "', newSecure='" + request.isSecure() + "'"); } } else { if (log.isDebugEnabled()) { log.debug("Skip RemoteIpValve for request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "'"); } } if (requestAttributesEnabled) { request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE, request.getRemoteAddr()); request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE, request.getRemoteHost()); request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE, request.getProtocol()); request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE, Integer.valueOf(request.getServerPort())); } try { getNext().invoke(request, response); } finally { request.setRemoteAddr(originalRemoteAddr); request.setRemoteHost(originalRemoteHost); request.setSecure(originalSecure); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString(originalScheme); request.setServerPort(originalServerPort); } }
// in java/org/apache/catalina/valves/ValveBase.java
Override public void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Perform the request getNext().event(request, response, event); }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
public String getToken() throws IOException { if(ended) { return null ; } String result = null; subToken = false; parameter = false; int c = sr.read(); while (c != -1) { switch (c) { case ' ': result = buf.toString(); buf = new StringBuilder(); buf.append((char) c); return result; case '-': result = buf.toString(); buf = new StringBuilder(); subToken = true; return result; case '(': result = buf.toString(); buf = new StringBuilder(); parameter = true; return result; case ')': result = buf.toString(); buf = new StringBuilder(); break; default: buf.append((char) c); } c = sr.read(); } ended = true; if (buf.length() != 0) { return buf.toString(); } else { return null; } }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
public String getParameter()throws IOException { String result; if (!parameter) { return null; } parameter = false; int c = sr.read(); while (c != -1) { if (c == ')') { result = buf.toString(); buf = new StringBuilder(); return result; } buf.append((char) c); c = sr.read(); } return null; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
public String getWhiteSpaces() throws IOException { if(isEnded()) { return "" ; } StringBuilder whiteSpaces = new StringBuilder(); if (buf.length() > 0) { whiteSpaces.append(buf); buf = new StringBuilder(); } int c = sr.read(); while (Character.isWhitespace((char) c)) { whiteSpaces.append((char) c); c = sr.read(); } if (c == -1) { ended = true; } else { buf.append((char) c); } return whiteSpaces.toString(); }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
public String getRemains() throws IOException { StringBuilder remains = new StringBuilder(); for(int c = sr.read(); c != -1; c = sr.read()) { remains.append((char) c); } return remains.toString(); }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
protected AccessLogElement getLogElement(String token, PatternTokenizer tokenizer) throws IOException { if ("date".equals(token)) { return new DateElement(); } else if ("time".equals(token)) { if (tokenizer.hasSubToken()) { String nextToken = tokenizer.getToken(); if ("taken".equals(nextToken)) { return new ElapsedTimeElement(false); } } else { return new TimeElement(); } } else if ("bytes".equals(token)) { return new ByteSentElement(true); } else if ("cached".equals(token)) { /* I don't know how to evaluate this! */ return new StringElement("-"); } else if ("c".equals(token)) { String nextToken = tokenizer.getToken(); if ("ip".equals(nextToken)) { return new RemoteAddrElement(); } else if ("dns".equals(nextToken)) { return new HostElement(); } } else if ("s".equals(token)) { String nextToken = tokenizer.getToken(); if ("ip".equals(nextToken)) { return new LocalAddrElement(); } else if ("dns".equals(nextToken)) { return new AccessLogElement() { @Override public void addElement(StringBuilder buf, Date date, Request request, Response response, long time) { String value; try { value = InetAddress.getLocalHost().getHostName(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); value = "localhost"; } buf.append(value); } }; } } else if ("cs".equals(token)) { return getClientToServerElement(tokenizer); } else if ("sc".equals(token)) { return getServerToClientElement(tokenizer); } else if ("sr".equals(token) || "rs".equals(token)) { return getProxyElement(tokenizer); } else if ("x".equals(token)) { return getXParameterElement(tokenizer); } log.error("unable to decode with rest of chars starting: " + token); return null; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
protected AccessLogElement getClientToServerElement( PatternTokenizer tokenizer) throws IOException { if (tokenizer.hasSubToken()) { String token = tokenizer.getToken(); if ("method".equals(token)) { return new MethodElement(); } else if ("uri".equals(token)) { if (tokenizer.hasSubToken()) { token = tokenizer.getToken(); if ("stem".equals(token)) { return new RequestURIElement(); } else if ("query".equals(token)) { return new AccessLogElement() { @Override public void addElement(StringBuilder buf, Date date, Request request, Response response, long time) { String query = request.getQueryString(); if (query != null) { buf.append(query); } else { buf.append('-'); } } }; } } else { return new AccessLogElement() { @Override public void addElement(StringBuilder buf, Date date, Request request, Response response, long time) { String query = request.getQueryString(); if (query == null) { buf.append(request.getRequestURI()); } else { buf.append(request.getRequestURI()); buf.append('?'); buf.append(request.getQueryString()); } } }; } } } else if (tokenizer.hasParameter()) { String parameter = tokenizer.getParameter(); if (parameter == null) { log.error("No closing ) found for in decode"); return null; } return new RequestHeaderElement(parameter); } log.error("The next characters couldn't be decoded: " + tokenizer.getRemains()); return null; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
protected AccessLogElement getServerToClientElement( PatternTokenizer tokenizer) throws IOException { if (tokenizer.hasSubToken()) { String token = tokenizer.getToken(); if ("status".equals(token)) { return new HttpStatusCodeElement(); } else if ("comment".equals(token)) { return new StringElement("?"); } } else if (tokenizer.hasParameter()) { String parameter = tokenizer.getParameter(); if (parameter == null) { log.error("No closing ) found for in decode"); return null; } return new ResponseHeaderElement(parameter); } log.error("The next characters couldn't be decoded: " + tokenizer.getRemains()); return null; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
protected AccessLogElement getProxyElement(PatternTokenizer tokenizer) throws IOException { String token = null; if (tokenizer.hasSubToken()) { tokenizer.getToken(); return new StringElement("-"); } else if (tokenizer.hasParameter()) { tokenizer.getParameter(); return new StringElement("-"); } log.error("The next characters couldn't be decoded: " + token); return null; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
protected AccessLogElement getXParameterElement(PatternTokenizer tokenizer) throws IOException { if (!tokenizer.hasSubToken()) { log.error("x param in wrong format. Needs to be 'x-#(...)' read the docs!"); return null; } String token = tokenizer.getToken(); if ("threadname".equals(token)) { return new ThreadNameElement(); } if (!tokenizer.hasParameter()) { log.error("x param in wrong format. Needs to be 'x-#(...)' read the docs!"); return null; } String parameter = tokenizer.getParameter(); if (parameter == null) { log.error("No closing ) found for in decode"); return null; } if ("A".equals(token)) { return new ServletContextElement(parameter); } else if ("C".equals(token)) { return new CookieElement(parameter); } else if ("R".equals(token)) { return new RequestAttributeElement(parameter); } else if ("S".equals(token)) { return new SessionAttributeElement(parameter); } else if ("H".equals(token)) { return getServletRequestElement(parameter); } else if ("P".equals(token)) { return new RequestParameterElement(parameter); } else if ("O".equals(token)) { return new ResponseAllHeaderElement(parameter); } log.error("x param for servlet request, couldn't decode value: " + token); return null; }
// in java/org/apache/catalina/authenticator/SingleSignOn.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { request.removeNote(Constants.REQ_SSOID_NOTE); // Has a valid user already been authenticated? if (containerLog.isDebugEnabled()) { containerLog.debug("Process request for '" + request.getRequestURI() + "'"); } if (request.getUserPrincipal() != null) { if (containerLog.isDebugEnabled()) { containerLog.debug(" Principal '" + request.getUserPrincipal().getName() + "' has already been authenticated"); } getNext().invoke(request, response); return; } // Check for the single sign on cookie if (containerLog.isDebugEnabled()) { containerLog.debug(" Checking for SSO cookie"); } Cookie cookie = null; Cookie cookies[] = request.getCookies(); if (cookies == null) { cookies = new Cookie[0]; } for (int i = 0; i < cookies.length; i++) { if (Constants.SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) { cookie = cookies[i]; break; } } if (cookie == null) { if (containerLog.isDebugEnabled()) { containerLog.debug(" SSO cookie is not present"); } getNext().invoke(request, response); return; } // Look up the cached Principal associated with this cookie value if (containerLog.isDebugEnabled()) { containerLog.debug(" Checking for cached principal for " + cookie.getValue()); } SingleSignOnEntry entry = lookup(cookie.getValue()); if (entry != null) { if (containerLog.isDebugEnabled()) { containerLog.debug(" Found cached principal '" + (entry.getPrincipal() != null ? entry.getPrincipal().getName() : "") + "' with auth type '" + entry.getAuthType() + "'"); } request.setNote(Constants.REQ_SSOID_NOTE, cookie.getValue()); // Only set security elements if reauthentication is not required if (!getRequireReauthentication()) { request.setAuthType(entry.getAuthType()); request.setUserPrincipal(entry.getPrincipal()); } } else { if (containerLog.isDebugEnabled()) { containerLog.debug(" No cached principal found, erasing SSO cookie"); } cookie.setMaxAge(0); response.addCookie(cookie); } // Invoke the next Valve in our pipeline getNext().invoke(request, response); }
// in java/org/apache/catalina/authenticator/SSLAuthenticator.java
Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { // Have we already authenticated someone? Principal principal = request.getUserPrincipal(); //String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (containerLog.isDebugEnabled()) { containerLog.debug("Already authenticated '" + principal.getName() + "'"); } // Associate the session with any existing SSO session in order // to get coordinated session invalidation at logout String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return (true); } // NOTE: We don't try to reauthenticate using any existing SSO session, // because that will only work if the original authentication was // BASIC or FORM, which are less secure than the CLIENT_CERT auth-type // specified for this webapp // // Uncomment below to allow previous FORM or BASIC authentications // to authenticate users for this webapp // TODO make this a configurable attribute (in SingleSignOn??) /* // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); // Try to reauthenticate using data cached by SSO. If this fails, // either the original SSO logon was of DIGEST or SSL (which // we can't reauthenticate ourselves because there is no // cached username and password), or the realm denied // the user's reauthentication for some reason. // In either case we have to prompt the user for a logon if (reauthenticateFromSSO(ssoId, request)) return true; } */ // Retrieve the certificate chain for this client if (containerLog.isDebugEnabled()) { containerLog.debug(" Looking up certificates"); } X509Certificate certs[] = (X509Certificate[]) request.getAttribute(Globals.CERTIFICATES_ATTR); if ((certs == null) || (certs.length < 1)) { try { request.getCoyoteRequest().action (ActionCode.REQ_SSL_CERTIFICATE, null); } catch (IllegalStateException ise) { // Request body was too large for save buffer response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.certificates")); return false; } certs = (X509Certificate[]) request.getAttribute(Globals.CERTIFICATES_ATTR); } if ((certs == null) || (certs.length < 1)) { if (containerLog.isDebugEnabled()) { containerLog.debug(" No certificates included with this request"); } response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.certificates")); return (false); } // Authenticate the specified certificate chain principal = context.getRealm().authenticate(certs); if (principal == null) { if (containerLog.isDebugEnabled()) { containerLog.debug(" Realm.authenticate() returned false"); } response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.unauthorized")); return (false); } // Cache the principal (if requested) and record this authentication register(request, response, principal, HttpServletRequest.CLIENT_CERT_AUTH, null, null); return (true); }
// in java/org/apache/catalina/authenticator/NonLoginAuthenticator.java
Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { Principal principal = request.getPrincipal(); if (principal != null) { // excellent... we have already authenticated the client somehow, // probably from another container that has a login-config if (containerLog.isDebugEnabled()) containerLog.debug("Already authenticated as '" + principal.getName() + "'"); if (cache) { // create a new session (only if necessary) Session session = request.getSessionInternal(true); // save the inherited Principal (if necessary) in this // session so it can remain authenticated until it expires session.setPrincipal(principal); // is there an SSO session cookie? String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (ssoId != null) { if (containerLog.isDebugEnabled()) containerLog.debug("User authenticated by existing SSO"); // Associate session with the existing SSO ID if necessary associate(ssoId, session); } } // user was already authenticated, with or without a cookie return true; } // No Principal means the user is not already authenticated // and so will not be assigned any roles. It is safe to // to say the user is now authenticated because access to // protected resources will only be allowed with a matching role. // i.e. SC_FORBIDDEN (403 status) will be generated later. if (containerLog.isDebugEnabled()) containerLog.debug("User authenticated without any roles"); return true; }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (log.isDebugEnabled()) { log.debug("Security checking request " + request.getMethod() + " " + request.getRequestURI()); } // Have we got a cached authenticated Principal to record? if (cache) { Principal principal = request.getUserPrincipal(); if (principal == null) { Session session = request.getSessionInternal(false); if (session != null) { principal = session.getPrincipal(); if (principal != null) { if (log.isDebugEnabled()) { log.debug("We have cached auth type " + session.getAuthType() + " for principal " + session.getPrincipal()); } request.setAuthType(session.getAuthType()); request.setUserPrincipal(principal); } } } } // Special handling for form-based logins to deal with the case // where the login form (and therefore the "j_security_check" URI // to which it submits) might be outside the secured area String contextPath = this.context.getPath(); String requestURI = request.getDecodedRequestURI(); if (requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION)) { if (!authenticate(request, response)) { if (log.isDebugEnabled()) { log.debug(" Failed authenticate() test ??" + requestURI ); } return; } } // The Servlet may specify security constraints through annotations. // Ensure that they have been processed before constraints are checked Wrapper wrapper = (Wrapper) request.getMappingData().wrapper; if (wrapper != null) { wrapper.servletSecurityAnnotationScan(); } Realm realm = this.context.getRealm(); // Is this request URI subject to a security constraint? SecurityConstraint [] constraints = realm.findSecurityConstraints(request, this.context); if (constraints == null && !context.getPreemptiveAuthentication()) { if (log.isDebugEnabled()) { log.debug(" Not subject to any constraint"); } getNext().invoke(request, response); return; } // Make sure that constrained resources are not cached by web proxies // or browsers as caching can provide a security hole if (constraints != null && disableProxyCaching && !"POST".equalsIgnoreCase(request.getMethod())) { if (securePagesWithPragma) { // Note: These can cause problems with downloading files with IE response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); } else { response.setHeader("Cache-Control", "private"); } response.setHeader("Expires", DATE_ONE); } int i; if (constraints != null) { // Enforce any user data constraint for this security constraint if (log.isDebugEnabled()) { log.debug(" Calling hasUserDataPermission()"); } if (!realm.hasUserDataPermission(request, response, constraints)) { if (log.isDebugEnabled()) { log.debug(" Failed hasUserDataPermission() test"); } /* * ASSERT: Authenticator already set the appropriate * HTTP status code, so we do not have to do anything special */ return; } } // Since authenticate modifies the response on failure, // we have to check for allow-from-all first. boolean authRequired; if (constraints == null) { authRequired = false; } else { authRequired = true; for(i=0; i < constraints.length && authRequired; i++) { if(!constraints[i].getAuthConstraint()) { authRequired = false; } else if(!constraints[i].getAllRoles()) { String [] roles = constraints[i].findAuthRoles(); if(roles == null || roles.length == 0) { authRequired = false; } } } } if (!authRequired && context.getPreemptiveAuthentication()) { authRequired = request.getCoyoteRequest().getMimeHeaders().getValue( "authorization") != null; } if (!authRequired && context.getPreemptiveAuthentication()) { X509Certificate[] certs = (X509Certificate[]) request.getAttribute( Globals.CERTIFICATES_ATTR); authRequired = certs != null && certs.length > 0; } if(authRequired) { if (log.isDebugEnabled()) { log.debug(" Calling authenticate()"); } if (!authenticate(request, response)) { if (log.isDebugEnabled()) { log.debug(" Failed authenticate() test"); } /* * ASSERT: Authenticator already set the appropriate * HTTP status code, so we do not have to do anything * special */ return; } } if (constraints != null) { if (log.isDebugEnabled()) { log.debug(" Calling accessControl()"); } if (!realm.hasResourcePermission(request, response, constraints, this.context)) { if (log.isDebugEnabled()) { log.debug(" Failed accessControl() test"); } /* * ASSERT: AccessControl method has already set the * appropriate HTTP status code, so we do not have to do * anything special */ return; } } // Any and all specified constraints have been satisfied if (log.isDebugEnabled()) { log.debug(" Successfully passed all security constraints"); } getNext().invoke(request, response); }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { // Have we already authenticated someone? Principal principal = request.getUserPrincipal(); //String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (log.isDebugEnabled()) { log.debug("Already authenticated '" + principal.getName() + "'"); } // Associate the session with any existing SSO session in order // to get coordinated session invalidation at logout String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return (true); } // NOTE: We don't try to reauthenticate using any existing SSO session, // because that will only work if the original authentication was // BASIC or FORM, which are less secure than the DIGEST auth-type // specified for this webapp // // Uncomment below to allow previous FORM or BASIC authentications // to authenticate users for this webapp // TODO make this a configurable attribute (in SingleSignOn??) /* // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); // Try to reauthenticate using data cached by SSO. If this fails, // either the original SSO logon was of DIGEST or SSL (which // we can't reauthenticate ourselves because there is no // cached username and password), or the realm denied // the user's reauthentication for some reason. // In either case we have to prompt the user for a logon if (reauthenticateFromSSO(ssoId, request)) return true; } */ // Validate any credentials already included with this request String authorization = request.getHeader("authorization"); DigestInfo digestInfo = new DigestInfo(getOpaque(), getNonceValidity(), getKey(), cnonces, isValidateUri()); if (authorization != null) { if (digestInfo.validate(request, authorization)) { principal = digestInfo.authenticate(context.getRealm()); } if (principal != null) { String username = parseUsername(authorization); register(request, response, principal, HttpServletRequest.DIGEST_AUTH, username, null); return (true); } } // Send an "unauthorized" response and an appropriate challenge // Next, generate a nonce token (that is a token which is supposed // to be unique). String nonce = generateNonce(request); setAuthenticateHeader(request, response, nonce, digestInfo.isNonceStale()); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); // hres.flushBuffer(); return (false); }
// in java/org/apache/catalina/authenticator/BasicAuthenticator.java
Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { // Have we already authenticated someone? Principal principal = request.getUserPrincipal(); String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (log.isDebugEnabled()) { log.debug("Already authenticated '" + principal.getName() + "'"); } // Associate the session with any existing SSO session if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return (true); } // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) { log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); } /* Try to reauthenticate using data cached by SSO. If this fails, either the original SSO logon was of DIGEST or SSL (which we can't reauthenticate ourselves because there is no cached username and password), or the realm denied the user's reauthentication for some reason. In either case we have to prompt the user for a logon */ if (reauthenticateFromSSO(ssoId, request)) { return true; } } // Validate any credentials already included with this request String username = null; String password = null; MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders() .getValue("authorization"); if (authorization != null) { authorization.toBytes(); ByteChunk authorizationBC = authorization.getByteChunk(); if (authorizationBC.startsWithIgnoreCase("basic ", 0)) { authorizationBC.setOffset(authorizationBC.getOffset() + 6); // FIXME: Add trimming // authorizationBC.trim(); CharChunk authorizationCC = authorization.getCharChunk(); Base64.decode(authorizationBC, authorizationCC); // Get username and password int colon = authorizationCC.indexOf(':'); if (colon < 0) { username = authorizationCC.toString(); } else { char[] buf = authorizationCC.getBuffer(); username = new String(buf, 0, colon); password = new String(buf, colon + 1, authorizationCC.getEnd() - colon - 1); } authorizationBC.setOffset(authorizationBC.getOffset() - 6); } principal = context.getRealm().authenticate(username, password); if (principal != null) { register(request, response, principal, HttpServletRequest.BASIC_AUTH, username, password); return (true); } } StringBuilder value = new StringBuilder(16); value.append("Basic realm=\""); value.append(getRealmName(context)); value.append('\"'); response.setHeader(AUTH_HEADER_NAME, value.toString()); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return (false); }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { // Have we already authenticated someone? Principal principal = request.getUserPrincipal(); String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (log.isDebugEnabled()) { log.debug("Already authenticated '" + principal.getName() + "'"); } // Associate the session with any existing SSO session if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return true; } // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) { log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); } /* Try to reauthenticate using data cached by SSO. If this fails, either the original SSO logon was of DIGEST or SSL (which we can't reauthenticate ourselves because there is no cached username and password), or the realm denied the user's reauthentication for some reason. In either case we have to prompt the user for a logon */ if (reauthenticateFromSSO(ssoId, request)) { return true; } } MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders() .getValue("authorization"); if (authorization == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("authenticator.noAuthHeader")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } authorization.toBytes(); ByteChunk authorizationBC = authorization.getByteChunk(); if (!authorizationBC.startsWithIgnoreCase("negotiate ", 0)) { if (log.isDebugEnabled()) { log.debug(sm.getString( "spnegoAuthenticator.authHeaderNotNego")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } authorizationBC.setOffset(authorizationBC.getOffset() + 10); // FIXME: Add trimming // authorizationBC.trim(); ByteChunk decoded = new ByteChunk(); Base64.decode(authorizationBC, decoded); if (decoded.getLength() == 0) { if (log.isDebugEnabled()) { log.debug(sm.getString( "spnegoAuthenticator.authHeaderNoToken")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } LoginContext lc = null; GSSContext gssContext = null; byte[] outToken = null; try { try { lc = new LoginContext(getLoginConfigName()); lc.login(); } catch (LoginException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; } // Assume the GSSContext is stateless // TODO: Confirm this assumption final GSSManager manager = GSSManager.getInstance(); final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() { @Override public GSSCredential run() throws GSSException { return manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME, new Oid("1.3.6.1.5.5.2"), GSSCredential.ACCEPT_ONLY); } }; gssContext = manager.createContext(Subject.doAs(lc.getSubject(), action)); outToken = gssContext.acceptSecContext(decoded.getBytes(), decoded.getOffset(), decoded.getLength()); if (outToken == null) { if (log.isDebugEnabled()) { log.debug(sm.getString( "spnegoAuthenticator.ticketValidateFail")); } // Start again response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } principal = context.getRealm().authenticate(gssContext, isStoreDelegatedCredential()); } catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail", e)); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } catch (PrivilegedActionException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail", e)); response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } finally { if (gssContext != null) { try { gssContext.dispose(); } catch (GSSException e) { // Ignore } } if (lc != null) { try { lc.logout(); } catch (LoginException e) { // Ignore } } } // Send response token on success and failure response.setHeader("WWW-Authenticate", "Negotiate " + Base64.encode(outToken)); if (principal != null) { register(request, response, principal, Constants.SPNEGO_METHOD, principal.getName(), null); return true; } response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { // References to objects we will need later Session session = null; // Have we already authenticated someone? Principal principal = request.getUserPrincipal(); String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (log.isDebugEnabled()) { log.debug("Already authenticated '" + principal.getName() + "'"); } // Associate the session with any existing SSO session if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return (true); } // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) { log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); } // Try to reauthenticate using data cached by SSO. If this fails, // either the original SSO logon was of DIGEST or SSL (which // we can't reauthenticate ourselves because there is no // cached username and password), or the realm denied // the user's reauthentication for some reason. // In either case we have to prompt the user for a logon */ if (reauthenticateFromSSO(ssoId, request)) { return true; } } // Have we authenticated this user before but have caching disabled? if (!cache) { session = request.getSessionInternal(true); if (log.isDebugEnabled()) { log.debug("Checking for reauthenticate in session " + session); } String username = (String) session.getNote(Constants.SESS_USERNAME_NOTE); String password = (String) session.getNote(Constants.SESS_PASSWORD_NOTE); if ((username != null) && (password != null)) { if (log.isDebugEnabled()) { log.debug("Reauthenticating username '" + username + "'"); } principal = context.getRealm().authenticate(username, password); if (principal != null) { session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal); if (!matchRequest(request)) { register(request, response, principal, HttpServletRequest.FORM_AUTH, username, password); return (true); } } if (log.isDebugEnabled()) { log.debug("Reauthentication failed, proceed normally"); } } } // Is this the re-submit of the original request URI after successful // authentication? If so, forward the *original* request instead. if (matchRequest(request)) { session = request.getSessionInternal(true); if (log.isDebugEnabled()) { log.debug("Restore request from session '" + session.getIdInternal() + "'"); } principal = (Principal) session.getNote(Constants.FORM_PRINCIPAL_NOTE); register(request, response, principal, HttpServletRequest.FORM_AUTH, (String) session.getNote(Constants.SESS_USERNAME_NOTE), (String) session.getNote(Constants.SESS_PASSWORD_NOTE)); // If we're caching principals we no longer need the username // and password in the session, so remove them if (cache) { session.removeNote(Constants.SESS_USERNAME_NOTE); session.removeNote(Constants.SESS_PASSWORD_NOTE); } if (restoreRequest(request, session)) { if (log.isDebugEnabled()) { log.debug("Proceed to restored request"); } return (true); } else { if (log.isDebugEnabled()) { log.debug("Restore of original request failed"); } response.sendError(HttpServletResponse.SC_BAD_REQUEST); return (false); } } // Acquire references to objects we will need to evaluate MessageBytes uriMB = MessageBytes.newInstance(); CharChunk uriCC = uriMB.getCharChunk(); uriCC.setLimit(-1); String contextPath = request.getContextPath(); String requestURI = request.getDecodedRequestURI(); // Is this the action request from the login page? boolean loginAction = requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION); LoginConfig config = context.getLoginConfig(); // No -- Save this request and redirect to the form login page if (!loginAction) { session = request.getSessionInternal(true); if (log.isDebugEnabled()) { log.debug("Save request in session '" + session.getIdInternal() + "'"); } try { saveRequest(request, session); } catch (IOException ioe) { log.debug("Request body too big to save during authentication"); response.sendError(HttpServletResponse.SC_FORBIDDEN, sm.getString("authenticator.requestBodyTooBig")); return (false); } forwardToLoginPage(request, response, config); return (false); } // Yes -- Acknowledge the request, validate the specified credentials // and redirect to the error page if they are not correct request.getResponse().sendAcknowledgement(); Realm realm = context.getRealm(); if (characterEncoding != null) { request.setCharacterEncoding(characterEncoding); } String username = request.getParameter(Constants.FORM_USERNAME); String password = request.getParameter(Constants.FORM_PASSWORD); if (log.isDebugEnabled()) { log.debug("Authenticating username '" + username + "'"); } principal = realm.authenticate(username, password); if (principal == null) { forwardToErrorPage(request, response, config); return (false); } if (log.isDebugEnabled()) { log.debug("Authentication of '" + username + "' was successful"); } if (session == null) { session = request.getSessionInternal(false); } if (session == null) { if (containerLog.isDebugEnabled()) { containerLog.debug ("User took so long to log on the session expired"); } if (landingPage == null) { response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT, sm.getString("authenticator.sessionExpired")); } else { // Make the authenticator think the user originally requested // the landing page String uri = request.getContextPath() + landingPage; SavedRequest saved = new SavedRequest(); saved.setMethod("GET"); saved.setRequestURI(uri); request.getSessionInternal(true).setNote( Constants.FORM_REQUEST_NOTE, saved); response.sendRedirect(response.encodeRedirectURL(uri)); } return (false); } // Save the authenticated Principal in our session session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal); // Save the username and password as well session.setNote(Constants.SESS_USERNAME_NOTE, username); session.setNote(Constants.SESS_PASSWORD_NOTE, password); // Redirect the user to the original request URI (which will cause // the original request to be restored) requestURI = savedRequestURL(session); if (log.isDebugEnabled()) { log.debug("Redirecting to original '" + requestURI + "'"); } if (requestURI == null) { if (landingPage == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, sm.getString("authenticator.formlogin")); } else { // Make the authenticator think the user originally requested // the landing page String uri = request.getContextPath() + landingPage; SavedRequest saved = new SavedRequest(); saved.setMethod("GET"); saved.setRequestURI(uri); session.setNote(Constants.FORM_REQUEST_NOTE, saved); response.sendRedirect(response.encodeRedirectURL(uri)); } } else { response.sendRedirect(response.encodeRedirectURL(requestURI)); } return (false); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
protected void forwardToLoginPage(Request request, HttpServletResponse response, LoginConfig config) throws IOException { if (log.isDebugEnabled()) { log.debug(sm.getString("formAuthenticator.forwardLogin", request.getRequestURI(), request.getMethod(), config.getLoginPage(), context.getName())); } String loginPage = config.getLoginPage(); if (loginPage == null || loginPage.length() == 0) { String msg = sm.getString("formAuthenticator.noLoginPage", context.getName()); log.warn(msg); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); return; } // Always use GET for the login page, regardless of the method used String oldMethod = request.getMethod(); request.getCoyoteRequest().method().setString("GET"); RequestDispatcher disp = context.getServletContext().getRequestDispatcher(loginPage); try { if (context.fireRequestInitEvent(request)) { disp.forward(request.getRequest(), response); context.fireRequestDestroyEvent(request); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardLoginFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } finally { // Restore original method so that it is written into access log request.getCoyoteRequest().method().setString(oldMethod); } }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
protected void forwardToErrorPage(Request request, HttpServletResponse response, LoginConfig config) throws IOException { String errorPage = config.getErrorPage(); if (errorPage == null || errorPage.length() == 0) { String msg = sm.getString("formAuthenticator.noErrorPage", context.getName()); log.warn(msg); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); return; } RequestDispatcher disp = context.getServletContext().getRequestDispatcher (config.getErrorPage()); try { if (context.fireRequestInitEvent(request)) { disp.forward(request.getRequest(), response); context.fireRequestDestroyEvent(request); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardErrorFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
protected boolean restoreRequest(Request request, Session session) throws IOException { // Retrieve and remove the SavedRequest object from our session SavedRequest saved = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE); session.removeNote(Constants.FORM_REQUEST_NOTE); session.removeNote(Constants.FORM_PRINCIPAL_NOTE); if (saved == null) { return (false); } // Modify our current request to reflect the original one request.clearCookies(); Iterator<Cookie> cookies = saved.getCookies(); while (cookies.hasNext()) { request.addCookie(cookies.next()); } String method = saved.getMethod(); MimeHeaders rmh = request.getCoyoteRequest().getMimeHeaders(); rmh.recycle(); boolean cachable = "GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method); Iterator<String> names = saved.getHeaderNames(); while (names.hasNext()) { String name = names.next(); // The browser isn't expecting this conditional response now. // Assuming that it can quietly recover from an unexpected 412. // BZ 43687 if(!("If-Modified-Since".equalsIgnoreCase(name) || (cachable && "If-None-Match".equalsIgnoreCase(name)))) { Iterator<String> values = saved.getHeaderValues(name); while (values.hasNext()) { rmh.addValue(name).setString(values.next()); } } } request.clearLocales(); Iterator<Locale> locales = saved.getLocales(); while (locales.hasNext()) { request.addLocale(locales.next()); } request.getCoyoteRequest().getParameters().recycle(); request.getCoyoteRequest().getParameters().setQueryStringEncoding( request.getConnector().getURIEncoding()); // Swallow any request body since we will be replacing it byte[] buffer = new byte[4096]; InputStream is = request.createInputStream(); while (is.read(buffer) >= 0) { // Ignore request body } ByteChunk body = saved.getBody(); if (body != null) { request.getCoyoteRequest().action (ActionCode.REQ_SET_BODY_REPLAY, body); // Set content type MessageBytes contentType = MessageBytes.newInstance(); // If no content type specified, use default for POST String savedContentType = saved.getContentType(); if (savedContentType == null && "POST".equalsIgnoreCase(method)) { savedContentType = "application/x-www-form-urlencoded"; } contentType.setString(savedContentType); request.getCoyoteRequest().setContentType(contentType); } request.getCoyoteRequest().method().setString(method); request.getCoyoteRequest().queryString().setString (saved.getQueryString()); request.getCoyoteRequest().requestURI().setString (saved.getRequestURI()); return (true); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
protected void saveRequest(Request request, Session session) throws IOException { // Create and populate a SavedRequest object for this request SavedRequest saved = new SavedRequest(); Cookie cookies[] = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { saved.addCookie(cookies[i]); } } Enumeration<String> names = request.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); Enumeration<String> values = request.getHeaders(name); while (values.hasMoreElements()) { String value = values.nextElement(); saved.addHeader(name, value); } } Enumeration<Locale> locales = request.getLocales(); while (locales.hasMoreElements()) { Locale locale = locales.nextElement(); saved.addLocale(locale); } // May need to acknowledge a 100-continue expectation request.getResponse().sendAcknowledgement(); ByteChunk body = new ByteChunk(); body.setLimit(request.getConnector().getMaxSavePostSize()); byte[] buffer = new byte[4096]; int bytesRead; InputStream is = request.getInputStream(); while ( (bytesRead = is.read(buffer) ) >= 0) { body.append(buffer, 0, bytesRead); } // Only save the request body if there is something to save if (body.getLength() > 0) { saved.setContentType(request.getContentType()); saved.setBody(body); } saved.setMethod(request.getMethod()); saved.setQueryString(request.getQueryString()); saved.setRequestURI(request.getRequestURI()); // Stash the SavedRequest in our session for later use session.setNote(Constants.FORM_REQUEST_NOTE, saved); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Serve the requested resource, including the data content serveResource(request, response, true); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doHead(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Serve the requested resource, without the data content serveResource(request, response, false); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { StringBuilder allow = new StringBuilder(); // There is a doGet method allow.append("GET, HEAD"); // There is a doPost allow.append(", POST"); // There is a doPut allow.append(", PUT"); // There is a doDelete allow.append(", DELETE"); // Trace - assume disabled unless we can prove otherwise if (req instanceof RequestFacade && ((RequestFacade) req).getAllowTrace()) { allow.append(", TRACE"); } // Always allow options allow.append(", OPTIONS"); resp.setHeader("Allow", allow.toString()); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String path = getRelativePath(req); boolean exists = true; try { resources.lookup(path); } catch (NamingException e) { exists = false; } boolean result = true; // Temp. content file used to support partial PUT File contentFile = null; Range range = parseContentRange(req, resp); InputStream resourceInputStream = null; // Append data specified in ranges to existing content for this // resource - create a temp. file on the local filesystem to // perform this operation // Assume just one range is specified for now if (range != null) { contentFile = executePartialPut(req, range, path); resourceInputStream = new FileInputStream(contentFile); } else { resourceInputStream = req.getInputStream(); } try { Resource newResource = new Resource(resourceInputStream); // FIXME: Add attributes if (exists) { resources.rebind(path, newResource); } else { resources.bind(path, newResource); } } catch(NamingException e) { result = false; } if (result) { if (exists) { resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { resp.setStatus(HttpServletResponse.SC_CREATED); } } else { resp.sendError(HttpServletResponse.SC_CONFLICT); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected File executePartialPut(HttpServletRequest req, Range range, String path) throws IOException { // Append data specified in ranges to existing content for this // resource - create a temp. file on the local filesystem to // perform this operation File tempDir = (File) getServletContext().getAttribute (ServletContext.TEMPDIR); // Convert all '/' characters to '.' in resourcePath String convertedResourcePath = path.replace('/', '.'); File contentFile = new File(tempDir, convertedResourcePath); if (contentFile.createNewFile()) { // Clean up contentFile when Tomcat is terminated contentFile.deleteOnExit(); } RandomAccessFile randAccessContentFile = new RandomAccessFile(contentFile, "rw"); Resource oldResource = null; try { Object obj = resources.lookup(path); if (obj instanceof Resource) oldResource = (Resource) obj; } catch (NamingException e) { // Ignore } // Copy data in oldRevisionContent to contentFile if (oldResource != null) { BufferedInputStream bufOldRevStream = new BufferedInputStream(oldResource.streamContent(), BUFFER_SIZE); int numBytesRead; byte[] copyBuffer = new byte[BUFFER_SIZE]; while ((numBytesRead = bufOldRevStream.read(copyBuffer)) != -1) { randAccessContentFile.write(copyBuffer, 0, numBytesRead); } bufOldRevStream.close(); } randAccessContentFile.setLength(range.length); // Append data in request input stream to contentFile randAccessContentFile.seek(range.start); int numBytesRead; byte[] transferBuffer = new byte[BUFFER_SIZE]; BufferedInputStream requestBufInStream = new BufferedInputStream(req.getInputStream(), BUFFER_SIZE); while ((numBytesRead = requestBufInStream.read(transferBuffer)) != -1) { randAccessContentFile.write(transferBuffer, 0, numBytesRead); } randAccessContentFile.close(); requestBufInStream.close(); return contentFile; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String path = getRelativePath(req); boolean exists = true; try { resources.lookup(path); } catch (NamingException e) { exists = false; } if (exists) { boolean result = true; try { resources.unbind(path); } catch (NamingException e) { result = false; } if (result) { resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected boolean checkIfHeaders(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) throws IOException { return checkIfMatch(request, response, resourceAttributes) && checkIfModifiedSince(request, response, resourceAttributes) && checkIfNoneMatch(request, response, resourceAttributes) && checkIfUnmodifiedSince(request, response, resourceAttributes); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException { boolean serveContent = content; // Identify the requested resource path String path = getRelativePath(request); if (debug > 0) { if (serveContent) log("DefaultServlet.serveResource: Serving resource '" + path + "' headers and data"); else log("DefaultServlet.serveResource: Serving resource '" + path + "' headers only"); } CacheEntry cacheEntry = resources.lookupCache(path); if (!cacheEntry.exists) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } else { // We're included // SRV.9.3 says we must throw a FNFE throw new FileNotFoundException( sm.getString("defaultServlet.missingResource", requestUri)); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } // If the resource is not a collection, and the resource path // ends with "/" or "\", return NOT FOUND if (cacheEntry.context == null) { if (path.endsWith("/") || (path.endsWith("\\"))) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } } boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST; // Check if the conditions specified in the optional If headers are // satisfied. if (cacheEntry.context == null) { // Checking If headers boolean included = (request.getAttribute( RequestDispatcher.INCLUDE_CONTEXT_PATH) != null); if (!included && !isError && !checkIfHeaders(request, response, cacheEntry.attributes)) { return; } } // Find content type. String contentType = cacheEntry.attributes.getMimeType(); if (contentType == null) { contentType = getServletContext().getMimeType(cacheEntry.name); cacheEntry.attributes.setMimeType(contentType); } ArrayList<Range> ranges = null; long contentLength = -1L; if (cacheEntry.context != null) { // Skip directory listings if we have been configured to // suppress them if (!listings) { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); return; } contentType = "text/html;charset=UTF-8"; } else { if (!isError) { if (useAcceptRanges) { // Accept ranges header response.setHeader("Accept-Ranges", "bytes"); } // Parse range specifier ranges = parseRange(request, response, cacheEntry.attributes); // ETag header response.setHeader("ETag", cacheEntry.attributes.getETag()); // Last-Modified header response.setHeader("Last-Modified", cacheEntry.attributes.getLastModifiedHttp()); } // Get content length contentLength = cacheEntry.attributes.getContentLength(); // Special case for zero length files, which would cause a // (silent) ISE when setting the output buffer size if (contentLength == 0L) { serveContent = false; } } ServletOutputStream ostream = null; PrintWriter writer = null; if (serveContent) { // Trying to retrieve the servlet output stream try { ostream = response.getOutputStream(); } catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } } } // Check to see if a Filter, Valve of wrapper has written some content. // If it has, disable range requests and setting of a content length // since neither can be done reliably. ServletResponse r = response; long contentWritten = 0; while (r instanceof ServletResponseWrapper) { r = ((ServletResponseWrapper) r).getResponse(); } if (r instanceof ResponseFacade) { contentWritten = ((ResponseFacade) r).getContentWritten(); } if (contentWritten > 0) { ranges = FULL; } if ( (cacheEntry.context != null) || isError || ( ((ranges == null) || (ranges.isEmpty())) && (request.getHeader("Range") == null) ) || (ranges == FULL) ) { // Set the appropriate output headers if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if ((cacheEntry.resource != null) && (contentLength >= 0) && (!serveContent || ostream != null)) { if (debug > 0) log("DefaultServlet.serveFile: contentLength=" + contentLength); // Don't set a content length if something else has already // written to the response. if (contentWritten == 0) { if (contentLength < Integer.MAX_VALUE) { response.setContentLength((int) contentLength); } else { // Set the content-length as String to be able to use a // long response.setHeader("content-length", "" + contentLength); } } } InputStream renderResult = null; if (cacheEntry.context != null) { if (serveContent) { // Serve the directory browser renderResult = render(getPathPrefix(request), cacheEntry); } } // Copy the input stream to our output stream (if requested) if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, contentLength, null)) copy(cacheEntry, renderResult, ostream); } else { copy(cacheEntry, renderResult, writer); } } } else { if ((ranges == null) || (ranges.isEmpty())) return; // Partial content response. response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); if (ranges.size() == 1) { Range range = ranges.get(0); response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; if (length < Integer.MAX_VALUE) { response.setContentLength((int) length); } else { // Set the content-length as String to be able to use a long response.setHeader("content-length", "" + length); } if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, range.end - range.start + 1, range)) copy(cacheEntry, ostream, range); } else { // we should not get here throw new IllegalStateException(); } } } else { response.setContentType("multipart/byteranges; boundary=" + mimeSeparation); if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { copy(cacheEntry, ostream, ranges.iterator(), contentType); } else { // we should not get here throw new IllegalStateException(); } } } } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected Range parseContentRange(HttpServletRequest request, HttpServletResponse response) throws IOException { // Retrieving the content-range header (if any is specified String rangeHeader = request.getHeader("Content-Range"); if (rangeHeader == null) return null; // bytes is the only range unit supported if (!rangeHeader.startsWith("bytes")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } rangeHeader = rangeHeader.substring(6).trim(); int dashPos = rangeHeader.indexOf('-'); int slashPos = rangeHeader.indexOf('/'); if (dashPos == -1) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } if (slashPos == -1) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } Range range = new Range(); try { range.start = Long.parseLong(rangeHeader.substring(0, dashPos)); range.end = Long.parseLong(rangeHeader.substring(dashPos + 1, slashPos)); range.length = Long.parseLong (rangeHeader.substring(slashPos + 1, rangeHeader.length())); } catch (NumberFormatException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } if (!range.validate()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } return range; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected ArrayList<Range> parseRange(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) throws IOException { // Checking If-Range String headerValue = request.getHeader("If-Range"); if (headerValue != null) { long headerValueTime = (-1L); try { headerValueTime = request.getDateHeader("If-Range"); } catch (IllegalArgumentException e) { // Ignore } String eTag = resourceAttributes.getETag(); long lastModified = resourceAttributes.getLastModified(); if (headerValueTime == (-1L)) { // If the ETag the client gave does not match the entity // etag, then the entire entity is returned. if (!eTag.equals(headerValue.trim())) return FULL; } else { // If the timestamp of the entity the client got is older than // the last modification date of the entity, the entire entity // is returned. if (lastModified > (headerValueTime + 1000)) return FULL; } } long fileLength = resourceAttributes.getContentLength(); if (fileLength == 0) return null; // Retrieving the range header (if any is specified String rangeHeader = request.getHeader("Range"); if (rangeHeader == null) return null; // bytes is the only range unit supported (and I don't see the point // of adding new ones). if (!rangeHeader.startsWith("bytes")) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } rangeHeader = rangeHeader.substring(6); // Vector which will contain all the ranges which are successfully // parsed. ArrayList<Range> result = new ArrayList<Range>(); StringTokenizer commaTokenizer = new StringTokenizer(rangeHeader, ","); // Parsing the range list while (commaTokenizer.hasMoreTokens()) { String rangeDefinition = commaTokenizer.nextToken().trim(); Range currentRange = new Range(); currentRange.length = fileLength; int dashPos = rangeDefinition.indexOf('-'); if (dashPos == -1) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } if (dashPos == 0) { try { long offset = Long.parseLong(rangeDefinition); currentRange.start = fileLength + offset; currentRange.end = fileLength - 1; } catch (NumberFormatException e) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse .SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } } else { try { currentRange.start = Long.parseLong (rangeDefinition.substring(0, dashPos)); if (dashPos < rangeDefinition.length() - 1) currentRange.end = Long.parseLong (rangeDefinition.substring (dashPos + 1, rangeDefinition.length())); else currentRange.end = fileLength - 1; } catch (NumberFormatException e) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse .SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } } if (!currentRange.validate()) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } result.add(currentRange); } return result; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream render(String contextPath, CacheEntry cacheEntry) throws IOException, ServletException { InputStream xsltInputStream = findXsltInputStream(cacheEntry.context); if (xsltInputStream==null) { return renderHtml(contextPath, cacheEntry); } return renderXml(contextPath, cacheEntry, xsltInputStream); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream renderXml(String contextPath, CacheEntry cacheEntry, InputStream xsltInputStream) throws IOException, ServletException { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<listing "); sb.append(" contextPath='"); sb.append(contextPath); sb.append("'"); sb.append(" directory='"); sb.append(cacheEntry.name); sb.append("' "); sb.append(" hasParent='").append(!cacheEntry.name.equals("/")); sb.append("'>"); sb.append("<entries>"); try { // Render the directory entries within this directory NamingEnumeration<NameClassPair> enumeration = resources.list(cacheEntry.name); // rewriteUrl(contextPath) is expensive. cache result for later reuse String rewrittenContextPath = rewriteUrl(contextPath); while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String resourceName = ncPair.getName(); String trimmed = resourceName/*.substring(trim)*/; if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF") || trimmed.equalsIgnoreCase(localXsltFile)) continue; if ((cacheEntry.name + trimmed).equals(contextXsltFile)) continue; CacheEntry childCacheEntry = resources.lookupCache(cacheEntry.name + resourceName); if (!childCacheEntry.exists) { continue; } sb.append("<entry"); sb.append(" type='") .append((childCacheEntry.context != null)?"dir":"file") .append("'"); sb.append(" urlPath='") .append(rewrittenContextPath) .append(rewriteUrl(cacheEntry.name + resourceName)) .append((childCacheEntry.context != null)?"/":"") .append("'"); if (childCacheEntry.resource != null) { sb.append(" size='") .append(renderSize(childCacheEntry.attributes.getContentLength())) .append("'"); } sb.append(" date='") .append(childCacheEntry.attributes.getLastModifiedHttp()) .append("'"); sb.append(">"); sb.append(RequestUtil.filter(trimmed)); if (childCacheEntry.context != null) sb.append("/"); sb.append("</entry>"); } } catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); } sb.append("</entries>"); String readme = getReadme(cacheEntry.context); if (readme!=null) { sb.append("<readme><![CDATA["); sb.append(readme); sb.append("]]></readme>"); } sb.append("</listing>"); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Source xmlSource = new StreamSource(new StringReader(sb.toString())); Source xslSource = new StreamSource(xsltInputStream); Transformer transformer = tFactory.newTransformer(xslSource); ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8"); StreamResult out = new StreamResult(osWriter); transformer.transform(xmlSource, out); osWriter.flush(); return (new ByteArrayInputStream(stream.toByteArray())); } catch (TransformerException e) { throw new ServletException("XSL transformer error", e); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream renderHtml(String contextPath, CacheEntry cacheEntry) throws IOException, ServletException { String name = cacheEntry.name; // Prepare a writer to a buffered area ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8"); PrintWriter writer = new PrintWriter(osWriter); StringBuilder sb = new StringBuilder(); // rewriteUrl(contextPath) is expensive. cache result for later reuse String rewrittenContextPath = rewriteUrl(contextPath); // Render the page header sb.append("<html>\r\n"); sb.append("<head>\r\n"); sb.append("<title>"); sb.append(sm.getString("directory.title", name)); sb.append("</title>\r\n"); sb.append("<STYLE><!--"); sb.append(org.apache.catalina.util.TomcatCSS.TOMCAT_CSS); sb.append("--></STYLE> "); sb.append("</head>\r\n"); sb.append("<body>"); sb.append("<h1>"); sb.append(sm.getString("directory.title", name)); // Render the link to our parent (if required) String parentDirectory = name; if (parentDirectory.endsWith("/")) { parentDirectory = parentDirectory.substring(0, parentDirectory.length() - 1); } int slash = parentDirectory.lastIndexOf('/'); if (slash >= 0) { String parent = name.substring(0, slash); sb.append(" - <a href=\""); sb.append(rewrittenContextPath); if (parent.equals("")) parent = "/"; sb.append(rewriteUrl(parent)); if (!parent.endsWith("/")) sb.append("/"); sb.append("\">"); sb.append("<b>"); sb.append(sm.getString("directory.parent", parent)); sb.append("</b>"); sb.append("</a>"); } sb.append("</h1>"); sb.append("<HR size=\"1\" noshade=\"noshade\">"); sb.append("<table width=\"100%\" cellspacing=\"0\"" + " cellpadding=\"5\" align=\"center\">\r\n"); // Render the column headings sb.append("<tr>\r\n"); sb.append("<td align=\"left\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.filename")); sb.append("</strong></font></td>\r\n"); sb.append("<td align=\"center\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.size")); sb.append("</strong></font></td>\r\n"); sb.append("<td align=\"right\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.lastModified")); sb.append("</strong></font></td>\r\n"); sb.append("</tr>"); try { // Render the directory entries within this directory NamingEnumeration<NameClassPair> enumeration = resources.list(cacheEntry.name); boolean shade = false; while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String resourceName = ncPair.getName(); String trimmed = resourceName/*.substring(trim)*/; if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF")) continue; CacheEntry childCacheEntry = resources.lookupCache(cacheEntry.name + resourceName); if (!childCacheEntry.exists) { continue; } sb.append("<tr"); if (shade) sb.append(" bgcolor=\"#eeeeee\""); sb.append(">\r\n"); shade = !shade; sb.append("<td align=\"left\">&nbsp;&nbsp;\r\n"); sb.append("<a href=\""); sb.append(rewrittenContextPath); resourceName = rewriteUrl(name + resourceName); sb.append(resourceName); if (childCacheEntry.context != null) sb.append("/"); sb.append("\"><tt>"); sb.append(RequestUtil.filter(trimmed)); if (childCacheEntry.context != null) sb.append("/"); sb.append("</tt></a></td>\r\n"); sb.append("<td align=\"right\"><tt>"); if (childCacheEntry.context != null) sb.append("&nbsp;"); else sb.append(renderSize(childCacheEntry.attributes.getContentLength())); sb.append("</tt></td>\r\n"); sb.append("<td align=\"right\"><tt>"); sb.append(childCacheEntry.attributes.getLastModifiedHttp()); sb.append("</tt></td>\r\n"); sb.append("</tr>\r\n"); } } catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); } // Render the page footer sb.append("</table>\r\n"); sb.append("<HR size=\"1\" noshade=\"noshade\">"); String readme = getReadme(cacheEntry.context); if (readme!=null) { sb.append(readme); sb.append("<HR size=\"1\" noshade=\"noshade\">"); } sb.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>"); sb.append("</body>\r\n"); sb.append("</html>\r\n"); // Return an input stream to the underlying bytes writer.write(sb.toString()); writer.flush(); return (new ByteArrayInputStream(stream.toByteArray())); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected String getReadme(DirContext directory) throws IOException { if (readmeFile != null) { try { Object obj = directory.lookup(readmeFile); if ((obj != null) && (obj instanceof Resource)) { StringWriter buffer = new StringWriter(); InputStream is = ((Resource) obj).streamContent(); copyRange(new InputStreamReader(is), new PrintWriter(buffer)); return buffer.toString(); } } catch (NamingException e) { if (debug > 10) log("readme '" + readmeFile + "' not found", e); return null; } } return null; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream findXsltInputStream(DirContext directory) throws IOException { if (localXsltFile != null) { try { Object obj = directory.lookup(localXsltFile); if ((obj != null) && (obj instanceof Resource)) { InputStream is = ((Resource) obj).streamContent(); if (is != null) return is; } } catch (NamingException e) { if (debug > 10) log("localXsltFile '" + localXsltFile + "' not found", e); } } if (contextXsltFile != null) { InputStream is = getServletContext().getResourceAsStream(contextXsltFile); if (is != null) return is; if (debug > 10) log("contextXsltFile '" + contextXsltFile + "' not found"); } /* Open and read in file in one fell swoop to reduce chance * chance of leaving handle open. */ if (globalXsltFile!=null) { FileInputStream fis = null; try { File f = new File(globalXsltFile); if (f.exists()){ fis =new FileInputStream(f); byte b[] = new byte[(int)f.length()]; /* danger! */ fis.read(b); return new ByteArrayInputStream(b); } } finally { if (fis!=null) fis.close(); } } return null; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected boolean checkIfMatch(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) throws IOException { String eTag = resourceAttributes.getETag(); String headerValue = request.getHeader("If-Match"); if (headerValue != null) { if (headerValue.indexOf('*') == -1) { StringTokenizer commaTokenizer = new StringTokenizer (headerValue, ","); boolean conditionSatisfied = false; while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) { String currentToken = commaTokenizer.nextToken(); if (currentToken.trim().equals(eTag)) conditionSatisfied = true; } // If none of the given ETags match, 412 Precodition failed is // sent back if (!conditionSatisfied) { response.sendError (HttpServletResponse.SC_PRECONDITION_FAILED); return false; } } } return true; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected boolean checkIfNoneMatch(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) throws IOException { String eTag = resourceAttributes.getETag(); String headerValue = request.getHeader("If-None-Match"); if (headerValue != null) { boolean conditionSatisfied = false; if (!headerValue.equals("*")) { StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ","); while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) { String currentToken = commaTokenizer.nextToken(); if (currentToken.trim().equals(eTag)) conditionSatisfied = true; } } else { conditionSatisfied = true; } if (conditionSatisfied) { // For GET and HEAD, we should respond with // 304 Not Modified. // For every other method, 412 Precondition Failed is sent // back. if ( ("GET".equals(request.getMethod())) || ("HEAD".equals(request.getMethod())) ) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); return false; } response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } } return true; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected boolean checkIfUnmodifiedSince(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) throws IOException { try { long lastModified = resourceAttributes.getLastModified(); long headerValue = request.getDateHeader("If-Unmodified-Since"); if (headerValue != -1) { if ( lastModified >= (headerValue + 1000)) { // The entity has not been modified since the date // specified by the client. This is not an error case. response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } } } catch(IllegalArgumentException illegalArgument) { return true; } return true; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void copy(CacheEntry cacheEntry, InputStream is, ServletOutputStream ostream) throws IOException { IOException exception = null; InputStream resourceInputStream = null; // Optimization: If the binary content has already been loaded, send // it directly if (cacheEntry.resource != null) { byte buffer[] = cacheEntry.resource.getContent(); if (buffer != null) { ostream.write(buffer, 0, buffer.length); return; } resourceInputStream = cacheEntry.resource.streamContent(); } else { resourceInputStream = is; } InputStream istream = new BufferedInputStream (resourceInputStream, input); // Copy the input stream to the output stream exception = copyRange(istream, ostream); // Clean up the input stream istream.close(); // Rethrow any exception that has occurred if (exception != null) throw exception; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void copy(CacheEntry cacheEntry, InputStream is, PrintWriter writer) throws IOException { IOException exception = null; InputStream resourceInputStream = null; if (cacheEntry.resource != null) { resourceInputStream = cacheEntry.resource.streamContent(); } else { resourceInputStream = is; } Reader reader; if (fileEncoding == null) { reader = new InputStreamReader(resourceInputStream); } else { reader = new InputStreamReader(resourceInputStream, fileEncoding); } // Copy the input stream to the output stream exception = copyRange(reader, writer); // Clean up the reader reader.close(); // Rethrow any exception that has occurred if (exception != null) throw exception; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void copy(CacheEntry cacheEntry, ServletOutputStream ostream, Range range) throws IOException { IOException exception = null; InputStream resourceInputStream = cacheEntry.resource.streamContent(); InputStream istream = new BufferedInputStream(resourceInputStream, input); exception = copyRange(istream, ostream, range.start, range.end); // Clean up the input stream istream.close(); // Rethrow any exception that has occurred if (exception != null) throw exception; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void copy(CacheEntry cacheEntry, ServletOutputStream ostream, Iterator<Range> ranges, String contentType) throws IOException { IOException exception = null; while ( (exception == null) && (ranges.hasNext()) ) { InputStream resourceInputStream = cacheEntry.resource.streamContent(); InputStream istream = new BufferedInputStream(resourceInputStream, input); Range currentRange = ranges.next(); // Writing MIME header. ostream.println(); ostream.println("--" + mimeSeparation); if (contentType != null) ostream.println("Content-Type: " + contentType); ostream.println("Content-Range: bytes " + currentRange.start + "-" + currentRange.end + "/" + currentRange.length); ostream.println(); // Printing content exception = copyRange(istream, ostream, currentRange.start, currentRange.end); istream.close(); } ostream.println(); ostream.print("--" + mimeSeparation + "--"); // Rethrow any exception that has occurred if (exception != null) throw exception; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final String path = getRelativePath(req); // Block access to special subdirectories. // DefaultServlet assumes it services resources from the root of the web app // and doesn't add any special path protection // WebdavServlet remounts the webapp under a new path, so this check is // necessary on all methods (including GET). if (isSpecialPath(path)) { resp.sendError(WebdavStatus.SC_NOT_FOUND); return; } final String method = req.getMethod(); if (debug > 0) { log("[" + method + "] " + path); } if (method.equals(METHOD_PROPFIND)) { doPropfind(req, resp); } else if (method.equals(METHOD_PROPPATCH)) { doProppatch(req, resp); } else if (method.equals(METHOD_MKCOL)) { doMkcol(req, resp); } else if (method.equals(METHOD_COPY)) { doCopy(req, resp); } else if (method.equals(METHOD_MOVE)) { doMove(req, resp); } else if (method.equals(METHOD_LOCK)) { doLock(req, resp); } else if (method.equals(METHOD_UNLOCK)) { doUnlock(req, resp); } else { // DefaultServlet processing super.service(req, resp); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected boolean checkIfHeaders(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) throws IOException { if (!super.checkIfHeaders(request, response, resourceAttributes)) return false; // TODO : Checking the WebDAV If header return true; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("DAV", "1,2"); StringBuilder methodsAllowed = determineMethodsAllowed(resources, req); resp.addHeader("Allow", methodsAllowed.toString()); resp.addHeader("MS-Author-Via", "DAV"); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doPropfind(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (!listings) { // Get allowed methods StringBuilder methodsAllowed = determineMethodsAllowed(resources, req); resp.addHeader("Allow", methodsAllowed.toString()); resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED); return; } String path = getRelativePath(req); if (path.endsWith("/")) path = path.substring(0, path.length() - 1); // Properties which are to be displayed. Vector<String> properties = null; // Propfind depth int depth = maxDepth; // Propfind type int type = FIND_ALL_PROP; String depthStr = req.getHeader("Depth"); if (depthStr == null) { depth = maxDepth; } else { if (depthStr.equals("0")) { depth = 0; } else if (depthStr.equals("1")) { depth = 1; } else if (depthStr.equals("infinity")) { depth = maxDepth; } } Node propNode = null; if (req.getContentLength() > 0) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse (new InputSource(req.getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); NodeList childList = rootElement.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: if (currentNode.getNodeName().endsWith("prop")) { type = FIND_BY_PROPERTY; propNode = currentNode; } if (currentNode.getNodeName().endsWith("propname")) { type = FIND_PROPERTY_NAMES; } if (currentNode.getNodeName().endsWith("allprop")) { type = FIND_ALL_PROP; } break; } } } catch (SAXException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); } catch (IOException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); } } if (type == FIND_BY_PROPERTY) { properties = new Vector<String>(); // propNode must be non-null if type == FIND_BY_PROPERTY @SuppressWarnings("null") NodeList childList = propNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String nodeName = currentNode.getNodeName(); String propertyName = null; if (nodeName.indexOf(':') != -1) { propertyName = nodeName.substring (nodeName.indexOf(':') + 1); } else { propertyName = nodeName; } // href is a live property which is handled differently properties.addElement(propertyName); break; } } } boolean exists = true; Object object = null; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } } if (!exists) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, path); return; } resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); if (depth == 0) { parseProperties(req, generatedXML, path, type, properties); } else { // The stack always contains the object of the current level Stack<String> stack = new Stack<String>(); stack.push(path); // Stack of the objects one level below Stack<String> stackBelow = new Stack<String>(); while ((!stack.isEmpty()) && (depth >= 0)) { String currentPath = stack.pop(); parseProperties(req, generatedXML, currentPath, type, properties); try { object = resources.lookup(currentPath); } catch (NamingException e) { continue; } if ((object instanceof DirContext) && (depth > 0)) { try { NamingEnumeration<NameClassPair> enumeration = resources.list(currentPath); while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String newPath = currentPath; if (!(newPath.endsWith("/"))) newPath += "/"; newPath += ncPair.getName(); stackBelow.push(newPath); } } catch (NamingException e) { resp.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } // Displaying the lock-null resources present in that // collection String lockPath = currentPath; if (lockPath.endsWith("/")) lockPath = lockPath.substring(0, lockPath.length() - 1); Vector<String> currentLockNullResources = lockNullResources.get(lockPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); } } } if (stack.isEmpty()) { depth--; stack = stackBelow; stackBelow = new Stack<String>(); } generatedXML.sendData(); } } generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doProppatch(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doMkcol(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } String path = getRelativePath(req); boolean exists = true; try { resources.lookup(path); } catch (NamingException e) { exists = false; } // Can't create a collection if a resource already exists at the given // path if (exists) { // Get allowed methods StringBuilder methodsAllowed = determineMethodsAllowed(resources, req); resp.addHeader("Allow", methodsAllowed.toString()); resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED); return; } if (req.getContentLength() > 0) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { // Document document = documentBuilder.parse(new InputSource(req.getInputStream())); // TODO : Process this request body resp.sendError(WebdavStatus.SC_NOT_IMPLEMENTED); return; } catch(SAXException saxe) { // Parse error - assume invalid content resp.sendError(WebdavStatus.SC_UNSUPPORTED_MEDIA_TYPE); return; } } boolean result = true; try { resources.createSubcontext(path); } catch (NamingException e) { result = false; } if (!result) { resp.sendError(WebdavStatus.SC_CONFLICT, WebdavStatus.getStatusText (WebdavStatus.SC_CONFLICT)); } else { resp.setStatus(WebdavStatus.SC_CREATED); // Removing any lock-null resource which would be present lockNullResources.remove(path); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } deleteResource(req, resp); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } super.doPut(req, resp); String path = getRelativePath(req); // Removing any lock-null resource which would be present lockNullResources.remove(path); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doCopy(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } copyResource(req, resp); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doMove(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } String path = getRelativePath(req); if (copyResource(req, resp)) { deleteResource(path, req, resp, false); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doLock(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } LockInfo lock = new LockInfo(); // Parsing lock request // Parsing depth header String depthStr = req.getHeader("Depth"); if (depthStr == null) { lock.depth = maxDepth; } else { if (depthStr.equals("0")) { lock.depth = 0; } else { lock.depth = maxDepth; } } // Parsing timeout header int lockDuration = DEFAULT_TIMEOUT; String lockDurationStr = req.getHeader("Timeout"); if (lockDurationStr == null) { lockDuration = DEFAULT_TIMEOUT; } else { int commaPos = lockDurationStr.indexOf(","); // If multiple timeouts, just use the first if (commaPos != -1) { lockDurationStr = lockDurationStr.substring(0,commaPos); } if (lockDurationStr.startsWith("Second-")) { lockDuration = (new Integer(lockDurationStr.substring(7))).intValue(); } else { if (lockDurationStr.equalsIgnoreCase("infinity")) { lockDuration = MAX_TIMEOUT; } else { try { lockDuration = (new Integer(lockDurationStr)).intValue(); } catch (NumberFormatException e) { lockDuration = MAX_TIMEOUT; } } } if (lockDuration == 0) { lockDuration = DEFAULT_TIMEOUT; } if (lockDuration > MAX_TIMEOUT) { lockDuration = MAX_TIMEOUT; } } lock.expiresAt = System.currentTimeMillis() + (lockDuration * 1000); int lockRequestType = LOCK_CREATION; Node lockInfoNode = null; DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse(new InputSource (req.getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); lockInfoNode = rootElement; } catch (IOException e) { lockRequestType = LOCK_REFRESH; } catch (SAXException e) { lockRequestType = LOCK_REFRESH; } if (lockInfoNode != null) { // Reading lock information NodeList childList = lockInfoNode.getChildNodes(); StringWriter strWriter = null; DOMWriter domWriter = null; Node lockScopeNode = null; Node lockTypeNode = null; Node lockOwnerNode = null; for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String nodeName = currentNode.getNodeName(); if (nodeName.endsWith("lockscope")) { lockScopeNode = currentNode; } if (nodeName.endsWith("locktype")) { lockTypeNode = currentNode; } if (nodeName.endsWith("owner")) { lockOwnerNode = currentNode; } break; } } if (lockScopeNode != null) { childList = lockScopeNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String tempScope = currentNode.getNodeName(); if (tempScope.indexOf(':') != -1) { lock.scope = tempScope.substring (tempScope.indexOf(':') + 1); } else { lock.scope = tempScope; } break; } } if (lock.scope == null) { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } } else { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } if (lockTypeNode != null) { childList = lockTypeNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String tempType = currentNode.getNodeName(); if (tempType.indexOf(':') != -1) { lock.type = tempType.substring(tempType.indexOf(':') + 1); } else { lock.type = tempType; } break; } } if (lock.type == null) { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } } else { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } if (lockOwnerNode != null) { childList = lockOwnerNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: lock.owner += currentNode.getNodeValue(); break; case Node.ELEMENT_NODE: strWriter = new StringWriter(); domWriter = new DOMWriter(strWriter, true); domWriter.setQualifiedNames(false); domWriter.print(currentNode); lock.owner += strWriter.toString(); break; } } if (lock.owner == null) { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } } else { lock.owner = ""; } } String path = getRelativePath(req); lock.path = path; boolean exists = true; Object object = null; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; } Enumeration<LockInfo> locksList = null; if (lockRequestType == LOCK_CREATION) { // Generating lock id String lockTokenStr = req.getServletPath() + "-" + lock.type + "-" + lock.scope + "-" + req.getUserPrincipal() + "-" + lock.depth + "-" + lock.owner + "-" + lock.tokens + "-" + lock.expiresAt + "-" + System.currentTimeMillis() + "-" + secret; String lockToken = md5Encoder.encode(md5Helper.digest( lockTokenStr.getBytes(B2CConverter.ISO_8859_1))); if ( (exists) && (object instanceof DirContext) && (lock.depth == maxDepth) ) { // Locking a collection (and all its member resources) // Checking if a child resource of this collection is // already locked Vector<String> lockPaths = new Vector<String>(); locksList = collectionLocks.elements(); while (locksList.hasMoreElements()) { LockInfo currentLock = locksList.nextElement(); if (currentLock.hasExpired()) { resourceLocks.remove(currentLock.path); continue; } if ( (currentLock.path.startsWith(lock.path)) && ((currentLock.isExclusive()) || (lock.isExclusive())) ) { // A child collection of this collection is locked lockPaths.addElement(currentLock.path); } } locksList = resourceLocks.elements(); while (locksList.hasMoreElements()) { LockInfo currentLock = locksList.nextElement(); if (currentLock.hasExpired()) { resourceLocks.remove(currentLock.path); continue; } if ( (currentLock.path.startsWith(lock.path)) && ((currentLock.isExclusive()) || (lock.isExclusive())) ) { // A child resource of this collection is locked lockPaths.addElement(currentLock.path); } } if (!lockPaths.isEmpty()) { // One of the child paths was locked // We generate a multistatus error report Enumeration<String> lockPathsList = lockPaths.elements(); resp.setStatus(WebdavStatus.SC_CONFLICT); XMLWriter generatedXML = new XMLWriter(); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); while (lockPathsList.hasMoreElements()) { generatedXML.writeElement("D", "response", XMLWriter.OPENING); generatedXML.writeElement("D", "href", XMLWriter.OPENING); generatedXML.writeText(lockPathsList.nextElement()); generatedXML.writeElement("D", "href", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML .writeText("HTTP/1.1 " + WebdavStatus.SC_LOCKED + " " + WebdavStatus .getStatusText(WebdavStatus.SC_LOCKED)); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "response", XMLWriter.CLOSING); } generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); Writer writer = resp.getWriter(); writer.write(generatedXML.toString()); writer.close(); return; } boolean addLock = true; // Checking if there is already a shared lock on this path locksList = collectionLocks.elements(); while (locksList.hasMoreElements()) { LockInfo currentLock = locksList.nextElement(); if (currentLock.path.equals(lock.path)) { if (currentLock.isExclusive()) { resp.sendError(WebdavStatus.SC_LOCKED); return; } else { if (lock.isExclusive()) { resp.sendError(WebdavStatus.SC_LOCKED); return; } } currentLock.tokens.addElement(lockToken); lock = currentLock; addLock = false; } } if (addLock) { lock.tokens.addElement(lockToken); collectionLocks.addElement(lock); } } else { // Locking a single resource // Retrieving an already existing lock on that resource LockInfo presentLock = resourceLocks.get(lock.path); if (presentLock != null) { if ((presentLock.isExclusive()) || (lock.isExclusive())) { // If either lock is exclusive, the lock can't be // granted resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED); return; } else { presentLock.tokens.addElement(lockToken); lock = presentLock; } } else { lock.tokens.addElement(lockToken); resourceLocks.put(lock.path, lock); // Checking if a resource exists at this path exists = true; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; } if (!exists) { // "Creating" a lock-null resource int slash = lock.path.lastIndexOf('/'); String parentPath = lock.path.substring(0, slash); Vector<String> lockNulls = lockNullResources.get(parentPath); if (lockNulls == null) { lockNulls = new Vector<String>(); lockNullResources.put(parentPath, lockNulls); } lockNulls.addElement(lock.path); } // Add the Lock-Token header as by RFC 2518 8.10.1 // - only do this for newly created locks resp.addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">"); } } } if (lockRequestType == LOCK_REFRESH) { String ifHeader = req.getHeader("If"); if (ifHeader == null) ifHeader = ""; // Checking resource locks LockInfo toRenew = resourceLocks.get(path); Enumeration<String> tokenList = null; if (toRenew != null) { // At least one of the tokens of the locks must have been given tokenList = toRenew.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (ifHeader.indexOf(token) != -1) { toRenew.expiresAt = lock.expiresAt; lock = toRenew; } } } // Checking inheritable collection locks Enumeration<LockInfo> collectionLocksList = collectionLocks.elements(); while (collectionLocksList.hasMoreElements()) { toRenew = collectionLocksList.nextElement(); if (path.equals(toRenew.path)) { tokenList = toRenew.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (ifHeader.indexOf(token) != -1) { toRenew.expiresAt = lock.expiresAt; lock = toRenew; } } } } } // Set the status, then generate the XML response containing // the lock information XMLWriter generatedXML = new XMLWriter(); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "prop", XMLWriter.OPENING); generatedXML.writeElement("D", "lockdiscovery", XMLWriter.OPENING); lock.toXML(generatedXML); generatedXML.writeElement("D", "lockdiscovery", XMLWriter.CLOSING); generatedXML.writeElement("D", "prop", XMLWriter.CLOSING); resp.setStatus(WebdavStatus.SC_OK); resp.setContentType("text/xml; charset=UTF-8"); Writer writer = resp.getWriter(); writer.write(generatedXML.toString()); writer.close(); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doUnlock(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } String path = getRelativePath(req); String lockTokenHeader = req.getHeader("Lock-Token"); if (lockTokenHeader == null) lockTokenHeader = ""; // Checking resource locks LockInfo lock = resourceLocks.get(path); Enumeration<String> tokenList = null; if (lock != null) { // At least one of the tokens of the locks must have been given tokenList = lock.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (lockTokenHeader.indexOf(token) != -1) { lock.tokens.removeElement(token); } } if (lock.tokens.isEmpty()) { resourceLocks.remove(path); // Removing any lock-null resource which would be present lockNullResources.remove(path); } } // Checking inheritable collection locks Enumeration<LockInfo> collectionLocksList = collectionLocks.elements(); while (collectionLocksList.hasMoreElements()) { lock = collectionLocksList.nextElement(); if (path.equals(lock.path)) { tokenList = lock.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (lockTokenHeader.indexOf(token) != -1) { lock.tokens.removeElement(token); break; } } if (lock.tokens.isEmpty()) { collectionLocks.removeElement(lock); // Removing any lock-null resource which would be present lockNullResources.remove(path); } } } resp.setStatus(WebdavStatus.SC_NO_CONTENT); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
private boolean copyResource(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Parsing destination header String destinationPath = req.getHeader("Destination"); if (destinationPath == null) { resp.sendError(WebdavStatus.SC_BAD_REQUEST); return false; } // Remove url encoding from destination destinationPath = org.apache.catalina.util.RequestUtil.URLDecode( destinationPath, "UTF8"); int protocolIndex = destinationPath.indexOf("://"); if (protocolIndex >= 0) { // if the Destination URL contains the protocol, we can safely // trim everything upto the first "/" character after "://" int firstSeparator = destinationPath.indexOf("/", protocolIndex + 4); if (firstSeparator < 0) { destinationPath = "/"; } else { destinationPath = destinationPath.substring(firstSeparator); } } else { String hostName = req.getServerName(); if ((hostName != null) && (destinationPath.startsWith(hostName))) { destinationPath = destinationPath.substring(hostName.length()); } int portIndex = destinationPath.indexOf(":"); if (portIndex >= 0) { destinationPath = destinationPath.substring(portIndex); } if (destinationPath.startsWith(":")) { int firstSeparator = destinationPath.indexOf("/"); if (firstSeparator < 0) { destinationPath = "/"; } else { destinationPath = destinationPath.substring(firstSeparator); } } } // Normalise destination path (remove '.' and '..') destinationPath = RequestUtil.normalize(destinationPath); String contextPath = req.getContextPath(); if ((contextPath != null) && (destinationPath.startsWith(contextPath))) { destinationPath = destinationPath.substring(contextPath.length()); } String pathInfo = req.getPathInfo(); if (pathInfo != null) { String servletPath = req.getServletPath(); if ((servletPath != null) && (destinationPath.startsWith(servletPath))) { destinationPath = destinationPath .substring(servletPath.length()); } } if (debug > 0) log("Dest path :" + destinationPath); // Check destination path to protect special subdirectories if (isSpecialPath(destinationPath)) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return false; } String path = getRelativePath(req); if (destinationPath.equals(path)) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return false; } // Parsing overwrite header boolean overwrite = true; String overwriteHeader = req.getHeader("Overwrite"); if (overwriteHeader != null) { if (overwriteHeader.equalsIgnoreCase("T")) { overwrite = true; } else { overwrite = false; } } // Overwriting the destination boolean exists = true; try { resources.lookup(destinationPath); } catch (NamingException e) { exists = false; } if (overwrite) { // Delete destination resource, if it exists if (exists) { if (!deleteResource(destinationPath, req, resp, true)) { return false; } } else { resp.setStatus(WebdavStatus.SC_CREATED); } } else { // If the destination exists, then it's a conflict if (exists) { resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED); return false; } } // Copying source to destination Hashtable<String,Integer> errorList = new Hashtable<String,Integer>(); boolean result = copyResource(resources, errorList, path, destinationPath); if ((!result) || (!errorList.isEmpty())) { if (errorList.size() == 1) { resp.sendError(errorList.elements().nextElement().intValue()); } else { sendReport(req, resp, errorList); } return false; } // Copy was successful if (exists) { resp.setStatus(WebdavStatus.SC_NO_CONTENT); } else { resp.setStatus(WebdavStatus.SC_CREATED); } // Removing any lock-null resource which would be present at // the destination path lockNullResources.remove(destinationPath); return true; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
private boolean deleteResource(HttpServletRequest req, HttpServletResponse resp) throws IOException { String path = getRelativePath(req); return deleteResource(path, req, resp, true); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
private boolean deleteResource(String path, HttpServletRequest req, HttpServletResponse resp, boolean setStatus) throws IOException { String ifHeader = req.getHeader("If"); if (ifHeader == null) ifHeader = ""; String lockTokenHeader = req.getHeader("Lock-Token"); if (lockTokenHeader == null) lockTokenHeader = ""; if (isLocked(path, ifHeader + lockTokenHeader)) { resp.sendError(WebdavStatus.SC_LOCKED); return false; } boolean exists = true; Object object = null; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; } if (!exists) { resp.sendError(WebdavStatus.SC_NOT_FOUND); return false; } boolean collection = (object instanceof DirContext); if (!collection) { try { resources.unbind(path); } catch (NamingException e) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); return false; } } else { Hashtable<String,Integer> errorList = new Hashtable<String,Integer>(); deleteCollection(req, resources, path, errorList); try { resources.unbind(path); } catch (NamingException e) { errorList.put(path, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); } if (!errorList.isEmpty()) { sendReport(req, resp, errorList); return false; } } if (setStatus) { resp.setStatus(WebdavStatus.SC_NO_CONTENT); } return true; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
private void sendReport(HttpServletRequest req, HttpServletResponse resp, Hashtable<String,Integer> errorList) throws IOException { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); String absoluteUri = req.getRequestURI(); String relativePath = getRelativePath(req); XMLWriter generatedXML = new XMLWriter(); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); Enumeration<String> pathList = errorList.keys(); while (pathList.hasMoreElements()) { String errorPath = pathList.nextElement(); int errorCode = errorList.get(errorPath).intValue(); generatedXML.writeElement("D", "response", XMLWriter.OPENING); generatedXML.writeElement("D", "href", XMLWriter.OPENING); String toAppend = errorPath.substring(relativePath.length()); if (!toAppend.startsWith("/")) toAppend = "/" + toAppend; generatedXML.writeText(absoluteUri + toAppend); generatedXML.writeElement("D", "href", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML.writeText("HTTP/1.1 " + errorCode + " " + WebdavStatus.getStatusText(errorCode)); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "response", XMLWriter.CLOSING); } generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); Writer writer = resp.getWriter(); writer.write(generatedXML.toString()); writer.close(); }
// in java/org/apache/catalina/servlets/CGIServlet.java
protected void printServletEnvironment(ServletOutputStream out, HttpServletRequest req, HttpServletResponse res) throws IOException { // Document the properties from ServletRequest out.println("<h1>ServletRequest Properties</h1>"); out.println("<ul>"); Enumeration<String> attrs = req.getAttributeNames(); while (attrs.hasMoreElements()) { String attr = attrs.nextElement(); out.println("<li><b>attribute</b> " + attr + " = " + req.getAttribute(attr)); } out.println("<li><b>characterEncoding</b> = " + req.getCharacterEncoding()); out.println("<li><b>contentLength</b> = " + req.getContentLength()); out.println("<li><b>contentType</b> = " + req.getContentType()); Enumeration<Locale> locales = req.getLocales(); while (locales.hasMoreElements()) { Locale locale = locales.nextElement(); out.println("<li><b>locale</b> = " + locale); } Enumeration<String> params = req.getParameterNames(); while (params.hasMoreElements()) { String param = params.nextElement(); String values[] = req.getParameterValues(param); for (int i = 0; i < values.length; i++) out.println("<li><b>parameter</b> " + param + " = " + values[i]); } out.println("<li><b>protocol</b> = " + req.getProtocol()); out.println("<li><b>remoteAddr</b> = " + req.getRemoteAddr()); out.println("<li><b>remoteHost</b> = " + req.getRemoteHost()); out.println("<li><b>scheme</b> = " + req.getScheme()); out.println("<li><b>secure</b> = " + req.isSecure()); out.println("<li><b>serverName</b> = " + req.getServerName()); out.println("<li><b>serverPort</b> = " + req.getServerPort()); out.println("</ul>"); out.println("<hr>"); // Document the properties from HttpServletRequest out.println("<h1>HttpServletRequest Properties</h1>"); out.println("<ul>"); out.println("<li><b>authType</b> = " + req.getAuthType()); out.println("<li><b>contextPath</b> = " + req.getContextPath()); Cookie cookies[] = req.getCookies(); if (cookies!=null) { for (int i = 0; i < cookies.length; i++) out.println("<li><b>cookie</b> " + cookies[i].getName() +" = " +cookies[i].getValue()); } Enumeration<String> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String header = headers.nextElement(); out.println("<li><b>header</b> " + header + " = " + req.getHeader(header)); } out.println("<li><b>method</b> = " + req.getMethod()); out.println("<li><a name=\"pathInfo\"><b>pathInfo</b></a> = " + req.getPathInfo()); out.println("<li><b>pathTranslated</b> = " + req.getPathTranslated()); out.println("<li><b>queryString</b> = " + req.getQueryString()); out.println("<li><b>remoteUser</b> = " + req.getRemoteUser()); out.println("<li><b>requestedSessionId</b> = " + req.getRequestedSessionId()); out.println("<li><b>requestedSessionIdFromCookie</b> = " + req.isRequestedSessionIdFromCookie()); out.println("<li><b>requestedSessionIdFromURL</b> = " + req.isRequestedSessionIdFromURL()); out.println("<li><b>requestedSessionIdValid</b> = " + req.isRequestedSessionIdValid()); out.println("<li><b>requestURI</b> = " + req.getRequestURI()); out.println("<li><b>servletPath</b> = " + req.getServletPath()); out.println("<li><b>userPrincipal</b> = " + req.getUserPrincipal()); out.println("</ul>"); out.println("<hr>"); // Document the servlet request attributes out.println("<h1>ServletRequest Attributes</h1>"); out.println("<ul>"); attrs = req.getAttributeNames(); while (attrs.hasMoreElements()) { String attr = attrs.nextElement(); out.println("<li><b>" + attr + "</b> = " + req.getAttribute(attr)); } out.println("</ul>"); out.println("<hr>"); // Process the current session (if there is one) HttpSession session = req.getSession(false); if (session != null) { // Document the session properties out.println("<h1>HttpSession Properties</h1>"); out.println("<ul>"); out.println("<li><b>id</b> = " + session.getId()); out.println("<li><b>creationTime</b> = " + new Date(session.getCreationTime())); out.println("<li><b>lastAccessedTime</b> = " + new Date(session.getLastAccessedTime())); out.println("<li><b>maxInactiveInterval</b> = " + session.getMaxInactiveInterval()); out.println("</ul>"); out.println("<hr>"); // Document the session attributes out.println("<h1>HttpSession Attributes</h1>"); out.println("<ul>"); attrs = session.getAttributeNames(); while (attrs.hasMoreElements()) { String attr = attrs.nextElement(); out.println("<li><b>" + attr + "</b> = " + session.getAttribute(attr)); } out.println("</ul>"); out.println("<hr>"); } // Document the servlet configuration properties out.println("<h1>ServletConfig Properties</h1>"); out.println("<ul>"); out.println("<li><b>servletName</b> = " + getServletConfig().getServletName()); out.println("</ul>"); out.println("<hr>"); // Document the servlet configuration initialization parameters out.println("<h1>ServletConfig Initialization Parameters</h1>"); out.println("<ul>"); params = getServletConfig().getInitParameterNames(); while (params.hasMoreElements()) { String param = params.nextElement(); String value = getServletConfig().getInitParameter(param); out.println("<li><b>" + param + "</b> = " + value); } out.println("</ul>"); out.println("<hr>"); // Document the servlet context properties out.println("<h1>ServletContext Properties</h1>"); out.println("<ul>"); out.println("<li><b>majorVersion</b> = " + getServletContext().getMajorVersion()); out.println("<li><b>minorVersion</b> = " + getServletContext().getMinorVersion()); out.println("<li><b>realPath('/')</b> = " + getServletContext().getRealPath("/")); out.println("<li><b>serverInfo</b> = " + getServletContext().getServerInfo()); out.println("</ul>"); out.println("<hr>"); // Document the servlet context initialization parameters out.println("<h1>ServletContext Initialization Parameters</h1>"); out.println("<ul>"); params = getServletContext().getInitParameterNames(); while (params.hasMoreElements()) { String param = params.nextElement(); String value = getServletContext().getInitParameter(param); out.println("<li><b>" + param + "</b> = " + value); } out.println("</ul>"); out.println("<hr>"); // Document the servlet context attributes out.println("<h1>ServletContext Attributes</h1>"); out.println("<ul>"); attrs = getServletContext().getAttributeNames(); while (attrs.hasMoreElements()) { String attr = attrs.nextElement(); out.println("<li><b>" + attr + "</b> = " + getServletContext().getAttribute(attr)); } out.println("</ul>"); out.println("<hr>"); }
// in java/org/apache/catalina/servlets/CGIServlet.java
Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doGet(req, res); }
// in java/org/apache/catalina/servlets/CGIServlet.java
Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { CGIEnvironment cgiEnv = new CGIEnvironment(req, getServletContext()); if (cgiEnv.isValid()) { CGIRunner cgi = new CGIRunner(cgiEnv.getCommand(), cgiEnv.getEnvironment(), cgiEnv.getWorkingDirectory(), cgiEnv.getParameters()); //if POST, we need to cgi.setInput //REMIND: how does this interact with Servlet API 2.3's Filters?! if ("POST".equals(req.getMethod())) { cgi.setInput(req.getInputStream()); } cgi.setResponse(res); cgi.run(); } if (!cgiEnv.isValid()) { res.setStatus(404); } if (debug >= 10) { ServletOutputStream out = res.getOutputStream(); out.println("<HTML><HEAD><TITLE>$Name$</TITLE></HEAD>"); out.println("<BODY>$Header$<p>"); if (cgiEnv.isValid()) { out.println(cgiEnv.toString()); } else { out.println("<H3>"); out.println("CGI script not found or not specified."); out.println("</H3>"); out.println("<H4>"); out.println("Check the <b>HttpServletRequest "); out.println("<a href=\"#pathInfo\">pathInfo</a></b> "); out.println("property to see if it is what you meant "); out.println("it to be. You must specify an existant "); out.println("and executable file as part of the "); out.println("path-info."); out.println("</H4>"); out.println("<H4>"); out.println("For a good discussion of how CGI scripts "); out.println("work and what their environment variables "); out.println("mean, please visit the <a "); out.println("href=\"http://cgi-spec.golux.com\">CGI "); out.println("Specification page</a>."); out.println("</H4>"); } printServletEnvironment(out, req, res); out.println("</BODY></HTML>"); } }
// in java/org/apache/catalina/servlets/CGIServlet.java
protected boolean setCGIEnvironment(HttpServletRequest req) throws IOException { /* * This method is slightly ugly; c'est la vie. * "You cannot stop [ugliness], you can only hope to contain [it]" * (apologies to Marv Albert regarding MJ) */ Hashtable<String,String> envp = new Hashtable<String,String>(); // Add the shell environment variables (if any) envp.putAll(shellEnv); // Add the CGI environment variables String sPathInfoOrig = null; String sPathInfoCGI = null; String sPathTranslatedCGI = null; String sCGIFullPath = null; String sCGIScriptName = null; String sCGIFullName = null; String sCGIName = null; String[] sCGINames; sPathInfoOrig = this.pathInfo; sPathInfoOrig = sPathInfoOrig == null ? "" : sPathInfoOrig; if (webAppRootDir == null ) { // The app has not been deployed in exploded form webAppRootDir = tmpDir.toString(); expandCGIScript(); } sCGINames = findCGI(sPathInfoOrig, webAppRootDir, contextPath, servletPath, cgiPathPrefix); sCGIFullPath = sCGINames[0]; sCGIScriptName = sCGINames[1]; sCGIFullName = sCGINames[2]; sCGIName = sCGINames[3]; if (sCGIFullPath == null || sCGIScriptName == null || sCGIFullName == null || sCGIName == null) { return false; } envp.put("SERVER_SOFTWARE", "TOMCAT"); envp.put("SERVER_NAME", nullsToBlanks(req.getServerName())); envp.put("GATEWAY_INTERFACE", "CGI/1.1"); envp.put("SERVER_PROTOCOL", nullsToBlanks(req.getProtocol())); int port = req.getServerPort(); Integer iPort = (port == 0 ? Integer.valueOf(-1) : Integer.valueOf(port)); envp.put("SERVER_PORT", iPort.toString()); envp.put("REQUEST_METHOD", nullsToBlanks(req.getMethod())); envp.put("REQUEST_URI", nullsToBlanks(req.getRequestURI())); /*- * PATH_INFO should be determined by using sCGIFullName: * 1) Let sCGIFullName not end in a "/" (see method findCGI) * 2) Let sCGIFullName equal the pathInfo fragment which * corresponds to the actual cgi script. * 3) Thus, PATH_INFO = request.getPathInfo().substring( * sCGIFullName.length()) * * (see method findCGI, where the real work is done) * */ if (pathInfo == null || (pathInfo.substring(sCGIFullName.length()).length() <= 0)) { sPathInfoCGI = ""; } else { sPathInfoCGI = pathInfo.substring(sCGIFullName.length()); } envp.put("PATH_INFO", sPathInfoCGI); /*- * PATH_TRANSLATED must be determined after PATH_INFO (and the * implied real cgi-script) has been taken into account. * * The following example demonstrates: * * servlet info = /servlet/cgigw/dir1/dir2/cgi1/trans1/trans2 * cgifullpath = /servlet/cgigw/dir1/dir2/cgi1 * path_info = /trans1/trans2 * webAppRootDir = servletContext.getRealPath("/") * * path_translated = servletContext.getRealPath("/trans1/trans2") * * That is, PATH_TRANSLATED = webAppRootDir + sPathInfoCGI * (unless sPathInfoCGI is null or blank, then the CGI * specification dictates that the PATH_TRANSLATED metavariable * SHOULD NOT be defined. * */ if (sPathInfoCGI != null && !("".equals(sPathInfoCGI))) { sPathTranslatedCGI = context.getRealPath(sPathInfoCGI); } if (sPathTranslatedCGI == null || "".equals(sPathTranslatedCGI)) { //NOOP } else { envp.put("PATH_TRANSLATED", nullsToBlanks(sPathTranslatedCGI)); } envp.put("SCRIPT_NAME", nullsToBlanks(sCGIScriptName)); envp.put("QUERY_STRING", nullsToBlanks(req.getQueryString())); envp.put("REMOTE_HOST", nullsToBlanks(req.getRemoteHost())); envp.put("REMOTE_ADDR", nullsToBlanks(req.getRemoteAddr())); envp.put("AUTH_TYPE", nullsToBlanks(req.getAuthType())); envp.put("REMOTE_USER", nullsToBlanks(req.getRemoteUser())); envp.put("REMOTE_IDENT", ""); //not necessary for full compliance envp.put("CONTENT_TYPE", nullsToBlanks(req.getContentType())); /* Note CGI spec says CONTENT_LENGTH must be NULL ("") or undefined * if there is no content, so we cannot put 0 or -1 in as per the * Servlet API spec. */ int contentLength = req.getContentLength(); String sContentLength = (contentLength <= 0 ? "" : (Integer.valueOf(contentLength)).toString()); envp.put("CONTENT_LENGTH", sContentLength); Enumeration<String> headers = req.getHeaderNames(); String header = null; while (headers.hasMoreElements()) { header = null; header = headers.nextElement().toUpperCase(Locale.ENGLISH); //REMIND: rewrite multiple headers as if received as single //REMIND: change character set //REMIND: I forgot what the previous REMIND means if ("AUTHORIZATION".equalsIgnoreCase(header) || "PROXY_AUTHORIZATION".equalsIgnoreCase(header)) { //NOOP per CGI specification section 11.2 } else { envp.put("HTTP_" + header.replace('-', '_'), req.getHeader(header)); } } File fCGIFullPath = new File(sCGIFullPath); command = fCGIFullPath.getCanonicalPath(); envp.put("X_TOMCAT_SCRIPT_PATH", command); //for kicks envp.put("SCRIPT_FILENAME", command); //for PHP this.env = envp; return true; }
// in java/org/apache/catalina/servlets/CGIServlet.java
protected void run() throws IOException { /* * REMIND: this method feels too big; should it be re-written? */ if (!isReady()) { throw new IOException(this.getClass().getName() + ": not ready to run."); } if (debug >= 1 ) { log("runCGI(envp=[" + env + "], command=" + command + ")"); } if ((command.indexOf(File.separator + "." + File.separator) >= 0) || (command.indexOf(File.separator + "..") >= 0) || (command.indexOf(".." + File.separator) >= 0)) { throw new IOException(this.getClass().getName() + "Illegal Character in CGI command " + "path ('.' or '..') detected. Not " + "running CGI [" + command + "]."); } /* original content/structure of this section taken from * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4216884 * with major modifications by Martin Dengler */ Runtime rt = null; BufferedReader cgiHeaderReader = null; InputStream cgiOutput = null; BufferedReader commandsStdErr = null; Thread errReaderThread = null; BufferedOutputStream commandsStdIn = null; Process proc = null; int bufRead = -1; List<String> cmdAndArgs = new ArrayList<String>(); if (cgiExecutable.length() != 0) { cmdAndArgs.add(cgiExecutable); } if (cgiExecutableArgs != null) { cmdAndArgs.addAll(cgiExecutableArgs); } cmdAndArgs.add(command); cmdAndArgs.addAll(params); try { rt = Runtime.getRuntime(); proc = rt.exec( cmdAndArgs.toArray(new String[cmdAndArgs.size()]), hashToStringArray(env), wd); String sContentLength = env.get("CONTENT_LENGTH"); if(!"".equals(sContentLength)) { commandsStdIn = new BufferedOutputStream(proc.getOutputStream()); IOTools.flow(stdin, commandsStdIn); commandsStdIn.flush(); commandsStdIn.close(); } /* we want to wait for the process to exit, Process.waitFor() * is useless in our situation; see * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4223650 */ boolean isRunning = true; commandsStdErr = new BufferedReader (new InputStreamReader(proc.getErrorStream())); final BufferedReader stdErrRdr = commandsStdErr ; errReaderThread = new Thread() { @Override public void run () { sendToLog(stdErrRdr) ; } }; errReaderThread.start(); InputStream cgiHeaderStream = new HTTPHeaderInputStream(proc.getInputStream()); cgiHeaderReader = new BufferedReader(new InputStreamReader(cgiHeaderStream)); while (isRunning) { try { //set headers String line = null; while (((line = cgiHeaderReader.readLine()) != null) && !("".equals(line))) { if (debug >= 2) { log("runCGI: addHeader(\"" + line + "\")"); } if (line.startsWith("HTTP")) { response.setStatus(getSCFromHttpStatusLine(line)); } else if (line.indexOf(":") >= 0) { String header = line.substring(0, line.indexOf(":")).trim(); String value = line.substring(line.indexOf(":") + 1).trim(); if (header.equalsIgnoreCase("status")) { response.setStatus(getSCFromCGIStatusHeader(value)); } else { response.addHeader(header , value); } } else { log("runCGI: bad header line \"" + line + "\""); } } //write output byte[] bBuf = new byte[2048]; OutputStream out = response.getOutputStream(); cgiOutput = proc.getInputStream(); try { while ((bufRead = cgiOutput.read(bBuf)) != -1) { if (debug >= 4) { log("runCGI: output " + bufRead + " bytes of data"); } out.write(bBuf, 0, bufRead); } } finally { // Attempt to consume any leftover byte if something bad happens, // such as a socket disconnect on the servlet side; otherwise, the // external process could hang if (bufRead != -1) { while ((bufRead = cgiOutput.read(bBuf)) != -1) { // NOOP - just read the data } } } proc.exitValue(); // Throws exception if alive isRunning = false; } catch (IllegalThreadStateException e) { try { Thread.sleep(500); } catch (InterruptedException ignored) { // Ignore } } } //replacement for Process.waitFor() } catch (IOException e){ log ("Caught exception " + e); throw e; } finally{ // Close the header reader if (cgiHeaderReader != null) { try { cgiHeaderReader.close(); } catch (IOException ioe) { log ("Exception closing header reader " + ioe); } } // Close the output stream if used if (cgiOutput != null) { try { cgiOutput.close(); } catch (IOException ioe) { log ("Exception closing output stream " + ioe); } } // Make sure the error stream reader has finished if (errReaderThread != null) { try { errReaderThread.join(stderrTimeout); } catch (InterruptedException e) { log ("Interupted waiting for stderr reader thread"); } } if (debug > 4) { log ("Running finally block"); } if (proc != null){ proc.destroy(); proc = null; } } }
// in java/org/apache/catalina/servlets/CGIServlet.java
Override public int read() throws IOException { if (state == STATE_HEADER_END) { return -1; } int i = input.read(); // Update the state // State machine looks like this // // -------->-------- // | (CR) | // | | // CR1--->--- | // | | | // ^(CR) |(LF) | // | | | // CHAR--->--LF1--->--EOH // (LF) | (LF) | // |(CR) ^(LF) // | | // (CR2)-->--- if (i == 10) { // LF switch(state) { case STATE_CHARACTER: state = STATE_FIRST_LF; break; case STATE_FIRST_CR: state = STATE_FIRST_LF; break; case STATE_FIRST_LF: case STATE_SECOND_CR: state = STATE_HEADER_END; break; } } else if (i == 13) { // CR switch(state) { case STATE_CHARACTER: state = STATE_FIRST_CR; break; case STATE_FIRST_CR: state = STATE_HEADER_END; break; case STATE_FIRST_LF: state = STATE_SECOND_CR; break; } } else { state = STATE_CHARACTER; } return i; }
// in java/org/apache/catalina/ha/session/SerializablePrincipal.java
public static GenericPrincipal readPrincipal(ObjectInput in) throws IOException, ClassNotFoundException { String name = in.readUTF(); boolean hasPwd = in.readBoolean(); String pwd = null; if ( hasPwd ) pwd = in.readUTF(); int size = in.readInt(); String[] roles = new String[size]; for ( int i=0; i<size; i++ ) roles[i] = in.readUTF(); Principal userPrincipal = null; boolean hasUserPrincipal = in.readBoolean(); if (hasUserPrincipal) { try { userPrincipal = (Principal) in.readObject(); } catch (ClassNotFoundException e) { log.error(sm.getString( "serializablePrincipal.readPrincipal.cnfe"), e); throw e; } } return new GenericPrincipal(name,pwd,Arrays.asList(roles), userPrincipal); }
// in java/org/apache/catalina/ha/session/SerializablePrincipal.java
public static void writePrincipal(GenericPrincipal p, ObjectOutput out) throws IOException { out.writeUTF(p.getName()); out.writeBoolean(p.getPassword()!=null); if ( p.getPassword()!= null ) out.writeUTF(p.getPassword()); String[] roles = p.getRoles(); if ( roles == null ) roles = new String[0]; out.writeInt(roles.length); for ( int i=0; i<roles.length; i++ ) out.writeUTF(roles[i]); boolean hasUserPrincipal = (p != p.getUserPrincipal() && p.getUserPrincipal() instanceof Serializable); out.writeBoolean(hasUserPrincipal); if (hasUserPrincipal) out.writeObject(p.getUserPrincipal()); }
// in java/org/apache/catalina/ha/session/JvmRouteBinderValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (getEnabled() && request.getContext() != null && request.getContext().getDistributable() && !request.isAsyncDispatching()) { // valve cluster can access manager - other cluster handle turnover // at host level - hopefully! Manager manager = request.getContext().getManager(); if (manager != null && ( (manager instanceof ClusterManager && getCluster() != null && getCluster().getManager(((ClusterManager)manager).getName()) != null) || (manager instanceof PersistentManager))) { handlePossibleTurnover(request); } } // Pass this request on to the next valve in our pipeline getNext().invoke(request, response); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public byte[] getDiff() throws IOException { try{ lock(); return getDeltaRequest().serialize(); }finally{ unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void applyDiff(byte[] diff, int offset, int length) throws IOException, ClassNotFoundException { try { lock(); ReplicationStream stream = ( (ClusterManager) getManager()).getReplicationStream(diff, offset, length); ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); try { ClassLoader[] loaders = getClassLoaders(); if (loaders != null && loaders.length > 0) Thread.currentThread().setContextClassLoader(loaders[0]); getDeltaRequest().readExternal(stream); getDeltaRequest().execute(this, ((ClusterManager)getManager()).isNotifyListenersOnReplication()); } finally { Thread.currentThread().setContextClassLoader(contextLoader); } }finally { unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException { try { lock(); readObjectData(in); }finally{ unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void readObjectData(ObjectInputStream stream) throws ClassNotFoundException, IOException { readObject((ObjectInput)stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
public void readObjectData(ObjectInput stream) throws ClassNotFoundException, IOException { readObject(stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void writeObjectData(ObjectOutputStream stream) throws IOException { writeObjectData((ObjectOutput)stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
public void writeObjectData(ObjectOutput stream) throws IOException { writeObject(stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override protected void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException { readObject((ObjectInput)stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
private void readObject(ObjectInput stream) throws ClassNotFoundException, IOException { // Deserialize the scalar instance variables (except Manager) authType = null; // Transient only creationTime = ( (Long) stream.readObject()).longValue(); lastAccessedTime = ( (Long) stream.readObject()).longValue(); maxInactiveInterval = ( (Integer) stream.readObject()).intValue(); isNew = ( (Boolean) stream.readObject()).booleanValue(); isValid = ( (Boolean) stream.readObject()).booleanValue(); thisAccessedTime = ( (Long) stream.readObject()).longValue(); version = ( (Long) stream.readObject()).longValue(); boolean hasPrincipal = stream.readBoolean(); principal = null; if (hasPrincipal) { principal = SerializablePrincipal.readPrincipal(stream); } // setId((String) stream.readObject()); id = (String) stream.readObject(); if (log.isDebugEnabled()) log.debug(sm.getString("deltaSession.readSession", id)); // Deserialize the attribute count and attribute values if (attributes == null) attributes = new ConcurrentHashMap<String, Object>(); int n = ( (Integer) stream.readObject()).intValue(); boolean isValidSave = isValid; isValid = true; for (int i = 0; i < n; i++) { String name = (String) stream.readObject(); Object value = stream.readObject(); if ( (value instanceof String) && (value.equals(NOT_SERIALIZED))) continue; attributes.put(name, value); } isValid = isValidSave; if (listeners == null) { ArrayList<SessionListener> arrayList = new ArrayList<SessionListener>(); listeners = arrayList; } if (notes == null) { notes = new Hashtable<String,Object>(); } activate(); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override public void writeExternal(ObjectOutput out ) throws java.io.IOException { try { lock(); writeObject(out); }finally { unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
Override protected void writeObject(ObjectOutputStream stream) throws IOException { writeObject((ObjectOutput)stream); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
private void writeObject(ObjectOutput stream) throws IOException { // Write the scalar instance variables (except Manager) stream.writeObject(Long.valueOf(creationTime)); stream.writeObject(Long.valueOf(lastAccessedTime)); stream.writeObject(Integer.valueOf(maxInactiveInterval)); stream.writeObject(Boolean.valueOf(isNew)); stream.writeObject(Boolean.valueOf(isValid)); stream.writeObject(Long.valueOf(thisAccessedTime)); stream.writeObject(Long.valueOf(version)); stream.writeBoolean(getPrincipal() != null); if (getPrincipal() != null) { SerializablePrincipal.writePrincipal((GenericPrincipal) principal,stream); } stream.writeObject(id); if (log.isDebugEnabled()) log.debug(sm.getString("deltaSession.writeSession", id)); // Accumulate the names of serializable and non-serializable attributes String keys[] = keys(); ArrayList<String> saveNames = new ArrayList<String>(); ArrayList<Object> saveValues = new ArrayList<Object>(); for (int i = 0; i < keys.length; i++) { Object value = null; value = attributes.get(keys[i]); if (value == null || exclude(keys[i])) continue; else if (value instanceof Serializable) { saveNames.add(keys[i]); saveValues.add(value); } } // Serialize the attribute count and the Serializable attributes int n = saveNames.size(); stream.writeObject(Integer.valueOf(n)); for (int i = 0; i < n; i++) { stream.writeObject( saveNames.get(i)); try { stream.writeObject(saveValues.get(i)); } catch (NotSerializableException e) { log.error(sm.getString("standardSession.notSerializable",saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); log.error(" storing attribute '" + saveNames.get(i)+ "' with value NOT_SERIALIZED"); } } }
// in java/org/apache/catalina/ha/session/ClusterManagerBase.java
Override public ReplicationStream getReplicationStream(byte[] data) throws IOException { return getReplicationStream(data,0,data.length); }
// in java/org/apache/catalina/ha/session/ClusterManagerBase.java
Override public ReplicationStream getReplicationStream(byte[] data, int offset, int length) throws IOException { ByteArrayInputStream fis = new ByteArrayInputStream(data, offset, length); return new ReplicationStream(fis, getClassLoaders()); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
Override public void readExternal(java.io.ObjectInput in) throws IOException,ClassNotFoundException { //sessionId - String //recordAll - boolean //size - int //AttributeInfo - in an array reset(); sessionId = in.readUTF(); recordAllActions = in.readBoolean(); int cnt = in.readInt(); if (actions == null) actions = new LinkedList<AttributeInfo>(); else actions.clear(); for (int i = 0; i < cnt; i++) { AttributeInfo info = null; if (this.actionPool.size() > 0) { try { info = actionPool.removeFirst(); } catch ( Exception x ) { log.error("Unable to remove element",x); info = new AttributeInfo(); } } else { info = new AttributeInfo(); } info.readExternal(in); actions.addLast(info); }//for }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
Override public void writeExternal(java.io.ObjectOutput out ) throws java.io.IOException { //sessionId - String //recordAll - boolean //size - int //AttributeInfo - in an array out.writeUTF(getSessionId()); out.writeBoolean(recordAllActions); out.writeInt(getSize()); for ( int i=0; i<getSize(); i++ ) { AttributeInfo info = actions.get(i); info.writeExternal(out); } }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
protected byte[] serialize() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); writeExternal(oos); oos.flush(); oos.close(); return bos.toByteArray(); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
Override public void readExternal(java.io.ObjectInput in ) throws IOException,ClassNotFoundException { //type - int //action - int //name - String //hasvalue - boolean //value - object type = in.readInt(); action = in.readInt(); name = in.readUTF(); boolean hasValue = in.readBoolean(); if ( hasValue ) value = in.readObject(); }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
Override public void writeExternal(java.io.ObjectOutput out) throws IOException { //type - int //action - int //name - String //hasvalue - boolean //value - object out.writeInt(getType()); out.writeInt(getAction()); out.writeUTF(getName()); out.writeBoolean(getValue()!=null); if (getValue()!=null) out.writeObject(getValue()); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected byte[] serializeSessionId(String sessionId) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeUTF(sessionId); oos.flush(); oos.close(); return bos.toByteArray(); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected String deserializeSessionId(byte[] data) throws IOException { ReplicationStream ois = getReplicationStream(data); String sessionId = ois.readUTF(); ois.close(); return sessionId; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected DeltaRequest deserializeDeltaRequest(DeltaSession session, byte[] data) throws ClassNotFoundException, IOException { try { session.lock(); ReplicationStream ois = getReplicationStream(data); session.getDeltaRequest().readExternal(ois); ois.close(); return session.getDeltaRequest(); }finally { session.unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected byte[] serializeDeltaRequest(DeltaSession session, DeltaRequest deltaRequest) throws IOException { try { session.lock(); return deltaRequest.serialize(); }finally { session.unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void deserializeSessions(byte[] data) throws ClassNotFoundException,IOException { // Initialize our internal data structures //sessions.clear(); //should not do this // Open an input stream to the specified pathname, if any ClassLoader originalLoader = Thread.currentThread().getContextClassLoader(); ObjectInputStream ois = null; // Load the previously unloaded active sessions try { ois = getReplicationStream(data); Integer count = (Integer) ois.readObject(); int n = count.intValue(); for (int i = 0; i < n; i++) { DeltaSession session = (DeltaSession) createEmptySession(); session.readObjectData(ois); session.setManager(this); session.setValid(true); session.setPrimarySession(false); //in case the nodes in the cluster are out of //time synch, this will make sure that we have the //correct timestamp, isValid returns true, cause // accessCount=1 session.access(); //make sure that the session gets ready to expire if // needed session.setAccessCount(0); session.resetDeltaRequest(); // FIXME How inform other session id cache like SingleSignOn // increment sessionCounter to correct stats report if (findSession(session.getIdInternal()) == null ) { sessionCounter++; } else { sessionReplaceCounter++; // FIXME better is to grap this sessions again ! if (log.isWarnEnabled()) log.warn(sm.getString("deltaManager.loading.existing.session",session.getIdInternal())); } add(session); if (notifySessionListenersOnReplication) { session.tellNew(); } } } catch (ClassNotFoundException e) { log.error(sm.getString("deltaManager.loading.cnfe", e), e); throw e; } catch (IOException e) { log.error(sm.getString("deltaManager.loading.ioe", e), e); throw e; } finally { // Close the input stream try { if (ois != null) ois.close(); } catch (IOException f) { // ignored } ois = null; if (originalLoader != null) Thread.currentThread().setContextClassLoader(originalLoader); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected byte[] serializeSessions(Session[] currentSessions) throws IOException { // Open an output stream to the specified pathname, if any ByteArrayOutputStream fos = null; ObjectOutputStream oos = null; try { fos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(new BufferedOutputStream(fos)); oos.writeObject(Integer.valueOf(currentSessions.length)); for(int i=0 ; i < currentSessions.length;i++) { ((DeltaSession)currentSessions[i]).writeObjectData(oos); } // Flush and close the output stream oos.flush(); } catch (IOException e) { log.error(sm.getString("deltaManager.unloading.ioe", e), e); throw e; } finally { if (oos != null) { try { oos.close(); } catch (IOException f) { // Ignore } oos = null; } } // send object data as byte[] return fos.toByteArray(); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleSESSION_DELTA(SessionMessage msg, Member sender) throws IOException, ClassNotFoundException { counterReceive_EVT_SESSION_DELTA++; byte[] delta = msg.getSession(); DeltaSession session = (DeltaSession) findSession(msg.getSessionID()); if (session != null) { if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.delta",getName(), msg.getSessionID())); try { session.lock(); DeltaRequest dreq = deserializeDeltaRequest(session, delta); dreq.execute(session, isNotifyListenersOnReplication()); session.setPrimarySession(false); }finally { session.unlock(); } } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleSESSION_ACCESSED(SessionMessage msg,Member sender) throws IOException { counterReceive_EVT_SESSION_ACCESSED++; DeltaSession session = (DeltaSession) findSession(msg.getSessionID()); if (session != null) { if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.accessed",getName(), msg.getSessionID())); session.access(); session.setPrimarySession(false); session.endAccess(); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleSESSION_EXPIRED(SessionMessage msg,Member sender) throws IOException { counterReceive_EVT_SESSION_EXPIRED++; DeltaSession session = (DeltaSession) findSession(msg.getSessionID()); if (session != null) { if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.expired",getName(), msg.getSessionID())); session.expire(notifySessionListenersOnReplication, false); } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleALL_SESSION_DATA(SessionMessage msg,Member sender) throws ClassNotFoundException, IOException { counterReceive_EVT_ALL_SESSION_DATA++; if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataBegin",getName())); byte[] data = msg.getSession(); deserializeSessions(data); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataAfter",getName())); //stateTransferred = true; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleGET_ALL_SESSIONS(SessionMessage msg, Member sender) throws IOException { counterReceive_EVT_GET_ALL_SESSIONS++; //get a list of all the session from this manager if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.unloadingBegin", getName())); // Write the number of active sessions, followed by the details // get all sessions and serialize without sync Session[] currentSessions = findSessions(); long findSessionTimestamp = System.currentTimeMillis() ; if (isSendAllSessions()) { sendSessions(sender, currentSessions, findSessionTimestamp); } else { // send session at blocks for (int i = 0; i < currentSessions.length; i += getSendAllSessionsSize()) { int len = i + getSendAllSessionsSize() > currentSessions.length ? currentSessions.length - i : getSendAllSessionsSize(); Session[] sendSessions = new Session[len]; System.arraycopy(currentSessions, i, sendSessions, 0, len); sendSessions(sender, sendSessions,findSessionTimestamp); if (getSendAllSessionsWaitTime() > 0) { try { Thread.sleep(getSendAllSessionsWaitTime()); } catch (Exception sleep) { } }//end if }//for }//end if SessionMessage newmsg = new SessionMessageImpl(name,SessionMessage.EVT_ALL_SESSION_TRANSFERCOMPLETE, null,"SESSION-STATE-TRANSFERED", "SESSION-STATE-TRANSFERED"+ getName()); newmsg.setTimestamp(findSessionTimestamp); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.createMessage.allSessionTransfered",getName())); counterSend_EVT_ALL_SESSION_TRANSFERCOMPLETE++; cluster.send(newmsg, sender); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void handleCHANGE_SESSION_ID(SessionMessage msg,Member sender) throws IOException { counterReceive_EVT_CHANGE_SESSION_ID++; DeltaSession session = (DeltaSession) findSession(msg.getSessionID()); if (session != null) { String newSessionID = deserializeSessionId(msg.getSession()); session.setPrimarySession(false); session.setId(newSessionID, false); if (notifyContainerListenersOnReplication) { getContainer().fireContainerEvent(Context.CHANGE_SESSION_ID_EVENT, new String[] {msg.getSessionID(), newSessionID}); } } }
// in java/org/apache/catalina/ha/session/DeltaManager.java
protected void sendSessions(Member sender, Session[] currentSessions,long sendTimestamp) throws IOException { byte[] data = serializeSessions(currentSessions); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.unloadingAfter",getName())); SessionMessage newmsg = new SessionMessageImpl(name,SessionMessage.EVT_ALL_SESSION_DATA, data,"SESSION-STATE", "SESSION-STATE-" + getName()); newmsg.setTimestamp(sendTimestamp); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.createMessage.allSessionData",getName())); counterSend_EVT_ALL_SESSION_DATA++; cluster.send(newmsg, sender); }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public static FileMessageFactory getInstance(File f, boolean openForWrite) throws FileNotFoundException, IOException { return new FileMessageFactory(f, openForWrite); }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public FileMessage readMessage(FileMessage f) throws IllegalArgumentException, IOException { checkState(false); int length = in.read(data); if (length == -1) { cleanup(); return null; } else { f.setData(data, length); f.setTotalLength(size); f.setTotalNrOfMsgs(totalNrOfMessages); f.setMessageNumber(++nrOfMessagesProcessed); return f; }//end if }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public boolean writeMessage(FileMessage msg) throws IllegalArgumentException, IOException { if (!openForWrite) throw new IllegalArgumentException( "Can't write message, this factory is reading."); if (log.isDebugEnabled()) log.debug("Message " + msg + " data " + HexUtils.toHexString(msg.getData()) + " data length " + msg.getDataLength() + " out " + out); if (msg.getMessageNumber() <= lastMessageProcessed.get()) { // Duplicate of message already processed log.warn("Receive Message again -- Sender ActTimeout too short [ name: " + msg.getContextName() + " war: " + msg.getFileName() + " data: " + HexUtils.toHexString(msg.getData()) + " data length: " + msg.getDataLength() + " ]"); return false; } FileMessage previous = msgBuffer.put(Long.valueOf(msg.getMessageNumber()), msg); if (previous !=null) { // Duplicate of message not yet processed log.warn("Receive Message again -- Sender ActTimeout too short [ name: " + msg.getContextName() + " war: " + msg.getFileName() + " data: " + HexUtils.toHexString(msg.getData()) + " data length: " + msg.getDataLength() + " ]"); return false; } FileMessage next = null; synchronized (this) { if (!isWriting) { next = msgBuffer.get(Long.valueOf(lastMessageProcessed.get() + 1)); if (next != null) { isWriting = true; } else { return false; } } else { return false; } } while (next != null) { out.write(next.getData(), 0, next.getDataLength()); lastMessageProcessed.incrementAndGet(); out.flush(); if (next.getMessageNumber() == next.getTotalNrOfMsgs()) { out.close(); cleanup(); return true; } synchronized(this) { next = msgBuffer.get(Long.valueOf(lastMessageProcessed.get() + 1)); if (next == null) { isWriting = false; } } } return false; }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
public synchronized FileMessageFactory getFactory(FileMessage msg) throws java.io.FileNotFoundException, java.io.IOException { File writeToFile = new File(getTempDir(), msg.getFileName()); FileMessageFactory factory = fileFactories.get(msg.getFileName()); if (factory == null) { factory = FileMessageFactory.getInstance(writeToFile, true); fileFactories.put(msg.getFileName(), factory); } return factory; }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
Override public void install(String contextName, File webapp) throws IOException { Member[] members = getCluster().getMembers(); Member localMember = getCluster().getLocalMember(); FileMessageFactory factory = FileMessageFactory.getInstance(webapp, false); FileMessage msg = new FileMessage(localMember, webapp.getName(), contextName); if(log.isDebugEnabled()) log.debug(sm.getString("farmWarDeployer.sendStart", contextName, webapp)); msg = factory.readMessage(msg); while (msg != null) { for (int i = 0; i < members.length; i++) { if (log.isDebugEnabled()) log.debug(sm.getString("farmWarDeployer.sendFragment", contextName, webapp, members[i])); getCluster().send(msg, members[i]); } msg = factory.readMessage(msg); } if(log.isDebugEnabled()) log.debug(sm.getString( "farmWarDeployer.sendEnd", contextName, webapp)); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
Override public void remove(String contextName, boolean undeploy) throws IOException { if (log.isInfoEnabled()) log.info(sm.getString("farmWarDeployer.removeStart", contextName)); Member localMember = getCluster().getLocalMember(); UndeployMessage msg = new UndeployMessage(localMember, System .currentTimeMillis(), "Undeploy:" + contextName + ":" + System.currentTimeMillis(), contextName, undeploy); if (log.isDebugEnabled()) log.debug(sm.getString("farmWarDeployer.removeTxMsg", contextName)); cluster.send(msg); // remove locally if (undeploy) { try { if (!isServiced(contextName)) { addServiced(contextName); try { remove(contextName); } finally { removeServiced(contextName); } } else log.error(sm.getString("farmWarDeployer.removeFailRemote", contextName)); } catch (Exception ex) { log.error(sm.getString("farmWarDeployer.removeFailLocal", contextName), ex); } } }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { long totalstart = 0; //this happens before the request if(doStatistics()) { totalstart = System.currentTimeMillis(); } if (primaryIndicator) { createPrimaryIndicator(request) ; } Context context = request.getContext(); boolean isCrossContext = context != null && context instanceof StandardContext && ((StandardContext) context).getCrossContext(); try { if(isCrossContext) { if(log.isDebugEnabled()) { log.debug(sm.getString("ReplicationValve.crossContext.add")); } //FIXME add Pool of Arraylists crossContextSessions.set(new ArrayList<DeltaSession>()); } getNext().invoke(request, response); if(context != null) { Manager manager = context.getManager(); if (manager != null && manager instanceof ClusterManager) { ClusterManager clusterManager = (ClusterManager) manager; CatalinaCluster containerCluster = (CatalinaCluster) getContainer().getCluster(); if (containerCluster == null) { if (log.isWarnEnabled()) { log.warn(sm.getString("ReplicationValve.nocluster")); } return; } // valve cluster can access manager - other cluster handle replication // at host level - hopefully! if(containerCluster.getManager(clusterManager.getName()) == null) { return ; } if(containerCluster.hasMembers()) { sendReplicationMessage(request, totalstart, isCrossContext, clusterManager, containerCluster); } else { resetReplicationRequest(request,isCrossContext); } } } } finally { // Array must be remove: Current master request send endAccess at recycle. // Don't register this request session again! if(isCrossContext) { if(log.isDebugEnabled()) { log.debug(sm.getString("ReplicationValve.crossContext.remove")); } // crossContextSessions.remove() only exist at Java 5 // register ArrayList at a pool crossContextSessions.set(null); } } }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
protected void createPrimaryIndicator(Request request) throws IOException { String id = request.getRequestedSessionId(); if ((id != null) && (id.length() > 0)) { Manager manager = request.getContext().getManager(); Session session = manager.findSession(id); if (session instanceof ClusterSession) { ClusterSession cses = (ClusterSession) session; if (log.isDebugEnabled()) { log.debug(sm.getString( "ReplicationValve.session.indicator", request.getContext().getName(),id, primaryIndicatorName, Boolean.valueOf(cses.isPrimarySession()))); } request.setAttribute(primaryIndicatorName, cses.isPrimarySession()?Boolean.TRUE:Boolean.FALSE); } else { if (log.isDebugEnabled()) { if (session != null) { log.debug(sm.getString( "ReplicationValve.session.found", request.getContext().getName(),id)); } else { log.debug(sm.getString( "ReplicationValve.session.invalid", request.getContext().getName(),id)); } } } } }
// in java/org/apache/catalina/ssi/SSIFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // cast once HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse res = (HttpServletResponse)response; // indicate that we're in SSI processing req.setAttribute(Globals.SSI_FLAG_ATTR, "true"); // setup to capture output ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream(); ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(config.getServletContext(),req, res, basos); // process remainder of filter chain chain.doFilter(req, responseIncludeWrapper); // we can't assume the chain flushed its output responseIncludeWrapper.flushOutputStreamOrWriter(); byte[] bytes = basos.toByteArray(); // get content type String contentType = responseIncludeWrapper.getContentType(); // is this an allowed type for SSI processing? if (contentTypeRegEx.matcher(contentType).matches()) { String encoding = res.getCharacterEncoding(); // set up SSI processing SSIExternalResolver ssiExternalResolver = new SSIServletExternalResolver(config.getServletContext(), req, res, isVirtualWebappRelative, debug, encoding); SSIProcessor ssiProcessor = new SSIProcessor(ssiExternalResolver, debug, allowExec); // prepare readers/writers Reader reader = new InputStreamReader(new ByteArrayInputStream(bytes), encoding); ByteArrayOutputStream ssiout = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(ssiout, encoding)); // do SSI processing long lastModified = ssiProcessor.process(reader, responseIncludeWrapper.getLastModified(), writer); // set output bytes writer.flush(); bytes = ssiout.toByteArray(); // override headers if (expires != null) { res.setDateHeader("expires", (new java.util.Date()).getTime() + expires.longValue() * 1000); } if (lastModified > 0) { res.setDateHeader("last-modified", lastModified); } res.setContentLength(bytes.length); Matcher shtmlMatcher = shtmlRegEx.matcher(responseIncludeWrapper.getContentType()); if (shtmlMatcher.matches()) { // Convert shtml mime type to ordinary html mime type but preserve // encoding, if any. String enc = shtmlMatcher.group(1); res.setContentType("text/html" + ((enc != null) ? enc : "")); } } // write output OutputStream out = null; try { out = res.getOutputStream(); } catch (IllegalStateException e) { // Ignore, will try to use a writer } if (out == null) { res.getWriter().write(new String(bytes)); } else { out.write(bytes); } }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected String getAbsolutePath(String path) throws IOException { String pathWithoutContext = SSIServletRequestUtil.getRelativePath(req); String prefix = getPathWithoutFileName(pathWithoutContext); if (prefix == null) { throw new IOException("Couldn't remove filename from path: " + pathWithoutContext); } String fullPath = prefix + path; String retVal = RequestUtil.normalize(fullPath); if (retVal == null) { throw new IOException("Normalization yielded null on path: " + fullPath); } return retVal; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected ServletContextAndPath getServletContextAndPathFromNonVirtualPath( String nonVirtualPath) throws IOException { if (nonVirtualPath.startsWith("/") || nonVirtualPath.startsWith("\\")) { throw new IOException("A non-virtual path can't be absolute: " + nonVirtualPath); } if (nonVirtualPath.indexOf("../") >= 0) { throw new IOException("A non-virtual path can't contain '../' : " + nonVirtualPath); } String path = getAbsolutePath(nonVirtualPath); ServletContextAndPath csAndP = new ServletContextAndPath( context, path); return csAndP; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected ServletContextAndPath getServletContextAndPathFromVirtualPath( String virtualPath) throws IOException { if (!virtualPath.startsWith("/") && !virtualPath.startsWith("\\")) { return new ServletContextAndPath(context, getAbsolutePath(virtualPath)); } String normalized = RequestUtil.normalize(virtualPath); if (isVirtualWebappRelative) { return new ServletContextAndPath(context, normalized); } ServletContext normContext = context.getContext(normalized); if (normContext == null) { throw new IOException("Couldn't get context for path: " + normalized); } //If it's the root context, then there is no context element // to remove, // ie: // '/file1.shtml' vs '/appName1/file1.shtml' if (!isRootContext(normContext)) { String noContext = getPathWithoutContext( normContext.getContextPath(), normalized); if (noContext == null) { throw new IOException( "Couldn't remove context from path: " + normalized); } return new ServletContextAndPath(normContext, noContext); } return new ServletContextAndPath(normContext, normalized); }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected ServletContextAndPath getServletContextAndPath( String originalPath, boolean virtual) throws IOException { ServletContextAndPath csAndP = null; if (debug > 0) { log("SSIServletExternalResolver.getServletContextAndPath( " + originalPath + ", " + virtual + ")", null); } if (virtual) { csAndP = getServletContextAndPathFromVirtualPath(originalPath); } else { csAndP = getServletContextAndPathFromNonVirtualPath(originalPath); } return csAndP; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
protected URLConnection getURLConnection(String originalPath, boolean virtual) throws IOException { ServletContextAndPath csAndP = getServletContextAndPath(originalPath, virtual); ServletContext context = csAndP.getServletContext(); String path = csAndP.getPath(); URL url = context.getResource(path); if (url == null) { throw new IOException("Context did not contain resource: " + path); } URLConnection urlConnection = url.openConnection(); return urlConnection; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
Override public long getFileLastModified(String path, boolean virtual) throws IOException { long lastModified = 0; try { URLConnection urlConnection = getURLConnection(path, virtual); lastModified = urlConnection.getLastModified(); } catch (IOException e) { // Ignore this. It will always fail for non-file based includes } return lastModified; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
Override public long getFileSize(String path, boolean virtual) throws IOException { long fileSize = -1; try { URLConnection urlConnection = getURLConnection(path, virtual); fileSize = urlConnection.getContentLength(); } catch (IOException e) { // Ignore this. It will always fail for non-file based includes } return fileSize; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
Override public String getFileText(String originalPath, boolean virtual) throws IOException { try { ServletContextAndPath csAndP = getServletContextAndPath( originalPath, virtual); ServletContext context = csAndP.getServletContext(); String path = csAndP.getPath(); RequestDispatcher rd = context.getRequestDispatcher(path); if (rd == null) { throw new IOException( "Couldn't get request dispatcher for path: " + path); } ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream(); ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(context, req, res, basos); rd.include(req, responseIncludeWrapper); //We can't assume the included servlet flushed its output responseIncludeWrapper.flushOutputStreamOrWriter(); byte[] bytes = basos.toByteArray(); //Assume platform default encoding unless otherwise specified String retVal; if (inputEncoding == null) { retVal = new String( bytes ); } else { retVal = new String (bytes, B2CConverter.getCharset(inputEncoding)); } //make an assumption that an empty response is a failure. This is // a problem // if a truly empty file //were included, but not sure how else to tell. if (retVal.equals("") && !req.getMethod().equalsIgnoreCase( org.apache.coyote.http11.Constants.HEAD)) { throw new IOException("Couldn't find file: " + path); } return retVal; } catch (ServletException e) { throw new IOException("Couldn't include file: " + originalPath + " because of ServletException: " + e.getMessage()); } }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
public void flushOutputStreamOrWriter() throws IOException { if (servletOutputStream != null) { servletOutputStream.flush(); } if (printWriter != null) { printWriter.flush(); } }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
Override public PrintWriter getWriter() throws java.io.IOException { if (servletOutputStream == null) { if (printWriter == null) { setCharacterEncoding(getCharacterEncoding()); printWriter = new PrintWriter( new OutputStreamWriter(captureServletOutputStream, getCharacterEncoding())); } return printWriter; } throw new IllegalStateException(); }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
Override public ServletOutputStream getOutputStream() throws java.io.IOException { if (printWriter == null) { if (servletOutputStream == null) { servletOutputStream = captureServletOutputStream; } return servletOutputStream; } throw new IllegalStateException(); }
// in java/org/apache/catalina/ssi/SSIServlet.java
Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { if (debug > 0) log("SSIServlet.doGet()"); requestHandler(req, res); }
// in java/org/apache/catalina/ssi/SSIServlet.java
Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { if (debug > 0) log("SSIServlet.doPost()"); requestHandler(req, res); }
// in java/org/apache/catalina/ssi/SSIServlet.java
protected void requestHandler(HttpServletRequest req, HttpServletResponse res) throws IOException { ServletContext servletContext = getServletContext(); String path = SSIServletRequestUtil.getRelativePath(req); if (debug > 0) log("SSIServlet.requestHandler()\n" + "Serving " + (buffered?"buffered ":"unbuffered ") + "resource '" + path + "'"); // Exclude any resource in the /WEB-INF and /META-INF subdirectories // (the "toUpperCase()" avoids problems on Windows systems) if (path == null || path.toUpperCase(Locale.ENGLISH).startsWith("/WEB-INF") || path.toUpperCase(Locale.ENGLISH).startsWith("/META-INF")) { res.sendError(HttpServletResponse.SC_NOT_FOUND, path); log("Can't serve file: " + path); return; } URL resource = servletContext.getResource(path); if (resource == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND, path); log("Can't find file: " + path); return; } String resourceMimeType = servletContext.getMimeType(path); if (resourceMimeType == null) { resourceMimeType = "text/html"; } res.setContentType(resourceMimeType + ";charset=" + outputEncoding); if (expires != null) { res.setDateHeader("Expires", (new java.util.Date()).getTime() + expires.longValue() * 1000); } req.setAttribute(Globals.SSI_FLAG_ATTR, "true"); processSSI(req, res, resource); }
// in java/org/apache/catalina/ssi/SSIServlet.java
protected void processSSI(HttpServletRequest req, HttpServletResponse res, URL resource) throws IOException { SSIExternalResolver ssiExternalResolver = new SSIServletExternalResolver(getServletContext(), req, res, isVirtualWebappRelative, debug, inputEncoding); SSIProcessor ssiProcessor = new SSIProcessor(ssiExternalResolver, debug, allowExec); PrintWriter printWriter = null; StringWriter stringWriter = null; if (buffered) { stringWriter = new StringWriter(); printWriter = new PrintWriter(stringWriter); } else { printWriter = res.getWriter(); } URLConnection resourceInfo = resource.openConnection(); InputStream resourceInputStream = resourceInfo.getInputStream(); String encoding = resourceInfo.getContentEncoding(); if (encoding == null) { encoding = inputEncoding; } InputStreamReader isr; if (encoding == null) { isr = new InputStreamReader(resourceInputStream); } else { isr = new InputStreamReader(resourceInputStream, encoding); } BufferedReader bufferedReader = new BufferedReader(isr); long lastModified = ssiProcessor.process(bufferedReader, resourceInfo.getLastModified(), printWriter); if (lastModified > 0) { res.setDateHeader("last-modified", lastModified); } if (buffered) { printWriter.flush(); @SuppressWarnings("null") String text = stringWriter.toString(); res.getWriter().write(text); } bufferedReader.close(); }
// in java/org/apache/catalina/ssi/SSIProcessor.java
public long process(Reader reader, long lastModifiedDate, PrintWriter writer) throws IOException { SSIMediator ssiMediator = new SSIMediator(ssiExternalResolver, lastModifiedDate, debug); StringWriter stringWriter = new StringWriter(); IOTools.flow(reader, stringWriter); String fileContents = stringWriter.toString(); stringWriter = null; int index = 0; boolean inside = false; StringBuilder command = new StringBuilder(); try { while (index < fileContents.length()) { char c = fileContents.charAt(index); if (!inside) { if (c == COMMAND_START.charAt(0) && charCmp(fileContents, index, COMMAND_START)) { inside = true; index += COMMAND_START.length(); command.setLength(0); //clear the command string } else { if (!ssiMediator.getConditionalState().processConditionalCommandsOnly) { writer.write(c); } index++; } } else { if (c == COMMAND_END.charAt(0) && charCmp(fileContents, index, COMMAND_END)) { inside = false; index += COMMAND_END.length(); String strCmd = parseCmd(command); if (debug > 0) { ssiExternalResolver.log( "SSIProcessor.process -- processing command: " + strCmd, null); } String[] paramNames = parseParamNames(command, strCmd .length()); String[] paramValues = parseParamValues(command, strCmd.length(), paramNames.length); //We need to fetch this value each time, since it may // change // during the loop String configErrMsg = ssiMediator.getConfigErrMsg(); SSICommand ssiCommand = commands.get(strCmd.toLowerCase(Locale.ENGLISH)); String errorMessage = null; if (ssiCommand == null) { errorMessage = "Unknown command: " + strCmd; } else if (paramValues == null) { errorMessage = "Error parsing directive parameters."; } else if (paramNames.length != paramValues.length) { errorMessage = "Parameter names count does not match parameter values count on command: " + strCmd; } else { // don't process the command if we are processing // conditional // commands only and the // command is not conditional if (!ssiMediator.getConditionalState().processConditionalCommandsOnly || ssiCommand instanceof SSIConditional) { long lmd = ssiCommand.process(ssiMediator, strCmd, paramNames, paramValues, writer); if (lmd > lastModifiedDate) { lastModifiedDate = lmd; } } } if (errorMessage != null) { ssiExternalResolver.log(errorMessage, null); writer.write(configErrMsg); } } else { command.append(c); index++; } } } } catch (SSIStopProcessingException e) { //If we are here, then we have already stopped processing, so all // is good } return lastModifiedDate; }
// in java/org/apache/catalina/ssi/SSIMediator.java
public long getFileSize(String path, boolean virtual) throws IOException { return ssiExternalResolver.getFileSize(path, virtual); }
// in java/org/apache/catalina/ssi/SSIMediator.java
public long getFileLastModified(String path, boolean virtual) throws IOException { return ssiExternalResolver.getFileLastModified(path, virtual); }
// in java/org/apache/catalina/ssi/SSIMediator.java
public String getFileText(String path, boolean virtual) throws IOException { return ssiExternalResolver.getFileText(path, virtual); }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void close() throws IOException { if (closed) { return; } if (suspended) { return; } // Flush the convertor if one is in use if (gotEnc && conv != null) { conv.flushBuffer(); } if ((!coyoteResponse.isCommitted()) && (coyoteResponse.getContentLengthLong() == -1)) { // If this didn't cause a commit of the response, the final content // length can be calculated if (!coyoteResponse.isCommitted()) { coyoteResponse.setContentLength(bb.getLength()); } } doFlush(false); closed = true; // The request should have been completely read by the time the response // is closed. Further reads of the input a) are pointless and b) really // confuse AJP (bug 50189) so close the input buffer to prevent them. Request req = (Request) coyoteResponse.getRequest().getNote( CoyoteAdapter.ADAPTER_NOTES); req.inputBuffer.close(); coyoteResponse.finish(); }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void flush() throws IOException { doFlush(true); }
// in java/org/apache/catalina/connector/OutputBuffer.java
protected void doFlush(boolean realFlush) throws IOException { if (suspended) { return; } // Flush the convertor if one is in use if (gotEnc && conv != null) { conv.flushBuffer(); } try { doFlush = true; if (initial) { coyoteResponse.sendHeaders(); initial = false; } if (bb.getLength() > 0) { bb.flushBuffer(); } } finally { doFlush = false; } if (realFlush) { coyoteResponse.action(ActionCode.CLIENT_FLUSH, coyoteResponse); // If some exception occurred earlier, or if some IOE occurred // here, notify the servlet with an IOE if (coyoteResponse.isExceptionPresent()) { throw new ClientAbortException (coyoteResponse.getErrorException()); } } }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void realWriteBytes(byte buf[], int off, int cnt) throws IOException { if (closed) { return; } if (coyoteResponse == null) { return; } // If we really have something to write if (cnt > 0) { // real write to the adapter outputChunk.setBytes(buf, off, cnt); try { coyoteResponse.doWrite(outputChunk); } catch (IOException e) { // An IOException on a write is almost always due to // the remote client aborting the request. Wrap this // so that it can be handled better by the error dispatcher. throw new ClientAbortException(e); } } }
// in java/org/apache/catalina/connector/OutputBuffer.java
public void write(byte b[], int off, int len) throws IOException { if (suspended) { return; } writeBytes(b, off, len); }
// in java/org/apache/catalina/connector/OutputBuffer.java
private void writeBytes(byte b[], int off, int len) throws IOException { if (closed) { return; } bb.append(b, off, len); bytesWritten += len; // if called from within flush(), then immediately flush // remaining bytes if (doFlush) { bb.flushBuffer(); } }
// in java/org/apache/catalina/connector/OutputBuffer.java
public void writeByte(int b) throws IOException { if (suspended) { return; } bb.append((byte) b); bytesWritten++; }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void write(int c) throws IOException { if (suspended) { return; } conv.convert((char) c); charsWritten++; }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void write(char c[]) throws IOException { if (suspended) { return; } write(c, 0, c.length); }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void write(char c[], int off, int len) throws IOException { if (suspended) { return; } conv.convert(c, off, len); charsWritten += len; }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void write(String s, int off, int len) throws IOException { if (suspended) { return; } charsWritten += len; if (s == null) { s = "null"; } conv.convert(s, off, len); }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public void write(String s) throws IOException { if (suspended) { return; } if (s == null) { s = "null"; } conv.convert(s); }
// in java/org/apache/catalina/connector/OutputBuffer.java
public void checkConverter() throws IOException { if (!gotEnc) { setConverter(); } }
// in java/org/apache/catalina/connector/OutputBuffer.java
protected void setConverter() throws IOException { if (coyoteResponse != null) { enc = coyoteResponse.getCharacterEncoding(); } gotEnc = true; if (enc == null) { enc = DEFAULT_ENCODING; } conv = encoders.get(enc); if (conv == null) { if (Globals.IS_SECURITY_ENABLED){ try{ conv = AccessController.doPrivileged( new PrivilegedExceptionAction<C2BConverter>(){ @Override public C2BConverter run() throws IOException{ return new C2BConverter(bb, enc); } } ); }catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } } } else { conv = new C2BConverter(bb, enc); } encoders.put(enc, conv); }
// in java/org/apache/catalina/connector/OutputBuffer.java
Override public C2BConverter run() throws IOException{ return new C2BConverter(bb, enc); }
// in java/org/apache/catalina/connector/Request.java
public boolean read() throws IOException { return (inputBuffer.realReadBytes(null, 0, 0) > 0); }
// in java/org/apache/catalina/connector/Request.java
public ServletInputStream createInputStream() throws IOException { if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } return inputStream; }
// in java/org/apache/catalina/connector/Request.java
public void finishRequest() throws IOException { // Optionally disable swallowing of additional request data. Context context = getContext(); if (context != null && response.getStatus() == HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE && !context.getSwallowAbortedUploads()) { coyoteRequest.action(ActionCode.DISABLE_SWALLOW_INPUT, null); } }
// in java/org/apache/catalina/connector/Request.java
Override public ServletInputStream getInputStream() throws IOException { if (usingReader) { throw new IllegalStateException (sm.getString("coyoteRequest.getInputStream.ise")); } usingInputStream = true; if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } return inputStream; }
// in java/org/apache/catalina/connector/Request.java
Override public BufferedReader getReader() throws IOException { if (usingInputStream) { throw new IllegalStateException (sm.getString("coyoteRequest.getReader.ise")); } usingReader = true; inputBuffer.checkConverter(); if (reader == null) { reader = new CoyoteReader(inputBuffer); } return reader; }
// in java/org/apache/catalina/connector/Request.java
Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { if (response.isCommitted()) { throw new IllegalStateException( sm.getString("coyoteRequest.authenticate.ise")); } return context.getAuthenticator().authenticate(this, response); }
// in java/org/apache/catalina/connector/Request.java
Override public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException { parseParts(); if (partsParseException != null) { if (partsParseException instanceof IOException) { throw (IOException) partsParseException; } else if (partsParseException instanceof IllegalStateException) { throw (IllegalStateException) partsParseException; } else if (partsParseException instanceof ServletException) { throw (ServletException) partsParseException; } } return parts; }
// in java/org/apache/catalina/connector/Request.java
Override public Part getPart(String name) throws IOException, IllegalStateException, ServletException { Collection<Part> c = getParts(); Iterator<Part> iterator = c.iterator(); while (iterator.hasNext()) { Part part = iterator.next(); if (name.equals(part.getName())) { return part; } } return null; }
// in java/org/apache/catalina/connector/Request.java
public void doUpgrade(UpgradeInbound inbound) throws IOException { coyoteRequest.action(ActionCode.UPGRADE, inbound); // Output required by RFC2616. Protocol specific headers should have // already been set. response.setStatus(HttpServletResponse.SC_SWITCHING_PROTOCOLS); response.flushBuffer(); }
// in java/org/apache/catalina/connector/Request.java
protected int readPostBody(byte body[], int len) throws IOException { int offset = 0; do { int inputLen = getStream().read(body, offset, len - offset); if (inputLen <= 0) { return offset; } offset += inputLen; } while ((len - offset) > 0); return len; }
// in java/org/apache/catalina/connector/Request.java
protected byte[] readChunkedPostBody() throws IOException { ByteChunk body = new ByteChunk(); byte[] buffer = new byte[CACHED_POST_LEN]; int len = 0; while (len > -1) { len = getStream().read(buffer, 0, CACHED_POST_LEN); if (connector.getMaxPostSize() > 0 && (body.getLength() + len) > connector.getMaxPostSize()) { // Too much data checkSwallowInput(); throw new IOException( sm.getString("coyoteRequest.chunkedPostTooLarge")); } if (len > 0) { body.append(buffer, 0, len); } } if (body.getLength() == 0) { return null; } if (body.getLength() < body.getBuffer().length) { int length = body.getLength(); byte[] result = new byte[length]; System.arraycopy(body.getBuffer(), 0, result, 0, length); return result; } return body.getBuffer(); }
// in java/org/apache/catalina/connector/CoyoteOutputStream.java
Override public void write(int i) throws IOException { ob.writeByte(i); }
// in java/org/apache/catalina/connector/CoyoteOutputStream.java
Override public void write(byte[] b) throws IOException { write(b, 0, b.length); }
// in java/org/apache/catalina/connector/CoyoteOutputStream.java
Override public void write(byte[] b, int off, int len) throws IOException { ob.write(b, off, len); }
// in java/org/apache/catalina/connector/CoyoteOutputStream.java
Override public void flush() throws IOException { ob.flush(); }
// in java/org/apache/catalina/connector/CoyoteOutputStream.java
Override public void close() throws IOException { ob.close(); }
// in java/org/apache/catalina/connector/Response.java
public void finishResponse() throws IOException { // Writing leftover bytes outputBuffer.close(); }
// in java/org/apache/catalina/connector/Response.java
public PrintWriter getReporter() throws IOException { if (outputBuffer.isNew()) { outputBuffer.checkConverter(); if (writer == null) { writer = new CoyoteWriter(outputBuffer); } return writer; } else { return null; } }
// in java/org/apache/catalina/connector/Response.java
Override public void flushBuffer() throws IOException { outputBuffer.flush(); }
// in java/org/apache/catalina/connector/Response.java
Override public ServletOutputStream getOutputStream() throws IOException { if (usingWriter) { throw new IllegalStateException (sm.getString("coyoteResponse.getOutputStream.ise")); } usingOutputStream = true; if (outputStream == null) { outputStream = new CoyoteOutputStream(outputBuffer); } return outputStream; }
// in java/org/apache/catalina/connector/Response.java
Override public PrintWriter getWriter() throws IOException { if (usingOutputStream) { throw new IllegalStateException (sm.getString("coyoteResponse.getWriter.ise")); } if (ENFORCE_ENCODING_IN_GET_WRITER) { /* * If the response's character encoding has not been specified as * described in <code>getCharacterEncoding</code> (i.e., the method * just returns the default value <code>ISO-8859-1</code>), * <code>getWriter</code> updates it to <code>ISO-8859-1</code> * (with the effect that a subsequent call to getContentType() will * include a charset=ISO-8859-1 component which will also be * reflected in the Content-Type response header, thereby satisfying * the Servlet spec requirement that containers must communicate the * character encoding used for the servlet response's writer to the * client). */ setCharacterEncoding(getCharacterEncoding()); } usingWriter = true; outputBuffer.checkConverter(); if (writer == null) { writer = new CoyoteWriter(outputBuffer); } return writer; }
// in java/org/apache/catalina/connector/Response.java
public void sendAcknowledgement() throws IOException { if (isCommitted()) { return; } // Ignore any call from an included servlet if (included) { return; } coyoteResponse.acknowledge(); }
// in java/org/apache/catalina/connector/Response.java
Override public void sendError(int status) throws IOException { sendError(status, null); }
// in java/org/apache/catalina/connector/Response.java
Override public void sendError(int status, String message) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendError.ise")); } // Ignore any call from an included servlet if (included) { return; } Wrapper wrapper = getRequest().getWrapper(); if (wrapper != null) { wrapper.incrementErrorCount(); } setError(); coyoteResponse.setStatus(status); coyoteResponse.setMessage(message); // Clear any data content that has been buffered resetBuffer(); // Cause the response to be finished (from the application perspective) setSuspended(true); }
// in java/org/apache/catalina/connector/Response.java
Override public void sendRedirect(String location) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendRedirect.ise")); } // Ignore any call from an included servlet if (included) { return; } // Clear any data content that has been buffered resetBuffer(true); // Generate a temporary redirect to the specified location try { String absolute = toAbsolute(location); setStatus(SC_FOUND); setHeader("Location", absolute); if (getContext().getSendRedirectBody()) { PrintWriter writer = getWriter(); writer.print(sm.getString("coyoteResponse.sendRedirect.note", RequestUtil.filter(absolute))); flushBuffer(); } } catch (IllegalArgumentException e) { setStatus(SC_NOT_FOUND); } // Cause the response to be finished (from the application perspective) setSuspended(true); }
// in java/org/apache/catalina/connector/Response.java
protected String toAbsolute(String location) { if (location == null) { return (location); } boolean leadingSlash = location.startsWith("/"); if (location.startsWith("//")) { // Scheme relative redirectURLCC.recycle(); // Add the scheme String scheme = request.getScheme(); try { redirectURLCC.append(scheme, 0, scheme.length()); redirectURLCC.append(':'); redirectURLCC.append(location, 0, location.length()); return redirectURLCC.toString(); } catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; } } else if (leadingSlash || !hasScheme(location)) { redirectURLCC.recycle(); String scheme = request.getScheme(); String name = request.getServerName(); int port = request.getServerPort(); try { redirectURLCC.append(scheme, 0, scheme.length()); redirectURLCC.append("://", 0, 3); redirectURLCC.append(name, 0, name.length()); if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443)) { redirectURLCC.append(':'); String portS = port + ""; redirectURLCC.append(portS, 0, portS.length()); } if (!leadingSlash) { String relativePath = request.getDecodedRequestURI(); int pos = relativePath.lastIndexOf('/'); relativePath = relativePath.substring(0, pos); String encodedURI = null; final String frelativePath = relativePath; if (SecurityUtil.isPackageProtectionEnabled() ){ try{ encodedURI = AccessController.doPrivileged( new PrivilegedExceptionAction<String>(){ @Override public String run() throws IOException{ return urlEncoder.encodeURL(frelativePath); } }); } catch (PrivilegedActionException pae){ IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(pae.getException()); throw iae; } } else { encodedURI = urlEncoder.encodeURL(relativePath); } redirectURLCC.append(encodedURI, 0, encodedURI.length()); redirectURLCC.append('/'); } redirectURLCC.append(location, 0, location.length()); normalize(redirectURLCC); } catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; } return redirectURLCC.toString(); }
// in java/org/apache/catalina/connector/Response.java
Override public String run() throws IOException{ return urlEncoder.encodeURL(frelativePath); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public ServletInputStream getInputStream() throws IOException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getInputStream(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public BufferedReader getReader() throws IOException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getReader(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { return request.authenticate(response); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Collection<Part> getParts() throws IllegalStateException, IOException, ServletException { return request.getParts(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Part getPart(String name) throws IllegalStateException, IOException, ServletException { return request.getPart(name); }
// in java/org/apache/catalina/connector/RequestFacade.java
public void doUpgrade(UpgradeInbound inbound) throws IOException { request.doUpgrade(inbound); }
// in java/org/apache/catalina/connector/CometEventImpl.java
Override public void close() throws IOException { if (request == null) { throw new IllegalStateException(sm.getString("cometEvent.nullRequest")); } request.finishRequest(); response.finishResponse(); if (request.isComet()) { request.cometClose(); } }
// in java/org/apache/catalina/connector/CometEventImpl.java
Override public void setTimeout(int timeout) throws IOException, ServletException, UnsupportedOperationException { if (request.getAttribute(Globals.COMET_TIMEOUT_SUPPORTED_ATTR) == Boolean.TRUE) { request.setAttribute(Globals.COMET_TIMEOUT_ATTR, Integer.valueOf(timeout)); if (request.isComet()) { request.setCometTimeout(timeout); } } else { throw new UnsupportedOperationException(); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int read() throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.readByte()); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.readByte()); return integer; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int available() throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.available()); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.available()); return integer; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int read(final byte[] b) throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.read(b, 0, b.length)); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage() ,e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.read(b, 0, b.length)); return integer; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int read(final byte[] b, final int off, final int len) throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.read(b, off, len)); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.read(b, off, len)); return integer; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int readLine(byte[] b, int off, int len) throws IOException { return super.readLine(b, off, len); }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public void close() throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ AccessController.doPrivileged( new PrivilegedExceptionAction<Void>(){ @Override public Void run() throws IOException{ ib.close(); return null; } }); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public Void run() throws IOException{ ib.close(); return null; }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public void close() throws IOException { closed = true; }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int realReadBytes(byte cbuf[], int off, int len) throws IOException { if (closed) { return -1; } if (coyoteRequest == null) { return -1; } if(state == INITIAL_STATE) { state = BYTE_STATE; } int result = coyoteRequest.doRead(bb); return result; }
// in java/org/apache/catalina/connector/InputBuffer.java
public int readByte() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return bb.substract(); }
// in java/org/apache/catalina/connector/InputBuffer.java
public int read(byte[] b, int off, int len) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return bb.substract(b, off, len); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public void realWriteChars(char c[], int off, int len) throws IOException { markPos = -1; cb.setOffset(0); cb.setEnd(0); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int realReadChars(char cbuf[], int off, int len) throws IOException { if (!gotEnc) { setConverter(); } if (bb.getLength() <= 0) { int nRead = realReadBytes(bb.getBytes(), 0, bb.getBytes().length); if (nRead < 0) { return -1; } } if (markPos == -1) { cb.setOffset(0); cb.setEnd(0); } int limit = bb.getLength()+cb.getStart(); if ( cb.getLimit() < limit ) { cb.setLimit(limit); } state = CHAR_STATE; conv.convert(bb, cb, bb.getLength()); bb.setOffset(bb.getEnd()); return cb.getLength(); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int read() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return cb.substract(); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int read(char[] cbuf) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return read(cbuf, 0, cbuf.length); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public int read(char[] cbuf, int off, int len) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return cb.substract(cbuf, off, len); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public long skip(long n) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } if (n < 0) { throw new IllegalArgumentException(); } long nRead = 0; while (nRead < n) { if (cb.getLength() >= n) { cb.setOffset(cb.getStart() + (int) n); nRead = n; } else { nRead += cb.getLength(); cb.setOffset(cb.getEnd()); int toRead = 0; if (cb.getChars().length < (n - nRead)) { toRead = cb.getChars().length; } else { toRead = (int) (n - nRead); } int nb = realReadChars(cb.getChars(), 0, toRead); if (nb < 0) { break; } } } return nRead; }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public boolean ready() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } return (available() > 0); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public void mark(int readAheadLimit) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } if (cb.getLength() <= 0) { cb.setOffset(0); cb.setEnd(0); } else { if ((cb.getBuffer().length > (2 * size)) && (cb.getLength()) < (cb.getStart())) { System.arraycopy(cb.getBuffer(), cb.getStart(), cb.getBuffer(), 0, cb.getLength()); cb.setEnd(cb.getLength()); cb.setOffset(0); } } cb.setLimit(cb.getStart() + readAheadLimit + size); markPos = cb.getStart(); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public void reset() throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } if (state == CHAR_STATE) { if (markPos < 0) { cb.recycle(); markPos = -1; throw new IOException(); } else { cb.setOffset(markPos); } } else { bb.recycle(); } }
// in java/org/apache/catalina/connector/InputBuffer.java
public void checkConverter() throws IOException { if (!gotEnc) { setConverter(); } }
// in java/org/apache/catalina/connector/InputBuffer.java
protected void setConverter() throws IOException { if (coyoteRequest != null) { enc = coyoteRequest.getCharacterEncoding(); } gotEnc = true; if (enc == null) { enc = DEFAULT_ENCODING; } conv = encoders.get(enc); if (conv == null) { if (SecurityUtil.isPackageProtectionEnabled()){ try{ conv = AccessController.doPrivileged( new PrivilegedExceptionAction<B2CConverter>(){ @Override public B2CConverter run() throws IOException { return new B2CConverter(enc); } } ); }catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } } } else { conv = new B2CConverter(enc); } encoders.put(enc, conv); }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public B2CConverter run() throws IOException { return new B2CConverter(enc); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public ServletOutputStream getOutputStream() throws IOException { // if (isFinished()) // throw new IllegalStateException // (/*sm.getString("responseFacade.finished")*/); ServletOutputStream sos = response.getOutputStream(); if (isFinished()) { response.setSuspended(true); } return (sos); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public PrintWriter getWriter() throws IOException { // if (isFinished()) // throw new IllegalStateException // (/*sm.getString("responseFacade.finished")*/); PrintWriter writer = response.getWriter(); if (isFinished()) { response.setSuspended(true); } return (writer); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void flushBuffer() throws IOException { if (isFinished()) { // throw new IllegalStateException // (/*sm.getString("responseFacade.finished")*/); return; } if (SecurityUtil.isPackageProtectionEnabled()){ try{ AccessController.doPrivileged( new PrivilegedExceptionAction<Void>(){ @Override public Void run() throws IOException{ response.setAppCommitted(true); response.flushBuffer(); return null; } }); } catch(PrivilegedActionException e){ Exception ex = e.getException(); if (ex instanceof IOException){ throw (IOException)ex; } } }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public Void run() throws IOException{ response.setAppCommitted(true); response.flushBuffer(); return null; }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void sendError(int sc, String msg) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendError.ise")); } response.setAppCommitted(true); response.sendError(sc, msg); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void sendError(int sc) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendError.ise")); } response.setAppCommitted(true); response.sendError(sc); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void sendRedirect(String location) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendRedirect.ise")); } response.setAppCommitted(true); response.sendRedirect(location); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public void close() throws IOException { ib.close(); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public int read() throws IOException { return ib.read(); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public int read(char[] cbuf) throws IOException { return ib.read(cbuf, 0, cbuf.length); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public int read(char[] cbuf, int off, int len) throws IOException { return ib.read(cbuf, off, len); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public long skip(long n) throws IOException { return ib.skip(n); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public boolean ready() throws IOException { return ib.ready(); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public void mark(int readAheadLimit) throws IOException { ib.mark(readAheadLimit); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public void reset() throws IOException { ib.reset(); }
// in java/org/apache/catalina/connector/CoyoteReader.java
Override public String readLine() throws IOException { if (lineBuffer == null) { lineBuffer = new char[MAX_LINE_LENGTH]; } String result = null; int pos = 0; int end = -1; int skip = -1; StringBuilder aggregator = null; while (end < 0) { mark(MAX_LINE_LENGTH); while ((pos < MAX_LINE_LENGTH) && (end < 0)) { int nRead = read(lineBuffer, pos, MAX_LINE_LENGTH - pos); if (nRead < 0) { if (pos == 0 && aggregator == null) { return null; } end = pos; skip = pos; } for (int i = pos; (i < (pos + nRead)) && (end < 0); i++) { if (lineBuffer[i] == LINE_SEP[0]) { end = i; skip = i + 1; char nextchar; if (i == (pos + nRead - 1)) { nextchar = (char) read(); } else { nextchar = lineBuffer[i+1]; } if (nextchar == LINE_SEP[1]) { skip++; } } else if (lineBuffer[i] == LINE_SEP[1]) { end = i; skip = i + 1; } } if (nRead > 0) { pos += nRead; } } if (end < 0) { if (aggregator == null) { aggregator = new StringBuilder(); } aggregator.append(lineBuffer); pos = 0; } else { reset(); skip(skip); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; try { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<Void>() { @Override public Void run() throws ServletException, IOException { internalDoFilter(req,res); return null; } } ); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public Void run() throws ServletException, IOException { internalDoFilter(req,res); return null; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
private void internalDoFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { // Call the next filter if there is one if (pos < n) { ApplicationFilterConfig filterConfig = filters[pos++]; Filter filter = null; try { filter = filterConfig.getFilter(); support.fireInstanceEvent(InstanceEvent.BEFORE_FILTER_EVENT, filter, request, response); if (request.isAsyncSupported() && "false".equalsIgnoreCase( filterConfig.getFilterDef().getAsyncSupported())) { request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE); } if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; Principal principal = ((HttpServletRequest) req).getUserPrincipal(); Object[] args = new Object[]{req, res, this}; SecurityUtil.doAsPrivilege ("doFilter", filter, classType, args, principal); } else { filter.doFilter(request, response, this); } support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response); } catch (IOException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (ServletException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (RuntimeException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); } return; } // We fell off the end of the chain -- call the servlet instance try { if (ApplicationDispatcher.WRAP_SAME_OBJECT) { lastServicedRequest.set(request); lastServicedResponse.set(response); } support.fireInstanceEvent(InstanceEvent.BEFORE_SERVICE_EVENT, servlet, request, response); if (request.isAsyncSupported() && !support.getWrapper().isAsyncSupported()) { request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE); } // Use potentially wrapped request from this point if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) { if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; Principal principal = ((HttpServletRequest) req).getUserPrincipal(); Object[] args = new Object[]{req, res}; SecurityUtil.doAsPrivilege("service", servlet, classTypeUsedInService, args, principal); } else { servlet.service(request, response); } } else { servlet.service(request, response); } support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response); } catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); } finally { if (ApplicationDispatcher.WRAP_SAME_OBJECT) { lastServicedRequest.set(null); lastServicedResponse.set(null); } } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public void doFilterEvent(CometEvent event) throws IOException, ServletException { if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; try { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<Void>() { @Override public Void run() throws ServletException, IOException { internalDoFilterEvent(ev); return null; } } ); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public Void run() throws ServletException, IOException { internalDoFilterEvent(ev); return null; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
private void internalDoFilterEvent(CometEvent event) throws IOException, ServletException { // Call the next filter if there is one if (pos < n) { ApplicationFilterConfig filterConfig = filters[pos++]; CometFilter filter = null; try { filter = (CometFilter) filterConfig.getFilter(); // FIXME: No instance listener processing for events for now /* support.fireInstanceEvent(InstanceEvent.BEFORE_FILTER_EVENT, filter, event); */ if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; Principal principal = ev.getHttpServletRequest().getUserPrincipal(); Object[] args = new Object[]{ev, this}; SecurityUtil.doAsPrivilege("doFilterEvent", filter, cometClassType, args, principal); } else { filter.doFilterEvent(event, this); } /*support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event);*/ } catch (IOException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (ServletException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (RuntimeException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); } return; } // We fell off the end of the chain -- call the servlet instance try { /* support.fireInstanceEvent(InstanceEvent.BEFORE_SERVICE_EVENT, servlet, request, response); */ if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; Principal principal = ev.getHttpServletRequest().getUserPrincipal(); Object[] args = new Object[]{ ev }; SecurityUtil.doAsPrivilege("event", servlet, classTypeUsedInEvent, args, principal); } else { ((CometProcessor) servlet).event(event); } /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response);*/ } catch (IOException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (ServletException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (RuntimeException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw new ServletException (sm.getString("filterChain.servlet"), e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Initialize local variables we may need boolean unavailable = false; Throwable throwable = null; // This should be a Request attribute... long t1=System.currentTimeMillis(); requestCount++; StandardWrapper wrapper = (StandardWrapper) getContainer(); Servlet servlet = null; Context context = (Context) wrapper.getParent(); // Check for the application being marked unavailable if (!context.getAvailable()) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardContext.isUnavailable")); unavailable = true; } // Check for the servlet being marked unavailable if (!unavailable && wrapper.isUnavailable()) { container.getLogger().info(sm.getString("standardWrapper.isUnavailable", wrapper.getName())); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } unavailable = true; } // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (UnavailableException e) { container.getLogger().error( sm.getString("standardWrapper.allocateException", wrapper.getName()), e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } } catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } // Identify if the request is Comet related now that the servlet has been allocated boolean comet = false; if (servlet instanceof CometProcessor && request.getAttribute( Globals.COMET_SUPPORTED_ATTR) == Boolean.TRUE) { comet = true; request.setComet(true); } MessageBytes requestPathMB = request.getRequestPathMB(); DispatcherType dispatcherType = DispatcherType.REQUEST; if (request.getDispatcherType()==DispatcherType.ASYNC) dispatcherType = DispatcherType.ASYNC; request.setAttribute (ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, dispatcherType); request.setAttribute (ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB); // Create the filter chain for this request ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance(); ApplicationFilterChain filterChain = factory.createFilterChain(request, wrapper, servlet); // Reset comet flag value after creating the filter chain request.setComet(false); // Call the filter chain for this request // NOTE: This also calls the servlet's service() method try { if ((servlet != null) && (filterChain != null)) { // Swallow output if needed if (context.getSwallowOutput()) { try { SystemLogHandler.startCapture(); if (request.isAsyncDispatching()) { //TODO SERVLET3 - async ((AsyncContextImpl)request.getAsyncContext()).doInternalDispatch(); } else if (comet) { filterChain.doFilterEvent(request.getEvent()); request.setComet(true); } else { filterChain.doFilter(request.getRequest(), response.getResponse()); } } finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } } } else { if (request.isAsyncDispatching()) { //TODO SERVLET3 - async ((AsyncContextImpl)request.getAsyncContext()).doInternalDispatch(); } else if (comet) { request.setComet(true); filterChain.doFilterEvent(request.getEvent()); } else { filterChain.doFilter (request.getRequest(), response.getResponse()); } } } } catch (ClientAbortException e) { throwable = e; exception(request, response, e); } catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing } catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } // Release the filter chain (if any) for this request if (filterChain != null) { if (request.isComet()) { // If this is a Comet request, then the same chain will be used for the // processing of all subsequent events. filterChain.reuse(); } else { filterChain.release(); } } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } // If this servlet has been marked permanently unavailable, // unload it and release this instance try { if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) { wrapper.unload(); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } long t2=System.currentTimeMillis(); long time=t2-t1; processingTime += time; if( time > maxTime) maxTime=time; if( time < minTime) minTime=time; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
Override public void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Initialize local variables we may need Throwable throwable = null; // This should be a Request attribute... long t1=System.currentTimeMillis(); // FIXME: Add a flag to count the total amount of events processed ? requestCount++; StandardWrapper wrapper = (StandardWrapper) getContainer(); if (wrapper == null) { // Context has been shutdown. Nothing to do here. return; } Servlet servlet = null; Context context = (Context) wrapper.getParent(); // Check for the application being marked unavailable boolean unavailable = !context.getAvailable() || wrapper.isUnavailable(); // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (UnavailableException e) { // The response is already committed, so it's not possible to do anything } catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } MessageBytes requestPathMB = request.getRequestPathMB(); request.setAttribute (ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, DispatcherType.REQUEST); request.setAttribute (ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB); // Get the current (unchanged) filter chain for this request ApplicationFilterChain filterChain = (ApplicationFilterChain) request.getFilterChain(); // Call the filter chain for this request // NOTE: This also calls the servlet's event() method try { if ((servlet != null) && (filterChain != null)) { // Swallow output if needed if (context.getSwallowOutput()) { try { SystemLogHandler.startCapture(); filterChain.doFilterEvent(request.getEvent()); } finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } } } else { filterChain.doFilterEvent(request.getEvent()); } } } catch (ClientAbortException e) { throwable = e; exception(request, response, e); } catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing } catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } // Release the filter chain (if any) for this request if (filterChain != null) { filterChain.reuse(); } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } // If this servlet has been marked permanently unavailable, // unload it and release this instance try { if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) { wrapper.unload(); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } long t2=System.currentTimeMillis(); long time=t2-t1; processingTime += time; if( time > maxTime) maxTime=time; if( time < minTime) minTime=time; }
// in java/org/apache/catalina/core/ApplicationHttpResponse.java
Override public void sendError(int sc) throws IOException { if (!included) ((HttpServletResponse) getResponse()).sendError(sc); }
// in java/org/apache/catalina/core/ApplicationHttpResponse.java
Override public void sendError(int sc, String msg) throws IOException { if (!included) ((HttpServletResponse) getResponse()).sendError(sc, msg); }
// in java/org/apache/catalina/core/ApplicationHttpResponse.java
Override public void sendRedirect(String location) throws IOException { if (!included) ((HttpServletResponse) getResponse()).sendRedirect(location); }
// in java/org/apache/catalina/core/AsyncListenerWrapper.java
public void fireOnStartAsync(AsyncEvent event) throws IOException { listener.onStartAsync(event); }
// in java/org/apache/catalina/core/AsyncListenerWrapper.java
public void fireOnComplete(AsyncEvent event) throws IOException { listener.onComplete(event); }
// in java/org/apache/catalina/core/AsyncListenerWrapper.java
public void fireOnTimeout(AsyncEvent event) throws IOException { listener.onTimeout(event); }
// in java/org/apache/catalina/core/AsyncListenerWrapper.java
public void fireOnError(AsyncEvent event) throws IOException { listener.onError(event); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
public boolean timeout() throws IOException { AtomicBoolean result = new AtomicBoolean(); request.getCoyoteRequest().action(ActionCode.ASYNC_TIMEOUT, result); if (result.get()) { boolean listenerInvoked = false; List<AsyncListenerWrapper> listenersCopy = new ArrayList<AsyncListenerWrapper>(); listenersCopy.addAll(listeners); for (AsyncListenerWrapper listener : listenersCopy) { listener.fireOnTimeout(event); listenerInvoked = true; } if (listenerInvoked) { request.getCoyoteRequest().action( ActionCode.ASYNC_IS_TIMINGOUT, result); return !result.get(); } else { // No listeners, container calls complete complete(); } } return true; }
// in java/org/apache/catalina/core/AsyncContextImpl.java
protected void doInternalDispatch() throws ServletException, IOException { if (log.isDebugEnabled()) { logDebug("intDispatch"); } try { dispatch.run(); if (!request.isAsync()) { fireOnComplete(); } } catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); } }
// in java/org/apache/catalina/core/StandardContextValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Disallow any direct access to resources under WEB-INF or META-INF MessageBytes requestPathMB = request.getRequestPathMB(); if ((requestPathMB.startsWithIgnoreCase("/META-INF/", 0)) || (requestPathMB.equalsIgnoreCase("/META-INF")) || (requestPathMB.startsWithIgnoreCase("/WEB-INF/", 0)) || (requestPathMB.equalsIgnoreCase("/WEB-INF"))) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Select the Wrapper to be used for this Request Wrapper wrapper = request.getWrapper(); if (wrapper == null || wrapper.isUnavailable()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Acknowledge the request try { response.sendAcknowledgement(); } catch (IOException ioe) { container.getLogger().error(sm.getString( "standardContextValve.acknowledgeException"), ioe); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (request.isAsyncSupported()) { request.setAsyncSupported(wrapper.getPipeline().isAsyncSupported()); } wrapper.getPipeline().getFirst().invoke(request, response); }
// in java/org/apache/catalina/core/StandardContextValve.java
Override public final void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Select the Wrapper to be used for this Request Wrapper wrapper = request.getWrapper(); wrapper.getPipeline().getFirst().event(request, response, event); }
// in java/org/apache/catalina/core/StandardEngineValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Select the Host to be used for this Request Host host = request.getHost(); if (host == null) { response.sendError (HttpServletResponse.SC_BAD_REQUEST, sm.getString("standardEngine.noHost", request.getServerName())); return; } if (request.isAsyncSupported()) { request.setAsyncSupported(host.getPipeline().isAsyncSupported()); } // Ask this Host to process this request host.getPipeline().getFirst().invoke(request, response); }
// in java/org/apache/catalina/core/StandardEngineValve.java
Override public final void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Ask this Host to process this request request.getHost().getPipeline().getFirst().event(request, response, event); }
// in java/org/apache/catalina/core/StandardHostValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Select the Context to be used for this Request Context context = request.getContext(); if (context == null) { response.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, sm.getString("standardHost.noContext")); return; } // Bind the context CL to the current thread if( context.getLoader() != null ) { // Not started - it should check for availability first // This should eventually move to Engine, it's generic. if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( context.getLoader().getClassLoader()); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader (context.getLoader().getClassLoader()); } } if (request.isAsyncSupported()) { request.setAsyncSupported(context.getPipeline().isAsyncSupported()); } // Don't fire listeners during async processing // If a request init listener throws an exception, the request is // aborted boolean asyncAtStart = request.isAsync(); if (asyncAtStart || context.fireRequestInitEvent(request)) { // Ask this Context to process this request try { context.getPipeline().getFirst().invoke(request, response); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); throwable(request, response, t); } // If the request was async at the start and an error occurred then // the async error handling will kick-in and that will fire the // request destroyed event *after* the error handling has taken // place if (!(request.isAsync() || (asyncAtStart && request.getAttribute( RequestDispatcher.ERROR_EXCEPTION) != null))) { // Protect against NPEs if context was destroyed during a long // running request. if (context.getState().isAvailable()) { // Error page processing response.setSuspended(false); Throwable t = (Throwable) request.getAttribute( RequestDispatcher.ERROR_EXCEPTION); if (t != null) { throwable(request, response, t); } else { status(request, response); } context.fireRequestDestroyEvent(request); } } } // Access a session (if present) to update last accessed time, based on a // strict interpretation of the specification if (ACCESS_SESSION) { request.getSession(false); } // Restore the context classloader if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( StandardHostValve.class.getClassLoader()); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader (StandardHostValve.class.getClassLoader()); } }
// in java/org/apache/catalina/core/StandardHostValve.java
Override public final void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Select the Context to be used for this Request Context context = request.getContext(); // Bind the context CL to the current thread if( context.getLoader() != null ) { // Not started - it should check for availability first // This should eventually move to Engine, it's generic. Thread.currentThread().setContextClassLoader (context.getLoader().getClassLoader()); } // Ask this Context to process this request context.getPipeline().getFirst().event(request, response, event); // Error page processing response.setSuspended(false); Throwable t = (Throwable) request.getAttribute( RequestDispatcher.ERROR_EXCEPTION); if (t != null) { throwable(request, response, t); } else { status(request, response); } // Access a session (if present) to update last accessed time, based on a // strict interpretation of the specification if (ACCESS_SESSION) { request.getSession(false); } // Restore the context classloader Thread.currentThread().setContextClassLoader (StandardHostValve.class.getClassLoader()); }
// in java/org/apache/catalina/core/ApplicationPart.java
Override public void delete() throws IOException { fileItem.delete(); }
// in java/org/apache/catalina/core/ApplicationPart.java
Override public InputStream getInputStream() throws IOException { return fileItem.getInputStream(); }
// in java/org/apache/catalina/core/ApplicationPart.java
Override public void write(String fileName) throws IOException { File file = new File(fileName); if (!file.isAbsolute()) { file = new File(mce.getLocation(), fileName); } try { fileItem.write(file); } catch (Exception e) { throw new IOException(e); } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
Override public Void run() throws ServletException, IOException { DispatcherType type = DispatcherType.INCLUDE; if (request.getDispatcherType()==DispatcherType.ASYNC) type = DispatcherType.ASYNC; doInclude(request,response,type); return null; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
Override public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (Globals.IS_SECURITY_ENABLED) { try { PrivilegedForward dp = new PrivilegedForward(request,response); AccessController.doPrivileged(dp); } catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; } } else { doForward(request,response); } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void doForward(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Reset any output that has been buffered, but keep headers/cookies if (response.isCommitted()) { throw new IllegalStateException (sm.getString("applicationDispatcher.forward.ise")); } try { response.resetBuffer(); } catch (IllegalStateException e) { throw e; } // Set up to handle the specified request and response State state = new State(request, response, false); if (WRAP_SAME_OBJECT) { // Check SRV.8.2 / SRV.14.2.5.1 compliance checkSameObjects(request, response); } wrapResponse(state); // Handle an HTTP named dispatcher forward if ((servletPath == null) && (pathInfo == null)) { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); HttpServletRequest hrequest = state.hrequest; wrequest.setRequestURI(hrequest.getRequestURI()); wrequest.setContextPath(hrequest.getContextPath()); wrequest.setServletPath(hrequest.getServletPath()); wrequest.setPathInfo(hrequest.getPathInfo()); wrequest.setQueryString(hrequest.getQueryString()); processRequest(request,response,state); } // Handle an HTTP path-based forward else { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); String contextPath = context.getPath(); HttpServletRequest hrequest = state.hrequest; if (hrequest.getAttribute( RequestDispatcher.FORWARD_REQUEST_URI) == null) { wrequest.setAttribute(RequestDispatcher.FORWARD_REQUEST_URI, hrequest.getRequestURI()); wrequest.setAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH, hrequest.getContextPath()); wrequest.setAttribute(RequestDispatcher.FORWARD_SERVLET_PATH, hrequest.getServletPath()); wrequest.setAttribute(RequestDispatcher.FORWARD_PATH_INFO, hrequest.getPathInfo()); wrequest.setAttribute(RequestDispatcher.FORWARD_QUERY_STRING, hrequest.getQueryString()); } wrequest.setContextPath(contextPath); wrequest.setRequestURI(requestURI); wrequest.setServletPath(servletPath); wrequest.setPathInfo(pathInfo); if (queryString != null) { wrequest.setQueryString(queryString); wrequest.setQueryParams(queryString); } processRequest(request,response,state); } // This is not a real close in order to support error processing if (wrapper.getLogger().isDebugEnabled() ) wrapper.getLogger().debug(" Disabling the response for futher output"); if (response instanceof ResponseFacade) { ((ResponseFacade) response).finish(); } else { // Servlet SRV.6.2.2. The Request/Response may have been wrapped // and may no longer be instance of RequestFacade if (wrapper.getLogger().isDebugEnabled()){ wrapper.getLogger().debug( " The Response is vehiculed using a wrapper: " + response.getClass().getName() ); } // Close anyway try { PrintWriter writer = response.getWriter(); writer.close(); } catch (IllegalStateException e) { try { ServletOutputStream stream = response.getOutputStream(); stream.close(); } catch (IllegalStateException f) { // Ignore } catch (IOException f) { // Ignore } } catch (IOException e) { // Ignore } } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void processRequest(ServletRequest request, ServletResponse response, State state) throws IOException, ServletException { DispatcherType disInt = (DispatcherType) request.getAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR); if (disInt != null) { boolean doInvoke = true; if (context.getFireRequestListenersOnForwards() && !context.fireRequestInitEvent(request)) { doInvoke = false; } if (doInvoke) { if (disInt != DispatcherType.ERROR) { state.outerRequest.setAttribute (ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); state.outerRequest.setAttribute (ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, DispatcherType.FORWARD); invoke(state.outerRequest, response, state); } else { invoke(state.outerRequest, response, state); } if (context.getFireRequestListenersOnForwards()) { context.fireRequestDestroyEvent(request); } } } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
Override public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (Globals.IS_SECURITY_ENABLED) { try { PrivilegedInclude dp = new PrivilegedInclude(request,response); AccessController.doPrivileged(dp); } catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; } } else { DispatcherType type = DispatcherType.INCLUDE; if (request.getDispatcherType()==DispatcherType.ASYNC) type = DispatcherType.ASYNC; doInclude(request,response,type); } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void doInclude(ServletRequest request, ServletResponse response, DispatcherType type) throws ServletException, IOException { // Set up to handle the specified request and response State state = new State(request, response, true); if (WRAP_SAME_OBJECT) { // Check SRV.8.2 / SRV.14.2.5.1 compliance checkSameObjects(request, response); } // Create a wrapped response to use for this request wrapResponse(state); // Handle an HTTP named dispatcher include if (name != null) { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); wrequest.setAttribute(Globals.NAMED_DISPATCHER_ATTR, name); if (servletPath != null) wrequest.setServletPath(servletPath); wrequest.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, type); wrequest.setAttribute( ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); invoke(state.outerRequest, state.outerResponse, state); } // Handle an HTTP path based include else { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); String contextPath = context.getPath(); if (requestURI != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_REQUEST_URI, requestURI); if (contextPath != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH, contextPath); if (servletPath != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH, servletPath); if (pathInfo != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_PATH_INFO, pathInfo); if (queryString != null) { wrequest.setAttribute(RequestDispatcher.INCLUDE_QUERY_STRING, queryString); wrequest.setQueryParams(queryString); } wrequest.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, type); wrequest.setAttribute( ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); invoke(state.outerRequest, state.outerResponse, state); } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void invoke(ServletRequest request, ServletResponse response, State state) throws IOException, ServletException { // Checking to see if the context classloader is the current context // classloader. If it's not, we're saving it, and setting the context // classloader to the Context classloader ClassLoader oldCCL = Thread.currentThread().getContextClassLoader(); ClassLoader contextClassLoader = context.getLoader().getClassLoader(); if (oldCCL != contextClassLoader) { Thread.currentThread().setContextClassLoader(contextClassLoader); } else { oldCCL = null; } // Initialize local variables we may need HttpServletResponse hresponse = state.hresponse; Servlet servlet = null; IOException ioException = null; ServletException servletException = null; RuntimeException runtimeException = null; boolean unavailable = false; // Check for the servlet being marked unavailable if (wrapper.isUnavailable()) { wrapper.getLogger().warn( sm.getString("applicationDispatcher.isUnavailable", wrapper.getName())); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) hresponse.setDateHeader("Retry-After", available); hresponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm .getString("applicationDispatcher.isUnavailable", wrapper .getName())); unavailable = true; } // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); servletException = e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servlet = null; } // Get the FilterChain Here ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance(); ApplicationFilterChain filterChain = factory.createFilterChain(request, wrapper,servlet); // Call the service() method for the allocated servlet instance try { support.fireInstanceEvent(InstanceEvent.BEFORE_DISPATCH_EVENT, servlet, request, response); // for includes/forwards if ((servlet != null) && (filterChain != null)) { filterChain.doFilter(request, response); } // Servlet Service Method is called by the FilterChain support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); } catch (ClientAbortException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); ioException = e; } catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); ioException = e; } catch (UnavailableException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); servletException = e; wrapper.unavailable(e); } catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause); } servletException = e; } catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); runtimeException = e; } // Release the filter chain (if any) for this request try { if (filterChain != null) filterChain.release(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e); // FIXME: Exception handling needs to be similar to what is in the StandardWrapperValue } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); } // Reset the old context class loader if (oldCCL != null) Thread.currentThread().setContextClassLoader(oldCCL); // Unwrap request/response if needed // See Bugzilla 30949 unwrapRequest(state); unwrapResponse(state); // Recycle request if necessary (also BZ 30949) recycleRequestWrapper(state); // Rethrow an exception if one was thrown by the invoked servlet if (ioException != null) throw ioException; if (servletException != null) throw servletException; if (runtimeException != null) throw runtimeException; }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
Override public Class<?> resolveClass(ObjectStreamClass classDesc) throws ClassNotFoundException, IOException { try { return Class.forName(classDesc.getName(), false, classLoader); } catch (ClassNotFoundException e) { try { // Try also the superclass because of primitive types return super.resolveClass(classDesc); } catch (ClassNotFoundException e2) { // Rethrow original exception, as it can have more information // about why the class was not found. BZ 48007 throw e; } } }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
Override protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { Class<?>[] cinterfaces = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) cinterfaces[i] = classLoader.loadClass(interfaces[i]); try { return Proxy.getProxyClass(classLoader, cinterfaces); } catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); } }
// in java/org/apache/catalina/util/XMLWriter.java
public void sendData() throws IOException { if (writer != null) { writer.write(buffer.toString()); buffer = new StringBuilder(); } }
// in java/org/apache/catalina/util/Conversions.java
public static long byteArrayToLong(byte[] input) throws IOException { if (input.length > 8) { // TODO: Better message throw new IOException(); } int shift = 0; long result = 0; for (int i = input.length - 1; i >= 0; i--) { result = result + ((input[i] & 0xFF) << shift); shift += 8; } return result; }
// in java/org/apache/catalina/util/IOTools.java
public static void flow( Reader reader, Writer writer, char[] buf ) throws IOException { int numRead; while ( (numRead = reader.read(buf) ) >= 0) { writer.write(buf, 0, numRead); } }
// in java/org/apache/catalina/util/IOTools.java
public static void flow( Reader reader, Writer writer ) throws IOException { char[] buf = new char[DEFAULT_BUFFER_SIZE]; flow( reader, writer, buf ); }
// in java/org/apache/catalina/util/IOTools.java
public static void flow( InputStream is, OutputStream os, byte[] buf ) throws IOException { int numRead; while ( (numRead = is.read(buf) ) >= 0) { os.write(buf, 0, numRead); } }
// in java/org/apache/catalina/util/IOTools.java
public static void flow( InputStream is, OutputStream os ) throws IOException { byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; flow( is, os, buf ); }
// in java/org/apache/catalina/util/ExtensionValidator.java
public static synchronized boolean validateApplication( DirContext dirContext, Context context) throws IOException { String appName = context.getName(); ArrayList<ManifestResource> appManifestResources = new ArrayList<ManifestResource>(); // If the application context is null it does not exist and // therefore is not valid if (dirContext == null) return false; // Find the Manifest for the Web Application InputStream inputStream = null; try { NamingEnumeration<Binding> wne = dirContext.listBindings("/META-INF/"); Binding binding = wne.nextElement(); if (binding.getName().toUpperCase(Locale.ENGLISH).equals("MANIFEST.MF")) { Resource resource = (Resource)dirContext.lookup ("/META-INF/" + binding.getName()); inputStream = resource.streamContent(); Manifest manifest = new Manifest(inputStream); inputStream.close(); inputStream = null; ManifestResource mre = new ManifestResource (sm.getString("extensionValidator.web-application-manifest"), manifest, ManifestResource.WAR); appManifestResources.add(mre); } } catch (NamingException nex) { // Application does not contain a MANIFEST.MF file } catch (NoSuchElementException nse) { // Application does not contain a MANIFEST.MF file } finally { if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } // Locate the Manifests for all bundled JARs NamingEnumeration<Binding> ne = null; try { ne = dirContext.listBindings("WEB-INF/lib/"); while ((ne != null) && ne.hasMoreElements()) { Binding binding = ne.nextElement(); if (!binding.getName().toLowerCase(Locale.ENGLISH).endsWith(".jar")) { continue; } Object obj = dirContext.lookup("/WEB-INF/lib/" + binding.getName()); if (!(obj instanceof Resource)) { // Probably a directory named xxx.jar - ignore it continue; } Resource resource = (Resource) obj; inputStream = resource.streamContent(); Manifest jmanifest = getManifest(inputStream); if (jmanifest != null) { ManifestResource mre = new ManifestResource( binding.getName(), jmanifest, ManifestResource.APPLICATION); appManifestResources.add(mre); } } } catch (NamingException nex) { // Jump out of the check for this application because it // has no resources } finally { if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } return validateManifestResources(appName, appManifestResources); }
// in java/org/apache/catalina/util/ExtensionValidator.java
public static void addSystemResource(File jarFile) throws IOException { Manifest manifest = getManifest(new FileInputStream(jarFile)); if (manifest != null) { ManifestResource mre = new ManifestResource(jarFile.getAbsolutePath(), manifest, ManifestResource.SYSTEM); containerManifestResources.add(mre); } }
// in java/org/apache/catalina/util/ExtensionValidator.java
private static Manifest getManifest(InputStream inStream) throws IOException { Manifest manifest = null; JarInputStream jin = null; try { jin = new JarInputStream(inStream); manifest = jin.getManifest(); jin.close(); jin = null; } finally { if (jin != null) { try { jin.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } return manifest; }
// in java/javax/servlet/jsp/tagext/SimpleTagSupport.java
Override public void doTag() throws JspException, IOException { // NOOP by default }
// in java/javax/servlet/jsp/tagext/BodyContent.java
Override public void flush() throws IOException { throw new IOException("Illegal to flush within a custom tag"); }
// in java/javax/servlet/ServletInputStream.java
public int readLine(byte[] b, int off, int len) throws IOException { if (len <= 0) { return 0; } int count = 0, c; while ((c = read()) != -1) { b[off++] = (byte) c; count++; if (c == '\n' || count == len) { break; } } return count > 0 ? count : -1; }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { return this._getHttpServletRequest().authenticate(response); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public Collection<Part> getParts() throws IllegalStateException, IOException, ServletException { return this._getHttpServletRequest().getParts(); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public Part getPart(String name) throws IllegalStateException, IOException, ServletException { return this._getHttpServletRequest().getPart(name); }
// in java/javax/servlet/http/HttpServletResponseWrapper.java
Override public void sendError(int sc, String msg) throws IOException { this._getHttpServletResponse().sendError(sc, msg); }
// in java/javax/servlet/http/HttpServletResponseWrapper.java
Override public void sendError(int sc) throws IOException { this._getHttpServletResponse().sendError(sc); }
// in java/javax/servlet/http/HttpServletResponseWrapper.java
Override public void sendRedirect(String location) throws IOException { this._getHttpServletResponse().sendRedirect(location); }
// in java/javax/servlet/http/HttpServlet.java
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_get_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { NoBodyResponse response = new NoBodyResponse(resp); doGet(req, response); response.setContentLength(); }
// in java/javax/servlet/http/HttpServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_post_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_put_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_delete_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Method[] methods = getAllDeclaredMethods(this.getClass()); boolean ALLOW_GET = false; boolean ALLOW_HEAD = false; boolean ALLOW_POST = false; boolean ALLOW_PUT = false; boolean ALLOW_DELETE = false; boolean ALLOW_TRACE = true; boolean ALLOW_OPTIONS = true; for (int i=0; i<methods.length; i++) { Method m = methods[i]; if (m.getName().equals("doGet")) { ALLOW_GET = true; ALLOW_HEAD = true; } if (m.getName().equals("doPost")) ALLOW_POST = true; if (m.getName().equals("doPut")) ALLOW_PUT = true; if (m.getName().equals("doDelete")) ALLOW_DELETE = true; } String allow = null; if (ALLOW_GET) allow=METHOD_GET; if (ALLOW_HEAD) if (allow==null) allow=METHOD_HEAD; else allow += ", " + METHOD_HEAD; if (ALLOW_POST) if (allow==null) allow=METHOD_POST; else allow += ", " + METHOD_POST; if (ALLOW_PUT) if (allow==null) allow=METHOD_PUT; else allow += ", " + METHOD_PUT; if (ALLOW_DELETE) if (allow==null) allow=METHOD_DELETE; else allow += ", " + METHOD_DELETE; if (ALLOW_TRACE) if (allow==null) allow=METHOD_TRACE; else allow += ", " + METHOD_TRACE; if (ALLOW_OPTIONS) if (allow==null) allow=METHOD_OPTIONS; else allow += ", " + METHOD_OPTIONS; resp.setHeader("Allow", allow); }
// in java/javax/servlet/http/HttpServlet.java
protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int responseLength; String CRLF = "\r\n"; StringBuilder buffer = new StringBuilder("TRACE ").append(req.getRequestURI()) .append(" ").append(req.getProtocol()); Enumeration<String> reqHeaderEnum = req.getHeaderNames(); while( reqHeaderEnum.hasMoreElements() ) { String headerName = reqHeaderEnum.nextElement(); buffer.append(CRLF).append(headerName).append(": ") .append(req.getHeader(headerName)); } buffer.append(CRLF); responseLength = buffer.length(); resp.setContentType("message/http"); resp.setContentLength(responseLength); ServletOutputStream out = resp.getOutputStream(); out.print(buffer.toString()); out.close(); return; }
// in java/javax/servlet/http/HttpServlet.java
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod(); if (method.equals(METHOD_GET)) { long lastModified = getLastModified(req); if (lastModified == -1) { // servlet doesn't support if-modified-since, no reason // to go through further expensive logic doGet(req, resp); } else { long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE); if (ifModifiedSince < (lastModified / 1000 * 1000)) { // If the servlet mod time is later, call doGet() // Round down to the nearest second for a proper compare // A ifModifiedSince of -1 will always be less maybeSetLastModified(resp, lastModified); doGet(req, resp); } else { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } } } else if (method.equals(METHOD_HEAD)) { long lastModified = getLastModified(req); maybeSetLastModified(resp, lastModified); doHead(req, resp); } else if (method.equals(METHOD_POST)) { doPost(req, resp); } else if (method.equals(METHOD_PUT)) { doPut(req, resp); } else if (method.equals(METHOD_DELETE)) { doDelete(req, resp); } else if (method.equals(METHOD_OPTIONS)) { doOptions(req,resp); } else if (method.equals(METHOD_TRACE)) { doTrace(req,resp); } else { // // Note that this means NO servlet supports whatever // method was requested, anywhere on this server. // String errMsg = lStrings.getString("http.method_not_implemented"); Object[] errArgs = new Object[1]; errArgs[0] = method; errMsg = MessageFormat.format(errMsg, errArgs); resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg); } }
// in java/javax/servlet/http/HttpServlet.java
Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request; HttpServletResponse response; try { request = (HttpServletRequest) req; response = (HttpServletResponse) res; } catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); } service(request, response); }
// in java/javax/servlet/http/HttpServlet.java
Override public ServletOutputStream getOutputStream() throws IOException { return noBody; }
// in java/javax/servlet/http/HttpServlet.java
Override public void write(byte buf[], int offset, int len) throws IOException { if (len >= 0) { contentLength += len; } else { // XXX // isn't this really an IllegalArgumentException? String msg = lStrings.getString("err.io.negativelength"); throw new IOException(msg); } }
// in java/javax/servlet/ServletResponseWrapper.java
Override public ServletOutputStream getOutputStream() throws IOException { return this.response.getOutputStream(); }
// in java/javax/servlet/ServletResponseWrapper.java
Override public PrintWriter getWriter() throws IOException { return this.response.getWriter(); }
// in java/javax/servlet/ServletResponseWrapper.java
Override public void flushBuffer() throws IOException { this.response.flushBuffer(); }
// in java/javax/servlet/ServletOutputStream.java
public void print(String s) throws IOException { if (s == null) s = "null"; int len = s.length(); for (int i = 0; i < len; i++) { char c = s.charAt(i); // // XXX NOTE: This is clearly incorrect for many strings, // but is the only consistent approach within the current // servlet framework. It must suffice until servlet output // streams properly encode their output. // if ((c & 0xff00) != 0) { // high order byte must be zero String errMsg = lStrings.getString("err.not_iso8859_1"); Object[] errArgs = new Object[1]; errArgs[0] = Character.valueOf(c); errMsg = MessageFormat.format(errMsg, errArgs); throw new CharConversionException(errMsg); } write(c); } }
// in java/javax/servlet/ServletOutputStream.java
public void print(boolean b) throws IOException { String msg; if (b) { msg = lStrings.getString("value.true"); } else { msg = lStrings.getString("value.false"); } print(msg); }
// in java/javax/servlet/ServletOutputStream.java
public void print(char c) throws IOException { print(String.valueOf(c)); }
// in java/javax/servlet/ServletOutputStream.java
public void print(int i) throws IOException { print(String.valueOf(i)); }
// in java/javax/servlet/ServletOutputStream.java
public void print(long l) throws IOException { print(String.valueOf(l)); }
// in java/javax/servlet/ServletOutputStream.java
public void print(float f) throws IOException { print(String.valueOf(f)); }
// in java/javax/servlet/ServletOutputStream.java
public void print(double d) throws IOException { print(String.valueOf(d)); }
// in java/javax/servlet/ServletOutputStream.java
public void println() throws IOException { print("\r\n"); }
// in java/javax/servlet/ServletOutputStream.java
public void println(String s) throws IOException { print(s); println(); }
// in java/javax/servlet/ServletOutputStream.java
public void println(boolean b) throws IOException { print(b); println(); }
// in java/javax/servlet/ServletOutputStream.java
public void println(char c) throws IOException { print(c); println(); }
// in java/javax/servlet/ServletOutputStream.java
public void println(int i) throws IOException { print(i); println(); }
// in java/javax/servlet/ServletOutputStream.java
public void println(long l) throws IOException { print(l); println(); }
// in java/javax/servlet/ServletOutputStream.java
public void println(float f) throws IOException { print(f); println(); }
// in java/javax/servlet/ServletOutputStream.java
public void println(double d) throws IOException { print(d); println(); }
// in java/javax/servlet/ServletRequestWrapper.java
Override public ServletInputStream getInputStream() throws IOException { return this.request.getInputStream(); }
// in java/javax/servlet/ServletRequestWrapper.java
Override public BufferedReader getReader() throws IOException { return this.request.getReader(); }
451
            
// in java/org/apache/jasper/runtime/ServletResponseWrapperInclude.java
catch (IOException ioe) { }
// in java/org/apache/jasper/runtime/BodyContentImpl.java
catch (IOException ex) { // ignore }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer.getMessage("jsp.error.flush"), ex); throw ise; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer .getMessage("jsp.error.attempt_to_clear_flushed_buffer")); ise.initCause(ex); throw ise; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch(IOException e) { buf.reset(); continue; }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
catch (IOException e) { err.jspError("jsp.error.file.not.found", path); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
catch (IOException ioe) { throw new JasperException(ioe); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException e) { log.error("Compilation error", e); }
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException ioe) {/*Ignore*/}
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException ioe) {/*Ignore*/}
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException exc) {/*Ignore*/}
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException exc) { log.error("Compilation error", exc); }
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException exc) { // Ignore }
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (IOException exc) { log.error("Compilation error", exc); }
// in java/org/apache/jasper/compiler/WebXml.java
catch (IOException e) { log.error(Localizer.getMessage( "jsp.error.stream.close.failed")); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (IOException ioe) { jspDocParser.err.jspError("jsp.error.data.file.read", path, ioe); }
// in java/org/apache/jasper/compiler/JavacErrorDetail.java
catch (IOException ioe) { // Can't read files - ignore }
// in java/org/apache/jasper/compiler/JavacErrorDetail.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/jasper/compiler/JavacErrorDetail.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JasperLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IOException e) { throw new ServletException("Could not precompile jsp: " + jspFile, e); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IOException e) { throw e; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; }
// in java/org/apache/jasper/JspCompilationContext.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage( "jsp.error.lastModified", getJspFile()), e); } result = -1; }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (IOException io) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), io); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { throw new JasperException(ioe); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { mapout = null; servletout = null; mappingout = null; }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // noting to do if it fails since we are done with it }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // since this is an optional default and a null value // for uriRoot has a non-error meaning, we can just // pass straight through }
// in java/org/apache/jasper/JspC.java
catch (IOException ex) { fis.close(); throw ex; }
// in java/org/apache/jasper/JspC.java
catch (IOException ex) { fos.close(); throw ex; }
// in java/org/apache/naming/resources/WARDirContext.java
catch (IOException e) { log.warn ("Exception closing WAR File " + base.getName(), e); }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (IOException e) { // Ignore }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (IOException e) { //Ignore }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (IOException e) { // Ignore }
// in java/org/apache/naming/resources/FileDirContext.java
catch (IOException e) { // Ignore }
// in java/org/apache/naming/resources/FileDirContext.java
catch (IOException e) { // Ignore }
// in java/org/apache/naming/resources/FileDirContext.java
catch (IOException e) { NamingException ne = new NamingException (sm.getString("resources.bindFailed", e)); ne.initCause(e); throw ne; }
// in java/org/apache/naming/resources/FileDirContext.java
catch (IOException e) { // Ignore }
// in java/org/apache/naming/resources/FileDirContext.java
catch (IOException e) { // Ignore }
// in java/org/apache/naming/resources/BaseDirContext.java
catch (IOException ioe) { log.warn(sm.getString("resources.addResourcesJarFail", url), ioe); }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (IOException e) { // Ignore }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (IOException e) { // Ignore }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IOException e) { // Ignore }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IOException e) { // Ignore }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IOException e) { // Critical problem, do something ... }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IOException e) { // Report error System.err.println("Configuration error"); e.printStackTrace(); }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/coyote/AbstractProtocol.java
catch (java.io.IOException e) { // IOExceptions are normal getLog().debug(sm.getString( "ajpprotocol.proto.ioexception.debug"), e); }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (IOException e) { error = true; break; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (IOException e) { error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (IOException e) { error = true; break; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch ( IOException x ) { //ignore }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch ( IOException x ) { // Ignore }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { // Set error flag error = true; return; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException iex) { // Ignore }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { response.setStatus(400); error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (IOException e) { error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (IOException e) { error = true; break; }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (IOException ioe) { log.warn(sm.getString("http11processor.socket.sslreneg",ioe)); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
catch ( IOException x ) { // Ignore }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
catch ( IOException x ) { //ignore }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
catch ( IOException x ) { // Ignore }
// in java/org/apache/coyote/http11/upgrade/UpgradeNioProcessor.java
catch ( IOException x ) { //ignore }
// in java/org/apache/coyote/http11/filters/GzipOutputFilter.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Ignored exception while flushing gzip filter", e); } }
// in java/org/apache/coyote/http11/filters/BufferedInputFilter.java
catch(IOException ioe) { // No need for i18n - this isn't going to get logged anywhere throw new IllegalStateException( "Request body too large for buffer"); }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
catch (IOException ignore) { // If our write failed, then trailer write in finish() will fail // with IOException as well, but it will leave Deflater in more // consistent state. }
// in java/org/apache/coyote/http11/filters/FlushableGZIPOutputStream.java
catch (IOException ignored) { // Ignore. As OutputStream#close() says, the contract of close() // is to close the stream. It does not matter much if the // stream is not writable any more. }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { // Set error flag error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { // Set error flag error = true; response.setErrorException(e); }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), e); } error = true; break; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (IOException e) { error = true; }
// in java/org/apache/coyote/http11/InternalNioOutputBuffer.java
catch ( IOException x ) { //ignore }
// in java/org/apache/coyote/spdy/SpdyAprNpnHandler.java
catch (IOException e) { }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (IOException e) { e.printStackTrace(); // Set error flag error = true; return; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (IOException e) { // Set error flag e.printStackTrace(); error = true; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (IOException iex) { // Ignore }
// in java/org/apache/coyote/spdy/SpdyProxyProtocol.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (IOException e) { apr.reset(); throw e; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (IOException e) { throw e; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException e) { log.log(Level.SEVERE, this + " error ", e); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException t) { reset(); // also sets status ERROR if (handler instanceof AprSocketContext.NonBlockingPollHandler) { ((AprSocketContext.NonBlockingPollHandler) handler).process(this, false, false, true); } notifyError(t, false); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException e) { throw e; }
// in java/org/apache/tomcat/buildutil/CheckEol.java
catch (IOException e) { throw new BuildException("Could not check file '" + file.getAbsolutePath() + "'", e); }
// in java/org/apache/tomcat/buildutil/Txt2Html.java
catch( IOException e ) { throw new BuildException( "Could not convert '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath() + "'", e ); }
// in java/org/apache/tomcat/spdy/SpdyStream.java
catch (IOException e) { e.printStackTrace(); // TODO: send rst, error processing the stream. }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (IOException ex) { abort("Compress error"); return false; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (IOException e) { // connection closed - abort all streams e.printStackTrace(); onClose(); return false; }
// in java/org/apache/tomcat/spdy/NetSupportOpenSSL.java
catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); ch.reset(); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (IOException ex) { ex.printStackTrace(); throw ex; }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (IOException ex) { if (running) { ex.printStackTrace(); } running = false; }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
catch (IOException x) { throw x; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw ioe; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException x) { if (running) { log.error(sm.getString("endpoint.accept.fail"), x); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("", ioe); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("", ioe); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { log.error(sm.getString( "endpoint.nio.selectorCloseFail"), ioe); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { log.error(sm.getString( "endpoint.nio.selectorCloseFail"), ioe); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( IOException x ) { if ( log.isDebugEnabled() ) log.debug("Unable to complete sendfile request:", x); cancelledKey(sk,SocketStatus.ERROR); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( IOException x ) { handshake = -1; if ( log.isDebugEnabled() ) log.debug("Error during SSL handshake",x);
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (IOException ioe) { countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw ioe; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (IOException x) { if (running) { log.error(sm.getString("endpoint.accept.fail"), x); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (IOException e) { // Ignore }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (IOException e) { // Ignore }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch (IOException e) { // ignore - presumably the timeout }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { Throwable cause = ioe.getCause(); if (cause instanceof UnrecoverableKeyException) { // Log a warning we had a password issue log.warn(sm.getString("jsse.invalid_truststore_password"), cause); // Re-try trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, null); } else { // Something else went wrong - re-throw throw ioe; } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { // May be expected when working with a trust store // Re-throw. Caller will catch and log as required throw ioe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { // Do nothing }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(IOException iex) { throw iex; }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
catch (NoSuchElementException x ) { try { synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 s = Selector.open(); } } catch (IOException iox) { } }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
catch (IOException iox) { }
// in java/org/apache/tomcat/util/http/parser/HttpParserTokenManager.java
catch(java.io.IOException e) { return pos + 1; }
// in java/org/apache/tomcat/util/http/parser/HttpParserTokenManager.java
catch(java.io.IOException e) { return curPos; }
// in java/org/apache/tomcat/util/http/parser/HttpParserTokenManager.java
catch(java.io.IOException e) { jjmatchedKind = 0; matchedToken = jjFillToken(); return matchedToken; }
// in java/org/apache/tomcat/util/http/parser/HttpParserTokenManager.java
catch (java.io.IOException e1) { EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException e) { // Can't happen, as decodedQuery can't overflow e.printStackTrace(); }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException ioe) { // Should never happen... log.error(sm.getString("parameters.copyFail"), ioe); }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IOException e) { parseFailed = true; decodeFailCount++; if (decodeFailCount == 1 || log.isDebugEnabled()) { if (log.isDebugEnabled()) { log.debug(sm.getString("parameters.decodeFail.debug", origName.toString(), origValue.toString()), e); } else if (log.isInfoEnabled()) { UserDataHelper.Mode logMode = userDataLog.getNextMode(); if (logMode != null) { String message = sm.getString( "parameters.decodeFail.info", tmpName.toString(), tmpValue.toString()); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString("parameters.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } } } }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); }
// in java/org/apache/tomcat/util/http/fileupload/IOUtils.java
catch (IOException ioe) { // ignore }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
catch (IOException e) { fileData = null; }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
catch (IOException e) { // ignore }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
catch (IOException e) { // ignore }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
catch (IOException e) { // ignore }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new FileUploadException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/http/fileupload/FileDeleteStrategy.java
catch (IOException ex) { return false; }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
catch (IOException ioe) { exception = ioe; }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
catch (IOException ioe) { exception = ioe; }
// in java/org/apache/tomcat/util/http/fileupload/util/Streams.java
catch (IOException ioe) { /* Ignore me */ }
// in java/org/apache/tomcat/util/http/fileupload/util/Streams.java
catch (IOException ioe) { /* Ignore me */ }
// in java/org/apache/tomcat/util/http/fileupload/ThresholdingOutputStream.java
catch (IOException ignored) { // ignore }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
catch( IOException ex) { if(log.isDebugEnabled()) { log.debug("B2CConverter: Reseting the converter " + ex.toString()); } reset(); throw ex; }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
catch(IOException ioe){ }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
catch (IOException e) { log.warn(sm.getString("c2bConverter.recycleFailed"), e); try { init(); } catch (IOException ignore) { // Should never happen since this means encoding is invalid and // in that case, the constructor will have failed. } }
// in java/org/apache/tomcat/util/buf/C2BConverter.java
catch (IOException ignore) { // Should never happen since this means encoding is invalid and // in that case, the constructor will have failed. }
// in java/org/apache/tomcat/util/buf/UEncoder.java
catch (IOException iex) { }
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
catch (IOException e) { log.warn(sm.getString("jarScan.webinflibFail", url), e); }
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
catch (IOException ioe) { log.warn(sm.getString( "jarScan.classloaderFail",urls[i]), ioe); }
// in java/org/apache/tomcat/util/scan/UrlJar.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/tomcat/util/scan/UrlJar.java
catch (IOException ioe) { entry = null; }
// in java/org/apache/tomcat/util/scan/FileUrlJar.java
catch (IOException e) { // Ignore }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (IOException e) { System.out.println(buf.toString()); e.printStackTrace(); throw new ClassFormatException("Byte code error: " + e, e); }
// in java/org/apache/el/parser/SimpleCharStream.java
catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_0(0, active0); return 1; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { return curPos; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(0, active0); return 1; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(1, active0); return 2; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(2, active0); return 3; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(3, active0); return 4; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(4, active0); return 5; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(5, active0); return 6; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(6, active0); return 7; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(7, active0); return 8; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjStopStringLiteralDfa_1(8, active0); return 9; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { return pos + 1; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { return curPos; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch(java.io.IOException e) { jjmatchedKind = 0; matchedToken = jjFillToken(); return matchedToken; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch (java.io.IOException e1) { continue EOFLoop; }
// in java/org/apache/el/parser/ELParserTokenManager.java
catch (java.io.IOException e1) { EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { props = null; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.contextClose"), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString( "contextConfig.fixDocBase", context.getName()), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { globalTimeStamp = -1; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { hostTimeStamp = -1; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException ioe) { log.error(sm.getString( "contextConfig.servletContainerInitializerFail", url, context.getName())); ok = false; return; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException ioe) { log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName())); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.baseError"), e); return null; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamJar", entryName, url),e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.jarFile", url), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamJndi", url),e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.jndiUrl", url), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamFile", file.getAbsolutePath()),e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.webxmlFail", resourcePath, descriptor.getTaglibURI()), ioe); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.webinfFail", path), ioe); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.dirFail", fileList[i].getAbsolutePath()), ioe); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/startup/TldConfig.java
catch (IOException ioe) { log.warn(sm.getString("tldConfig.jarFail", jarConn.getURL()), ioe); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { return file; }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException ioe) { return false; }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { /* Ignore */ }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException ioe) { // Ignore; }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { /* Ignore */ }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { /* Ignore */ }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e){ // Ignore }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e){ // Ignore }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { log.warn(sm.getString ("hostConfig.canonicalizing", app.name), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { log.warn(sm.getString ("hostConfig.canonicalizing", app.name), e); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (IOException e) { log.warn(sm.getString ("hostConfig.canonicalizing", app.name), e); }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { throw e; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { throw e; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { log.error(sm.getString ("expandWar.copy", fileSrc, fileDest), e); result = false; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/startup/Catalina.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/startup/Catalina.java
catch (IOException e) { log.error("Catalina.stop: ", e); System.exit(1); }
// in java/org/apache/catalina/startup/Catalina.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/startup/Catalina.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/startup/Catalina.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/startup/PasswdUserDatabase.java
catch (Exception e) { if (reader != null) { try { reader.close(); } catch (IOException f) { // Ignore } reader = null; } }
// in java/org/apache/catalina/startup/PasswdUserDatabase.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (IOException ioe) { homeFile = f.getAbsoluteFile(); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (IOException ioe) { homeFile = f.getAbsoluteFile(); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (IOException ioe) { homeFile = f.getAbsoluteFile(); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (IOException ioe) { baseFile = baseFile.getAbsoluteFile(); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (IOException e) { baseFile = baseFile.getAbsoluteFile(); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (IOException e) { homeFile = homeFile.getAbsoluteFile(); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { canonicalLoaderDir = null; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to close JAR", e); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { log.warn(sm.getString( "webappClassLoader.jdbcRemoveStreamError", contextName), ioe); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to open JAR", e); } return false; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { return null; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { return null; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { throw new IllegalArgumentException( sm.getString("webappClassLoader.validationErrorJarPath", jarEntry2.getName()), ioe); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { log.error(sm.getString("webappClassLoader.readError", name), e); return null; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { /* Ignore */}
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (IOException e) { return false; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (IOException e) { return false; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (IOException e) { // Should never happen containerLog.error("Could not append password bytes to chunk: ", e); }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (IOException e) { throw new LoginException(e.toString()); }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (IOException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.createServerFailed", serverName), e); }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (IOException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.destroyServerFailed", serverName),e); }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
catch (IOException e) { if (writer != null) { writer.close(); } fileNew.delete(); throw e; }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/ant/AbstractCatalinaTask.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/ant/DeployTask.java
catch (IOException e) { throw new BuildException(e); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (IOException e) { throw new BuildException(e); }
// in java/org/apache/catalina/ant/BaseRedirectorHelperTask.java
catch (IOException ioe) { log("Error closing redirector: " + ioe.getMessage(), Project.MSG_ERR); }
// in java/org/apache/catalina/websocket/StreamInbound.java
catch (IOException ioe) { // Given something must have gone to reach this point, this // might not work but try it anyway. closeOutboundConnection(Constants.STATUS_PROTOCOL_ERROR, null); return SocketState.CLOSED; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (IOException e) { appBaseFile = file; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (IOException e) { writer.println(smClient.getString( "hostManagerServlet.managerXml")); return; }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { if (war.exists() && !war.delete()) { writer.println( smClient.getString("managerServlet.deleteFail", war)); } throw e; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { e.printStackTrace(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { e.printStackTrace(); result = false; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
catch ( IOException x ) { log.error("Unable to compress byte contents"); throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
catch ( IOException x ) { log.error("Unable to decompress byte contents",x); }
// in java/org/apache/catalina/tribes/io/ObjectReader.java
catch ( IOException x ) { //unable to get buffer size log.warn("Unable to retrieve the socket receiver buffer size, setting to default 43800 bytes."); this.buffer = new XByteBuffer(43800,true); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { SenderState.getSenderState(getDestination()).setSuspect(); exception = x; if (log.isTraceEnabled()) log.trace(sm.getString("IDataSender.send.again", getAddress().getHostAddress(),new Integer(getPort())),x); while ( getAttempt()<getMaxRetryAttempts() ) { try { setAttempt(getAttempt()+1); // second try with fresh connection pushMessage(data, true,waitForAck); exception = null; } catch (IOException xx) { exception = xx; closeSocket(); } } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException xx) { exception = xx; closeSocket(); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { // Ignore }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
// in java/org/apache/catalina/tribes/transport/bio/BioReplicationTask.java
catch ( java.io.IOException x ) { log.warn("Unable to send ACK back through channel, channel disconnected?: "+x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch (IOException ioe) { log.error("Failed bind replication listener on address:"+ host, ioe); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind server socket to:" + addr + " throwing error."); throw x; } port++; }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
catch ( IOException x ) { throw new RuntimeException("Unable to open NIO selector.",x); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( IOException io ) { if ( x==null ) x = new ChannelException(io); x.addFaultyMember(senders[i].getDestination(),io); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( IOException io ) { if ( x==null ) x = new ChannelException(io); x.addFaultyMember(senders[i].getDestination(),io); }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( IOException x ) { sender.disconnect(); sender.reset(); //nioSenders.remove(entry.getKey()); i.remove(); result = true; }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( java.io.IOException x ) { log.warn("Unable to send ACK back through channel, channel disconnected?: "+x.getMessage()); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (IOException e) { if (log.isDebugEnabled()) log.debug("", e); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (IOException e) { if (log.isDebugEnabled()) log.debug("", e); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch ( IOException ignore ){ if (log.isWarnEnabled()) { log.warn("Unable to cleanup on selector close.",ignore); } }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { log.error("Unable to diff object. Will replicate the entire object instead.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { log.error("Unable to transfer LazyReplicatedMap state.", x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x ) { log.error("Unable to deserialize MapMessage.",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { log.error("Unable to deserialize MapMessage.", x); return; }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( IOException x ) { throw new RuntimeException(x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { throw new RuntimeException(x); }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
catch ( IOException x ) { throw new RuntimeException("Unable to parse hostname.",x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( IOException x ) { throw new IllegalArgumentException(x); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (IOException iox) { log.error("Unable to join multicast group, make sure your system has multicasting enabled."); throw iox; }
// in java/org/apache/catalina/tribes/membership/StaticMember.java
catch (IOException x) { throw new RuntimeException(x);}
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException f) { // ignored }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { error = true; log.error(sm.getString("standardManager.unloading.ioe", e), e); throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.unloading.ioe", e), e); try { oos.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/StoreBase.java
catch (IOException e) { manager.getContainer().getLogger().error("Error getting keys", e); return; }
// in java/org/apache/catalina/session/StoreBase.java
catch (IOException ioe) { // Ignore - session will be expired }
// in java/org/apache/catalina/session/StoreBase.java
catch (Exception e) { manager.getContainer().getLogger().error("Session: "+keys[i]+"; ", e); try { remove(keys[i]); } catch (IOException e2) { manager.getContainer().getLogger().error("Error removing key", e2); } }
// in java/org/apache/catalina/session/StoreBase.java
catch (IOException e2) { manager.getContainer().getLogger().error("Error removing key", e2); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/session/JDBCStore.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException e) { if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException e) { if (fos != null) { try { fos.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("checking isLoaded for id, " + id + ", "+e.getMessage(), e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("Exception clearing the Store: " + e, e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("Can't load sessions from store, " + e.getMessage(), e); return; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("Failed load session from store, " + e.getMessage(), e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error("Exception removing session " + e.getMessage(), e); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { // This is logged in writeSession() }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error(sm.getString ("persistentManager.serializeError", session.getIdInternal(), e)); throw e; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { // This is logged in writeSession() }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { // This is logged in writeSession() }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { // This is logged in writeSession() }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (IOException e) { container.getLogger().warn(sm.getString( "cometConnectionManagerValve.event"), e); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (IOException e) { writer = null; currentLogFile = null; log.error(sm.getString("accessLogValve.openFail", pathname), e); }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
catch (IOException e) { log.error("parse error", e); return null; }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (IOException ioe) { log.debug("Request body too big to save during authentication"); response.sendError(HttpServletResponse.SC_FORBIDDEN, sm.getString("authenticator.requestBodyTooBig")); return (false); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IOException e) { exception = e; len = -1; break; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IOException e) { exception = e; len = -1; break; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IOException e) { return e; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IOException e) { exception = e; len = -1; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (IOException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (IOException e) { lockRequestType = LOCK_REFRESH; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException ioe) { // delete in case file is corrupted if (f.exists()) { if (!f.delete() && debug >= 2) { log("expandCGIScript: failed to delete '" + f.getAbsolutePath() + "'"); } } }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException e){ log ("Caught exception " + e); throw e; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException ioe) { log ("Exception closing header reader " + ioe); }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException ioe) { log ("Exception closing output stream " + ioe); }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException e) { log("sendToLog error", e) ; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException ce) { log("sendToLog error", ce) ; }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (IOException e) { }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (IOException e) { }
// in java/org/apache/catalina/ha/backend/TcpSender.java
catch (IOException e) { }
// in java/org/apache/catalina/ha/session/JvmRouteBinderValve.java
catch (IOException e) { // Hups! }
// in java/org/apache/catalina/ha/session/JvmRouteBinderValve.java
catch (IOException e) { // Hups! }
// in java/org/apache/catalina/ha/session/JvmRouteSessionIDBinderListener.java
catch (IOException e) { log.error(e); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.unableSerializeSessionID", newSessionID), e); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.loading.ioe", e), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException f) { // ignored }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.unloading.ioe", e), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException x) { log.error(sm.getString("deltaManager.createMessage.unableCreateDeltaRequest",sessionId), x); return null; }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOnListener.java
catch (IOException io) { log.error("Session doesn't exist:" + io); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOnListener.java
catch (IOException io) { log.error("Session doesn't exist:" + io); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (java.io.IOException x) { log.error(sm.getString("farmWarDeployer.msgIoe"), x); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
catch (IOException e) { log.error(sm.getString("farmWarDeployer.fileCopyFail", from, to), e); return false; }
// in java/org/apache/catalina/ssi/SSIInclude.java
catch (IOException e) { ssiMediator.log("#include--Couldn't include file: " + substitutedValue, e); writer.write(configErrMsg); }
// in java/org/apache/catalina/ssi/SSIFlastmod.java
catch (IOException e) { ssiMediator.log( "#flastmod--Couldn't get last modified for file: " + substitutedValue, e); writer.write(configErrMsg); }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
catch (IOException e) { // Ignore this. It will always fail for non-file based includes }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
catch (IOException e) { // Ignore this. It will always fail for non-file based includes }
// in java/org/apache/catalina/ssi/SSIExec.java
catch (IOException e) { if (!foundProgram) { //apache doesn't output an error message if it can't find // a program } ssiMediator.log("Couldn't exec file: " + substitutedValue, e); }
// in java/org/apache/catalina/ssi/SSIFsize.java
catch (IOException e) { ssiMediator.log("#fsize--Couldn't get size for file: " + substitutedValue, e); writer.write(configErrMsg); }
// in java/org/apache/catalina/connector/OutputBuffer.java
catch (IOException e) { // An IOException on a write is almost always due to // the remote client aborting the request. Wrap this // so that it can be handled better by the error dispatcher. throw new ClientAbortException(e); }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { throw new SecurityException(sm.getString( "coyoteRequest.sendfileNotCanonical", value), e); }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Can't find the session }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/connector/Request.java
catch (IOException ioe) { partsParseException = ioe; return; }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { session = null; }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Client disconnect if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { // Client disconnect or chunkedPostTooLarge error if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; }
// in java/org/apache/catalina/connector/Response.java
catch (IOException ioe) { // Ignore - the client has probably closed the connection }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { throw new IllegalArgumentException(cc.toString(), e); }
// in java/org/apache/catalina/connector/CoyoteWriter.java
catch (IOException e) { error = true; }
// in java/org/apache/catalina/connector/CoyoteWriter.java
catch (IOException ex ) { // Ignore }
// in java/org/apache/catalina/connector/CoyoteWriter.java
catch (IOException e) { error = true; }
// in java/org/apache/catalina/connector/CoyoteWriter.java
catch (IOException e) { error = true; }
// in java/org/apache/catalina/connector/CoyoteWriter.java
catch (IOException e) { error = true; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException e) { error = true; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException e) { success = false; // Ignore }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException ioe) { res.setStatus(400); res.setMessage("Invalid URI: " + ioe.getMessage()); connector.getService().getContainer().logAccess( request, response, 0, true); return false; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException e) { // Ignore log.error("Invalid URI encoding; using HTTP default"); connector.setURIEncoding(null); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (IOException e) { log.error("Invalid URI character encoding; trying ascii"); cc.recycle(); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardHost.java
catch (IOException ioe) { // Ignore }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedServletsResource"), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedListenersResources"), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedServletsResources"), e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IOException ioe) { log.warn("onComplete() failed for listener of type [" + listener.getClass().getName() + "]", ioe); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IOException ioe) { log.warn("onStartAsync() failed for listener of type [" + listener.getClass().getName() + "]", ioe); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IOException ioe) { log.warn("onStartAsync() failed for listener of type [" + listener.getClass().getName() + "]", ioe); }
// in java/org/apache/catalina/core/ApplicationHttpRequest.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/core/ApplicationHttpRequest.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/core/StandardContextValve.java
catch (IOException ioe) { container.getLogger().error(sm.getString( "standardContextValve.acknowledgeException"), ioe); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { // Ignored }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { log.error("StandardServer.await: create[" + address + ":" + port + "]: ", e); return; }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { if (stopAwait) { // Wait was aborted with socket.close() break; } log.error("StandardServer.await: accept: ", e); break; }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { log.warn("StandardServer.await: read: ", e); ch = -1; }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/core/StandardServer.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (IOException e) { container.getLogger().warn("Exception Processing " + errorPage, e); }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (IOException e) { container.getLogger().warn("Exception Processing " + errorPage, e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException e) { log.warn(sm.getString("standardContext.workPath", getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException ioe) { log.error("Error in dependencyCheck", ioe); dependencyCheck = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException e) { log.warn(sm.getString("standardContext.workCreateException", workDir, catalinaHomePath, getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException e) { return ""; }
// in java/org/apache/catalina/core/StandardContext.java
catch (IOException ioe) {/*Ignore*/}
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IllegalStateException e) { try { ServletOutputStream stream = response.getOutputStream(); stream.close(); } catch (IllegalStateException f) { // Ignore } catch (IOException f) { // Ignore } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IOException f) { // Ignore }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IOException e) { // Ignore }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); ioException = e; }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IOException e) { log.error(sm.getString( "jreLeakListener.jarUrlConnCacheFail"), e); }
// in java/org/apache/catalina/util/URLEncoder.java
catch(IOException e) { buf.reset(); continue; }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (IOException e) { log.error(sm.getString ("extensionValidator.failload", item), e); }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (IOException e) { log.error (sm.getString ("extensionValidator.failload", files[i]), e); }
// in java/javax/servlet/jsp/tagext/BodyContent.java
catch (IOException ex) { // TODO -- clean this one up. throw new Error("internal error!;"); }
// in java/javax/servlet/http/HttpUtils.java
catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); }
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { throw new ELException("Failed to read " + SERVICE_RESOURCE_NAME, e); }
// in java/javax/el/ExpressionFactory.java
catch (IOException ioe) {/*Ignore*/}
// in java/javax/el/ExpressionFactory.java
catch (IOException ioe) {/*Ignore*/}
// in java/javax/el/ExpressionFactory.java
catch (IOException ioe) {/*Ignore*/}
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { throw new ELException("Failed to read " + PROPERTY_FILE, e); }
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { // Ignore }
81
            
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer.getMessage("jsp.error.flush"), ex); throw ise; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer .getMessage("jsp.error.attempt_to_clear_flushed_buffer")); ise.initCause(ex); throw ise; }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
catch (IOException ioe) { throw new JasperException(ioe); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IOException e) { throw new ServletException("Could not precompile jsp: " + jspFile, e); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IOException e) { throw e; }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (IOException io) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), io); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { throw new JasperException(ioe); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ex) { fis.close(); throw ex; }
// in java/org/apache/jasper/JspC.java
catch (IOException ex) { fos.close(); throw ex; }
// in java/org/apache/naming/resources/FileDirContext.java
catch (IOException e) { NamingException ne = new NamingException (sm.getString("resources.bindFailed", e)); ne.initCause(e); throw ne; }
// in java/org/apache/coyote/http11/filters/BufferedInputFilter.java
catch(IOException ioe) { // No need for i18n - this isn't going to get logged anywhere throw new IllegalStateException( "Request body too large for buffer"); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (IOException e) { apr.reset(); throw e; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (IOException e) { throw e; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (IOException e) { throw e; }
// in java/org/apache/tomcat/buildutil/CheckEol.java
catch (IOException e) { throw new BuildException("Could not check file '" + file.getAbsolutePath() + "'", e); }
// in java/org/apache/tomcat/buildutil/Txt2Html.java
catch( IOException e ) { throw new BuildException( "Could not convert '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath() + "'", e ); }
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (IOException ex) { ex.printStackTrace(); throw ex; }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
catch (IOException x) { throw x; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (IOException ioe) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw ioe; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (IOException ioe) { countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw ioe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { Throwable cause = ioe.getCause(); if (cause instanceof UnrecoverableKeyException) { // Log a warning we had a password issue log.warn(sm.getString("jsse.invalid_truststore_password"), cause); // Re-try trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, null); } else { // Something else went wrong - re-throw throw ioe; } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (IOException ioe) { // May be expected when working with a trust store // Re-throw. Caller will catch and log as required throw ioe; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch(IOException iex) { throw iex; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new FileUploadException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
catch( IOException ex) { if(log.isDebugEnabled()) { log.debug("B2CConverter: Reseting the converter " + ex.toString()); } reset(); throw ex; }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (IOException e) { System.out.println(buf.toString()); e.printStackTrace(); throw new ClassFormatException("Byte code error: " + e, e); }
// in java/org/apache/el/parser/SimpleCharStream.java
catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { throw e; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (IOException e) { throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { throw new IllegalArgumentException( sm.getString("webappClassLoader.validationErrorJarPath", jarEntry2.getName()), ioe); }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (IOException e) { throw new LoginException(e.toString()); }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
catch (IOException e) { if (writer != null) { writer.close(); } fileNew.delete(); throw e; }
// in java/org/apache/catalina/ant/DeployTask.java
catch (IOException e) { throw new BuildException(e); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (IOException e) { throw new BuildException(e); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (IOException e) { if (war.exists() && !war.delete()) { writer.println( smClient.getString("managerServlet.deleteFail", war)); } throw e; }
// in java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
catch ( IOException x ) { log.error("Unable to compress byte contents"); throw new ChannelException(x); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException ex1) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isDebugEnabled()) log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), new Integer(getPort()),new Long(0)), ex1); throw (ex1); }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind server socket to:" + addr + " throwing error."); throw x; } port++; }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
catch ( IOException x ) { throw new RuntimeException("Unable to open NIO selector.",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( IOException x ) { throw new RuntimeException(x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { throw new RuntimeException(x); }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
catch ( IOException x ) { throw new RuntimeException("Unable to parse hostname.",x); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( IOException x ) { throw new IllegalArgumentException(x); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (IOException iox) { log.error("Unable to join multicast group, make sure your system has multicasting enabled."); throw iox; }
// in java/org/apache/catalina/tribes/membership/StaticMember.java
catch (IOException x) { throw new RuntimeException(x);}
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (ClassNotFoundException e) { log.error(sm.getString("standardManager.loading.cnfe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.loading.ioe", e), e); try { ois.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { error = true; log.error(sm.getString("standardManager.unloading.ioe", e), e); throw e; }
// in java/org/apache/catalina/session/StandardManager.java
catch (IOException e) { log.error(sm.getString("standardManager.unloading.ioe", e), e); try { oos.close(); } catch (IOException f) { // Ignore } throw e; }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException e) { if (bis != null) { try { bis.close(); } catch (IOException f) { // Ignore } } if (fis != null) { try { fis.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/FileStore.java
catch (IOException e) { if (fos != null) { try { fos.close(); } catch (IOException f) { // Ignore } } throw e; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (IOException e) { log.error(sm.getString ("persistentManager.serializeError", session.getIdInternal(), e)); throw e; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IOException e){ log ("Caught exception " + e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.loading.ioe", e), e); throw e; }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (IOException e) { log.error(sm.getString("deltaManager.unloading.ioe", e), e); throw e; }
// in java/org/apache/catalina/connector/OutputBuffer.java
catch (IOException e) { // An IOException on a write is almost always due to // the remote client aborting the request. Wrap this // so that it can be handled better by the error dispatcher. throw new ClientAbortException(e); }
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { throw new SecurityException(sm.getString( "coyoteRequest.sendfileNotCanonical", value), e); }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { throw new IllegalArgumentException(cc.toString(), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (IOException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; }
// in java/javax/servlet/jsp/tagext/BodyContent.java
catch (IOException ex) { // TODO -- clean this one up. throw new Error("internal error!;"); }
// in java/javax/servlet/http/HttpUtils.java
catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); }
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { throw new ELException("Failed to read " + SERVICE_RESOURCE_NAME, e); }
// in java/javax/el/ExpressionFactory.java
catch (IOException e) { throw new ELException("Failed to read " + PROPERTY_FILE, e); }
17
checked (Domain) IOFileUploadException
public static class IOFileUploadException extends FileUploadException {
        /** The exceptions UID, for serializing an instance.
         */
        private static final long serialVersionUID = 1749796615868477269L;
        /** The exceptions cause; we overwrite the parent
         * classes field, which is available since Java
         * 1.4 only.
         */
        private final IOException cause;

        /**
         * Creates a new instance with the given cause.
         * @param pMsg The detail message.
         * @param pException The exceptions cause.
         */
        public IOFileUploadException(String pMsg, IOException pException) {
            super(pMsg);
            cause = pException;
        }

        /**
         * Returns the exceptions cause.
         * @return The exceptions cause, if any, or null.
         */
        @Override
        public Throwable getCause() {
            return cause;
        }
    }
1
            
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
public List<FileItem> parseRequest(RequestContext ctx) throws FileUploadException { List<FileItem> items = new ArrayList<FileItem>(); boolean successful = false; try { FileItemIterator iter = getItemIterator(ctx); FileItemFactory fac = getFileItemFactory(); if (fac == null) { throw new NullPointerException( "No FileItemFactory has been set."); } while (iter.hasNext()) { final FileItemStream item = iter.next(); // Don't use getName() here to prevent an InvalidFileNameException. final String fileName = ((org.apache.tomcat.util.http.fileupload.FileUploadBase.FileItemIteratorImpl.FileItemStreamImpl) item).name; FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), fileName); items.add(fileItem); try { Streams.copy(item.openStream(), fileItem.getOutputStream(), true); } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); } if (fileItem instanceof FileItemHeadersSupport) { final FileItemHeaders fih = item.getHeaders(); ((FileItemHeadersSupport) fileItem).setHeaders(fih); } } successful = true; return items; } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new FileUploadException(e.getMessage(), e); } finally { if (!successful) { for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) { FileItem fileItem = iterator.next(); try { fileItem.delete(); } catch (Exception e) { // ignore it } } } } }
1
            
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); }
0 0 0 0
unknown (Lib) IllegalAccessError 1
            
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
Override protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { ClassLoader latestLoader = (classLoaders!=null && classLoaders.length==0)?null:classLoaders[0]; ClassLoader nonPublicLoader = null; boolean hasNonPublicInterface = false; // define proxy in class loader of non-public interface(s), if any Class<?>[] classObjs = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { Class<?> cl = this.resolveClass(interfaces[i]); if (latestLoader==null) latestLoader = cl.getClassLoader(); if ((cl.getModifiers() & Modifier.PUBLIC) == 0) { if (hasNonPublicInterface) { if (nonPublicLoader != cl.getClassLoader()) { throw new IllegalAccessError( "conflicting non-public interface class loaders"); } } else { nonPublicLoader = cl.getClassLoader(); hasNonPublicInterface = true; } } classObjs[i] = cl; } try { return Proxy.getProxyClass(hasNonPublicInterface ? nonPublicLoader : latestLoader, classObjs); } catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); } }
0 0 0 0 0
unknown (Lib) IllegalAccessException 0 0 19
            
// in java/org/apache/catalina/loader/WebappClassLoader.java
private void checkThreadLocalMapForLeaks(Object map, Field internalTableField) throws IllegalAccessException, NoSuchFieldException { if (map != null) { Object[] table = (Object[]) internalTableField.get(map); if (table != null) { for (int j =0; j < table.length; j++) { if (table[j] != null) { boolean potentialLeak = false; // Check the key Object key = ((Reference<?>) table[j]).get(); if (this.equals(key) || loadedByThisOrChild(key)) { potentialLeak = true; } // Check the value Field valueField = table[j].getClass().getDeclaredField("value"); valueField.setAccessible(true); Object value = valueField.get(table[j]); if (this.equals(value) || loadedByThisOrChild(value)) { potentialLeak = true; } if (potentialLeak) { Object[] args = new Object[5]; args[0] = contextName; if (key != null) { args[1] = getPrettyClassName(key.getClass()); try { args[2] = key.toString(); } catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badKey", args[1]), e); args[2] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); } } if (value != null) { args[3] = getPrettyClassName(value.getClass()); try { args[4] = value.toString(); } catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badValue", args[3]), e); args[4] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); } } if (value == null) { if (log.isDebugEnabled()) { log.debug(sm.getString( "webappClassLoader.checkThreadLocalsForLeaksDebug", args)); } } else { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks", args)); } } } } } } }
// in java/org/apache/catalina/core/AprLifecycleListener.java
private static void terminateAPR() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { String methodName = "terminate"; Method method = Class.forName("org.apache.tomcat.jni.Library") .getMethod(methodName, (Class [])null); method.invoke(null, (Object []) null); aprAvailable = false; aprInitialized = false; sslInitialized = false; // Well we cleaned the pool in terminate. sslAvailable = false; // Well we cleaned the pool in terminate. fipsModeActive = false; }
// in java/org/apache/catalina/core/AprLifecycleListener.java
private static void initializeSSL() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { if ("off".equalsIgnoreCase(SSLEngine)) { return; } if (sslInitialized) { //only once per VM return; } sslInitialized = true; String methodName = "randSet"; Class<?> paramTypes[] = new Class[1]; paramTypes[0] = String.class; Object paramValues[] = new Object[1]; paramValues[0] = SSLRandomSeed; Class<?> clazz = Class.forName("org.apache.tomcat.jni.SSL"); Method method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); methodName = "initialize"; paramValues[0] = "on".equalsIgnoreCase(SSLEngine)?null:SSLEngine; method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); if("on".equalsIgnoreCase(FIPSMode)) { log.info(sm.getString("aprListener.initializingFIPS")); int result = SSL.fipsModeSet(1); // success is defined as return value = 1 if(1 == result) { fipsModeActive = true; log.info(sm.getString("aprListener.initializeFIPSSuccess")); } else { // This case should be handled by the native method, // but we'll make absolutely sure, here. String message = sm.getString("aprListener.initializeFIPSFailed"); log.error(message); throw new IllegalStateException(message); } } log.info(sm.getString("aprListener.initializedOpenSSL", SSL.versionString())); sslAvailable = true; }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
Filter getFilter() throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { // Return the existing filter instance, if any if (this.filter != null) return (this.filter); // Identify the class loader we will be using String filterClass = filterDef.getFilterClass(); this.filter = (Filter) getInstanceManager().newInstance(filterClass); initFilter(); return (this.filter); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
void setFilterDef(FilterDef filterDef) throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { this.filterDef = filterDef; if (filterDef == null) { // Release any previously allocated filter instance if (this.filter != null){ if (Globals.IS_SECURITY_ENABLED) { try{ SecurityUtil.doAsPrivilege("destroy", filter); } catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); } SecurityUtil.remove(filter); } else { filter.destroy(); } if (!context.getIgnoreAnnotations()) { try { ((StandardContext) context).getInstanceManager().destroyInstance(this.filter); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); } } } this.filter = null; } else { // Allocate a new filter instance if necessary if (filterDef.getFilter() == null) { getFilter(); } } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { Class<?> clazz = loadClassMaybePrivileged(className, classLoader); return newInstance(clazz.newInstance(), clazz); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(final String className, final ClassLoader classLoader) throws IllegalAccessException, NamingException, InvocationTargetException, InstantiationException, ClassNotFoundException { Class<?> clazz = classLoader.loadClass(className); return newInstance(clazz.newInstance(), clazz); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public void newInstance(Object o) throws IllegalAccessException, InvocationTargetException, NamingException { newInstance(o, o.getClass()); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
private Object newInstance(Object instance, Class<?> clazz) throws IllegalAccessException, InvocationTargetException, NamingException { if (!ignoreAnnotations) { Map<String, String> injections = injectionMap.get(clazz.getName()); populateAnnotationsCache(clazz, injections); processAnnotations(instance, injections); postConstruct(instance, clazz); } return instance; }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public void destroyInstance(Object instance) throws IllegalAccessException, InvocationTargetException { if (!ignoreAnnotations) { preDestroy(instance, instance.getClass()); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected void postConstruct(Object instance, final Class<?> clazz) throws IllegalAccessException, InvocationTargetException { if (context == null) { // No resource injection return; } Class<?> superClass = clazz.getSuperclass(); if (superClass != Object.class) { postConstruct(instance, superClass); } // At the end the postconstruct annotated // method is invoked AnnotationCacheEntry[] annotations; synchronized (annotationCache) { annotations = annotationCache.get(clazz); } for (AnnotationCacheEntry entry : annotations) { if (entry.getType() == AnnotationCacheEntryType.POST_CONSTRUCT) { Method postConstruct = getMethod(clazz, entry); synchronized (postConstruct) { boolean accessibility = postConstruct.isAccessible(); postConstruct.setAccessible(true); postConstruct.invoke(instance); postConstruct.setAccessible(accessibility); } } } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected void preDestroy(Object instance, final Class<?> clazz) throws IllegalAccessException, InvocationTargetException { Class<?> superClass = clazz.getSuperclass(); if (superClass != Object.class) { preDestroy(instance, superClass); } // At the end the postconstruct annotated // method is invoked AnnotationCacheEntry[] annotations = null; synchronized (annotationCache) { annotations = annotationCache.get(clazz); } if (annotations == null) { // instance not created through the instance manager return; } for (AnnotationCacheEntry entry : annotations) { if (entry.getType() == AnnotationCacheEntryType.PRE_DESTROY) { Method preDestroy = getMethod(clazz, entry); synchronized (preDestroy) { boolean accessibility = preDestroy.isAccessible(); preDestroy.setAccessible(true); preDestroy.invoke(instance); preDestroy.setAccessible(accessibility); } } } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected void populateAnnotationsCache(Class<?> clazz, Map<String, String> injections) throws IllegalAccessException, InvocationTargetException, NamingException { List<AnnotationCacheEntry> annotations = null; while (clazz != null) { AnnotationCacheEntry[] annotationsArray = null; synchronized (annotationCache) { annotationsArray = annotationCache.get(clazz); } if (annotationsArray == null) { if (annotations == null) { annotations = new ArrayList<AnnotationCacheEntry>(); } else { annotations.clear(); } if (context != null) { // Initialize fields annotations for resource injection if // JNDI is enabled Field[] fields = null; if (Globals.IS_SECURITY_ENABLED) { final Class<?> clazz2 = clazz; fields = AccessController.doPrivileged( new PrivilegedAction<Field[]>(){ @Override public Field[] run(){ return clazz2.getDeclaredFields(); } }); } else { fields = clazz.getDeclaredFields(); } for (Field field : fields) { if (injections != null && injections.containsKey(field.getName())) { annotations.add(new AnnotationCacheEntry( field.getName(), null, injections.get(field.getName()), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(Resource.class)) { Resource annotation = field.getAnnotation(Resource.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(EJB.class)) { EJB annotation = field.getAnnotation(EJB.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(WebServiceRef.class)) { WebServiceRef annotation = field.getAnnotation(WebServiceRef.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(PersistenceContext.class)) { PersistenceContext annotation = field.getAnnotation(PersistenceContext.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(PersistenceUnit.class)) { PersistenceUnit annotation = field.getAnnotation(PersistenceUnit.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } } } // Initialize methods annotations Method[] methods = null; if (Globals.IS_SECURITY_ENABLED) { final Class<?> clazz2 = clazz; methods = AccessController.doPrivileged( new PrivilegedAction<Method[]>(){ @Override public Method[] run(){ return clazz2.getDeclaredMethods(); } }); } else { methods = clazz.getDeclaredMethods(); } Method postConstruct = null; Method preDestroy = null; for (Method method : methods) { String methodName = method.getName(); if (context != null) { // Resource injection only if JNDI is enabled if (injections != null && methodName.startsWith("set") && methodName.length() > 3) { String fieldName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); if (injections.containsKey(fieldName)) { annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), injections.get(method.getName()), AnnotationCacheEntryType.SETTER)); break; } } if (method.isAnnotationPresent(Resource.class)) { Resource annotation = method.getAnnotation(Resource.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(EJB.class)) { EJB annotation = method.getAnnotation(EJB.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(WebServiceRef.class)) { WebServiceRef annotation = method.getAnnotation(WebServiceRef.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(PersistenceContext.class)) { PersistenceContext annotation = method.getAnnotation(PersistenceContext.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(PersistenceUnit.class)) { PersistenceUnit annotation = method.getAnnotation(PersistenceUnit.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } } if (method.isAnnotationPresent(PostConstruct.class)) { if ((postConstruct != null) || (method.getParameterTypes().length != 0) || (Modifier.isStatic(method.getModifiers())) || (method.getExceptionTypes().length > 0) || (!method.getReturnType().getName().equals("void"))) { throw new IllegalArgumentException( "Invalid PostConstruct annotation"); } postConstruct = method; } if (method.isAnnotationPresent(PreDestroy.class)) { if ((preDestroy != null || method.getParameterTypes().length != 0) || (Modifier.isStatic(method.getModifiers())) || (method.getExceptionTypes().length > 0) || (!method.getReturnType().getName().equals("void"))) { throw new IllegalArgumentException( "Invalid PreDestroy annotation"); } preDestroy = method; } } if (postConstruct != null) { annotations.add(new AnnotationCacheEntry( postConstruct.getName(), postConstruct.getParameterTypes(), null, AnnotationCacheEntryType.POST_CONSTRUCT)); } if (preDestroy != null) { annotations.add(new AnnotationCacheEntry( preDestroy.getName(), preDestroy.getParameterTypes(), null, AnnotationCacheEntryType.PRE_DESTROY)); } if (annotations.isEmpty()) { // Use common object to save memory annotationsArray = ANNOTATIONS_EMPTY; } else { annotationsArray = annotations.toArray( new AnnotationCacheEntry[annotations.size()]); } synchronized (annotationCache) { annotationCache.put(clazz, annotationsArray); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected void processAnnotations(Object instance, Map<String, String> injections) throws IllegalAccessException, InvocationTargetException, NamingException { if (context == null) { // No resource injection return; } Class<?> clazz = instance.getClass(); while (clazz != null) { AnnotationCacheEntry[] annotations; synchronized (annotationCache) { annotations = annotationCache.get(clazz); } for (AnnotationCacheEntry entry : annotations) { if (entry.getType() == AnnotationCacheEntryType.SETTER) { lookupMethodResource(context, instance, getMethod(clazz, entry), entry.getName(), clazz); } else if (entry.getType() == AnnotationCacheEntryType.FIELD) { lookupFieldResource(context, instance, getField(clazz, entry), entry.getName(), clazz); } } clazz = clazz.getSuperclass(); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected static void lookupFieldResource(Context context, Object instance, Field field, String name, Class<?> clazz) throws NamingException, IllegalAccessException { Object lookedupResource; boolean accessibility; String normalizedName = normalize(name); if ((normalizedName != null) && (normalizedName.length() > 0)) { lookedupResource = context.lookup(normalizedName); } else { lookedupResource = context.lookup(clazz.getName() + "/" + field.getName()); } synchronized (field) { accessibility = field.isAccessible(); field.setAccessible(true); field.set(instance, lookedupResource); field.setAccessible(accessibility); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected static void lookupMethodResource(Context context, Object instance, Method method, String name, Class<?> clazz) throws NamingException, IllegalAccessException, InvocationTargetException { if (!method.getName().startsWith("set") || method.getName().length() < 4 || method.getParameterTypes().length != 1 || !method.getReturnType().getName().equals("void")) { throw new IllegalArgumentException("Invalid method resource injection annotation"); } Object lookedupResource; boolean accessibility; String normalizedName = normalize(name); if ((normalizedName != null) && (normalizedName.length() > 0)) { lookedupResource = context.lookup(normalizedName); } else { lookedupResource = context.lookup( clazz.getName() + "/" + getName(method)); } synchronized (method) { accessibility = method.isAccessible(); method.setAccessible(true); method.invoke(instance, lookedupResource); method.setAccessible(accessibility); } }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
private Object executeMethod(final Method method, final ApplicationContext context, final Object[] params) throws PrivilegedActionException, IllegalAccessException, InvocationTargetException { if (SecurityUtil.isPackageProtectionEnabled()){ return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>(){ @Override public Object run() throws IllegalAccessException, InvocationTargetException{ return method.invoke(context, params); } }); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
Override public Object run() throws IllegalAccessException, InvocationTargetException{ return method.invoke(context, params); }
31
            
// in java/org/apache/jasper/JspCompilationContext.java
catch (IllegalAccessException e) { log.warn(Localizer.getMessage("jsp.error.compiler"), e); }
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.IllegalAccessException iae) { NamingException ne = new NamingException(iae.getMessage()); ne.setRootCause(iae); throw ne; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalAccessException iae) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: IllegalAccessException for " + o.getClass() + " " + name + "=" + value + ")", iae); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalAccessException iae) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: IllegalAccessException for " + o.getClass() + " " + name + ")", iae); }
// in java/org/apache/el/parser/AstFunction.java
catch (IllegalAccessException iae) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), iae); }
// in java/org/apache/el/parser/AstValue.java
catch (IllegalAccessException iae) { throw new ELException(iae); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IllegalAccessException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalAccessException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (IllegalAccessException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.IllegalAccessException", className), e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (IllegalAccessException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/session/JDBCStore.java
catch (IllegalAccessException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (IllegalAccessException e) { log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IllegalAccessException e) { ServletException se = new ServletException(e); throw se; }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalAccessException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalAccessException e) { log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/javax/el/ExpressionFactory.java
catch (IllegalAccessException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
20
            
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.IllegalAccessException iae) { NamingException ne = new NamingException(iae.getMessage()); ne.setRootCause(iae); throw ne; }
// in java/org/apache/el/parser/AstFunction.java
catch (IllegalAccessException iae) { throw new ELException(MessageFactory.get("error.function", this .getOutputName()), iae); }
// in java/org/apache/el/parser/AstValue.java
catch (IllegalAccessException iae) { throw new ELException(iae); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (IllegalAccessException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (IllegalAccessException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.IllegalAccessException", className), e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (IllegalAccessException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (IllegalAccessException e) { ServletException se = new ServletException(e); throw se; }
// in java/javax/el/ExpressionFactory.java
catch (IllegalAccessException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalAccessException e) { throw new ELException(e); }
7
runtime (Lib) IllegalArgumentException 226
            
// in java/org/apache/jasper/runtime/PageContextImpl.java
private Object doGetAttribute(String name, int scope) { switch (scope) { case PAGE_SCOPE: return attributes.get(name); case REQUEST_SCOPE: return request.getAttribute(name); case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } return session.getAttribute(name); case APPLICATION_SCOPE: return context.getAttribute(name); default: throw new IllegalArgumentException("Invalid scope"); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doSetAttribute(String name, Object o, int scope) { if (o != null) { switch (scope) { case PAGE_SCOPE: attributes.put(name, o); break; case REQUEST_SCOPE: request.setAttribute(name, o); break; case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } session.setAttribute(name, o); break; case APPLICATION_SCOPE: context.setAttribute(name, o); break; default: throw new IllegalArgumentException("Invalid scope"); } } else { removeAttribute(name, scope); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doRemoveAttribute(String name, int scope) { switch (scope) { case PAGE_SCOPE: attributes.remove(name); break; case REQUEST_SCOPE: request.removeAttribute(name); break; case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } session.removeAttribute(name); break; case APPLICATION_SCOPE: context.removeAttribute(name); break; default: throw new IllegalArgumentException("Invalid scope"); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private Enumeration<String> doGetAttributeNamesInScope(int scope) { switch (scope) { case PAGE_SCOPE: return Collections.enumeration(attributes.keySet()); case REQUEST_SCOPE: return request.getAttributeNames(); case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } return session.getAttributeNames(); case APPLICATION_SCOPE: return context.getAttributeNames(); default: throw new IllegalArgumentException("Invalid scope"); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object getValueFromPropertyEditorManager( Class<?> attrClass, String attrName, String attrValue) throws JasperException { try { PropertyEditor propEditor = PropertyEditorManager.findEditor(attrClass); if (propEditor != null) { propEditor.setAsText(attrValue); return propEditor.getValue(); } else { throw new IllegalArgumentException( Localizer.getMessage("jsp.error.beans.propertyeditor.notregistered")); } } catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); } }
// in java/org/apache/jasper/runtime/JspApplicationContextImpl.java
Override public void addELContextListener(ELContextListener listener) { if (listener == null) { throw new IllegalArgumentException("ELConextListener was null"); } this.contextListeners.add(listener); }
// in java/org/apache/jasper/runtime/JspApplicationContextImpl.java
public static JspApplicationContextImpl getInstance(ServletContext context) { if (context == null) { throw new IllegalArgumentException("ServletContext was null"); } JspApplicationContextImpl impl = (JspApplicationContextImpl) context .getAttribute(KEY); if (impl == null) { impl = new JspApplicationContextImpl(); context.setAttribute(KEY, impl); } return impl; }
// in java/org/apache/jasper/runtime/JspApplicationContextImpl.java
public ELContextImpl createELContext(JspContext context) { if (context == null) { throw new IllegalArgumentException("JspContext was null"); } // create ELContext for JspContext final ELResolver r = this.createELResolver(); ELContextImpl ctx; if (Constants.IS_SECURITY_ENABLED) { ctx = AccessController.doPrivileged( new PrivilegedAction<ELContextImpl>() { @Override public ELContextImpl run() { return new ELContextImpl(r); } }); }
// in java/org/apache/jasper/runtime/JspApplicationContextImpl.java
Override public void addELResolver(ELResolver resolver) throws IllegalStateException { if (resolver == null) { throw new IllegalArgumentException("ELResolver was null"); } if (this.instantiated) { throw new IllegalStateException( "cannot call addELResolver after the first request has been made"); } this.resolvers.add(resolver); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
public static synchronized TldLocationsCache getInstance( ServletContext ctxt) { if (ctxt == null) { throw new IllegalArgumentException("ServletContext was null"); } TldLocationsCache cache = (TldLocationsCache) ctxt.getAttribute(KEY); if (cache == null) { cache = new TldLocationsCache(ctxt); ctxt.setAttribute(KEY, cache); } return cache; }
// in java/org/apache/jasper/compiler/SmapStratum.java
public void setInputStartLine(int inputStartLine) { if (inputStartLine < 0) throw new IllegalArgumentException("" + inputStartLine); this.inputStartLine = inputStartLine; }
// in java/org/apache/jasper/compiler/SmapStratum.java
public void setOutputStartLine(int outputStartLine) { if (outputStartLine < 0) throw new IllegalArgumentException("" + outputStartLine); this.outputStartLine = outputStartLine; }
// in java/org/apache/jasper/compiler/SmapStratum.java
public void setLineFileID(int lineFileID) { if (lineFileID < 0) throw new IllegalArgumentException("" + lineFileID); this.lineFileID = lineFileID; this.lineFileIDSet = true; }
// in java/org/apache/jasper/compiler/SmapStratum.java
public void setInputLineCount(int inputLineCount) { if (inputLineCount < 0) throw new IllegalArgumentException("" + inputLineCount); this.inputLineCount = inputLineCount; }
// in java/org/apache/jasper/compiler/SmapStratum.java
public void setOutputLineIncrement(int outputLineIncrement) { if (outputLineIncrement < 0) throw new IllegalArgumentException("" + outputLineIncrement); this.outputLineIncrement = outputLineIncrement; }
// in java/org/apache/jasper/compiler/SmapStratum.java
public void addLineData( int inputStartLine, String inputFileName, int inputLineCount, int outputStartLine, int outputLineIncrement) { // check the input - what are you doing here?? int fileIndex = filePathList.indexOf(inputFileName); if (fileIndex == -1) // still throw new IllegalArgumentException( "inputFileName: " + inputFileName); //Jasper incorrectly SMAPs certain Nodes, giving them an //outputStartLine of 0. This can cause a fatal error in //optimizeLineSection, making it impossible for Jasper to //compile the JSP. Until we can fix the underlying //SMAPping problem, we simply ignore the flawed SMAP entries. if (outputStartLine == 0) return; // build the LineInfo LineInfo li = new LineInfo(); li.setInputStartLine(inputStartLine); li.setInputLineCount(inputLineCount); li.setOutputStartLine(outputStartLine); li.setOutputLineIncrement(outputLineIncrement); if (fileIndex != lastFileID) li.setLineFileID(fileIndex); lastFileID = fileIndex; // save it lineData.add(li); }
// in java/org/apache/jasper/compiler/AttributeParser.java
private char nextChar() { lastChEscaped = false; char ch = input.charAt(i); if (ch == '&') { if (i + 5 < size && input.charAt(i + 1) == 'a' && input.charAt(i + 2) == 'p' && input.charAt(i + 3) == 'o' && input.charAt(i + 4) == 's' && input.charAt(i + 5) == ';') { ch = '\''; i += 6; } else if (i + 5 < size && input.charAt(i + 1) == 'q' && input.charAt(i + 2) == 'u' && input.charAt(i + 3) == 'o' && input.charAt(i + 4) == 't' && input.charAt(i + 5) == ';') { ch = '\"'; i += 6; } else { ++i; } } else if (ch == '\\' && i + 1 < size) { ch = input.charAt(i + 1); if (ch == '\\' || ch == '\"' || ch == '\'' || (!isELIgnored && (ch == '$' || (!isDeferredSyntaxAllowedAsLiteral && ch == '#')))) { i += 2; lastChEscaped = true; } else { ch = '\\'; ++i; } } else if (ch == '<' && (i + 2 < size) && input.charAt(i + 1) == '\\' && input.charAt(i + 2) == '%') { // Note this is a hack since nextChar only returns a single char // It is safe since <% does not require special treatment for EL // or for literals result.append('<'); i+=3; return '%'; } else if (ch == '%' && i + 2 < size && input.charAt(i + 1) == '\\' && input.charAt(i + 2) == '>') { // Note this is a hack since nextChar only returns a single char // It is safe since %> does not require special treatment for EL // or for literals result.append('%'); i+=3; return '>'; } else if (ch == quote && strict) { String msg = Localizer.getMessage("jsp.error.attribute.noescape", input, ""+ quote); throw new IllegalArgumentException(msg); } else { ++i; } return ch; }
// in java/org/apache/jasper/util/UniqueAttributesImpl.java
private void handleDuplicate(String qName, String value) { if (pageDirective) { if (IMPORT.equalsIgnoreCase(qName)) { // Always merge imports int i = super.getIndex(IMPORT); String v = super.getValue(i); super.setValue(i, v + "," + value); return; } else if (PAGE_ENCODING.equalsIgnoreCase(qName)) { // Page encoding can only occur once per file so a second // attribute - even one with a duplicate value - is an error } else { // Other attributes can be repeated if and only if the values // are identical String v = super.getValue(qName); if (v.equals(value)) { return; } } } // Ordinary tag attributes can't be repeated, even with identical values throw new IllegalArgumentException( Localizer.getMessage("jsp.error.duplicateqname", qName)); }
// in java/org/apache/naming/StringManager.java
public String getString(String key) { if(key == null){ String msg = "key may not have a null value"; throw new IllegalArgumentException(msg); } String str = null; try { str = bundle.getString(key); } catch(MissingResourceException mre) { //bad: shouldn't mask an exception the following way: // str = "[cannot find message associated with key '" + key + "' due to " + mre + "]"; // because it hides the fact that the String was missing // from the calling code. //good: could just throw the exception (or wrap it in another) // but that would probably cause much havoc on existing // code. //better: consistent with container pattern to // simply return null. Calling code can then do // a null check. str = null; } return str; }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void setDocBase(String docBase) { // Validate the format of the proposed document root if (docBase == null) throw new IllegalArgumentException (sm.getString("resources.null")); if (!(docBase.endsWith(".war"))) throw new IllegalArgumentException (sm.getString("warResources.notWar")); // Calculate a File object referencing this document base directory File base = new File(docBase); // Validate that the document base is an existing directory if (!base.exists() || !base.canRead() || base.isDirectory()) throw new IllegalArgumentException (sm.getString("warResources.invalidWar", docBase)); try { this.base = new ZipFile(base); } catch (Exception e) { throw new IllegalArgumentException (sm.getString("warResources.invalidWar", e.getMessage())); } super.setDocBase(docBase); loadEntries(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void setDocBase(String docBase) { // Validate the format of the proposed document root if (docBase == null) throw new IllegalArgumentException (sm.getString("resources.null")); // Calculate a File object referencing this document base directory base = new File(docBase); try { base = base.getCanonicalFile(); } catch (IOException e) { // Ignore } // Validate that the document base is an existing directory if (!base.exists() || !base.isDirectory() || !base.canRead()) throw new IllegalArgumentException (sm.getString("fileResources.base", docBase)); this.absoluteBase = base.getAbsolutePath(); super.setDocBase(docBase); }
// in java/org/apache/naming/resources/BaseDirContext.java
public void addAlias(String path, BaseDirContext dirContext) { if (!path.startsWith("/")) { throw new IllegalArgumentException( sm.getString("resources.invalidAliasPath", path)); } aliases.put(path, dirContext); }
// in java/org/apache/naming/resources/BaseDirContext.java
public void removeAlias(String path) { if (!path.startsWith("/")) { throw new IllegalArgumentException( sm.getString("resources.invalidAliasPath", path)); } aliases.remove(path); }
// in java/org/apache/naming/resources/BaseDirContext.java
public void setAliases(String theAliases) { // Overwrite whatever is currently set aliases.clear(); if (theAliases == null || theAliases.length() == 0) return; String[] kvps = theAliases.split(","); for (String kvp : kvps) { String[] kv = kvp.split("="); if (kv.length != 2 || kv[0].length() == 0 || kv[1].length() == 0) throw new IllegalArgumentException( sm.getString("resources.invalidAliasMapping", kvp)); if (kv[0].equals("/")) { throw new IllegalArgumentException( sm.getString("resources.invalidAliasNotAllowed", kv[0])); } File aliasLoc = new File(kv[1]); if (!aliasLoc.exists()) { throw new IllegalArgumentException( sm.getString("resources.invalidAliasNotExist", kv[1])); } BaseDirContext context; if (kv[1].endsWith(".war") && !(aliasLoc.isDirectory())) { context = new WARDirContext(); } else if (aliasLoc.isDirectory()) { context = new FileDirContext(); } else { throw new IllegalArgumentException( sm.getString("resources.invalidAliasFile", kv[1])); } context.setDocBase(kv[1]); addAlias(kv[0], context); } }
// in java/org/apache/naming/resources/BaseDirContext.java
public void setDocBase(String docBase) { // Validate the format of the proposed document root if (docBase == null) throw new IllegalArgumentException (sm.getString("resources.null")); // Change the document root property this.docBase = docBase; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
protected boolean readMessage(AjpMessage message, boolean first, boolean useAvailableData) throws IOException { int headerLength = message.getHeaderLength(); if (first) { if (!readt(headerLength, useAvailableData)) { return false; } } else { read(headerLength); } inputBuffer.get(message.getBuffer(), 0, headerLength); int messageLength = message.processHeader(true); if (messageLength < 0) { // Invalid AJP header signature // TODO: Throw some exception and close the connection to frontend. return false; } else if (messageLength == 0) { // Zero length message. return true; } else { if (messageLength > message.getBuffer().length) { // Message too long for the buffer // Need to trigger a 400 response throw new IllegalArgumentException(sm.getString( "ajpprocessor.header.tooLong", Integer.valueOf(messageLength), Integer.valueOf(message.getBuffer().length))); } read(messageLength); inputBuffer.get(message.getBuffer(), headerLength, messageLength); return true; } }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
protected int readMessage(AjpMessage message, boolean blockFirstRead) throws IOException { byte[] buf = message.getBuffer(); int headerLength = message.getHeaderLength(); int bytesRead = read(buf, 0, headerLength, blockFirstRead); if (bytesRead == 0) { return 0; } int messageLength = message.processHeader(true); if (messageLength < 0) { // Invalid AJP header signature throw new IOException(sm.getString("ajpmessage.invalidLength", Integer.valueOf(messageLength))); } else if (messageLength == 0) { // Zero length message. return bytesRead; } else { if (messageLength > buf.length) { // Message too long for the buffer // Need to trigger a 400 response throw new IllegalArgumentException(sm.getString( "ajpprocessor.header.tooLong", Integer.valueOf(messageLength), Integer.valueOf(buf.length))); } bytesRead += read(buf, headerLength, messageLength, true); return bytesRead; } }
// in java/org/apache/coyote/ajp/AjpProcessor.java
protected boolean readMessage(AjpMessage message) throws IOException { byte[] buf = message.getBuffer(); int headerLength = message.getHeaderLength(); read(buf, 0, headerLength); int messageLength = message.processHeader(true); if (messageLength < 0) { // Invalid AJP header signature // TODO: Throw some exception and close the connection to frontend. return false; } else if (messageLength == 0) { // Zero length message. return true; } else { if (messageLength > buf.length) { // Message too long for the buffer // Need to trigger a 400 response throw new IllegalArgumentException(sm.getString( "ajpprocessor.header.tooLong", Integer.valueOf(messageLength), Integer.valueOf(buf.length))); } read(buf, headerLength, messageLength); return true; } }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableDataOnly) throws IOException { //check state if ( !parsingRequestLine ) return true; // // Skipping blank lines // if ( parsingRequestLinePhase == 0 ) { byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (useAvailableDataOnly) { return false; } // Ignore bytes that were read pos = lastValid = 0; // Do a simple read with a short timeout if ( readSocket(true, false)==0 ) return false; } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; if (pos >= skipBlankLinesSize) { // Move data, to have enough space for further reading // of headers and body System.arraycopy(buf, pos, buf, 0, lastValid - pos); lastValid -= pos; pos = 0; } skipBlankLinesBytes = pos; parsingRequestLineStart = pos; parsingRequestLinePhase = 2; if (log.isDebugEnabled()) { log.debug("Received [" + new String(buf, pos, lastValid - pos, DEFAULT_CHARSET) + "]"); } } if ( parsingRequestLinePhase == 2 ) { // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, parsingRequestLineStart, pos - parsingRequestLineStart); } pos++; } parsingRequestLinePhase = 3; } if ( parsingRequestLinePhase == 3 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 4; } if (parsingRequestLinePhase == 4) { // Mark the current buffer position int end = 0; // // Reading the URI // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request parsingRequestLineEol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (parsingRequestLineQPos == -1)) { parsingRequestLineQPos = pos; } pos++; } request.unparsedURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); if (parsingRequestLineQPos >= 0) { request.queryString().setBytes(buf, parsingRequestLineQPos + 1, end - parsingRequestLineQPos - 1); request.requestURI().setBytes(buf, parsingRequestLineStart, parsingRequestLineQPos - parsingRequestLineStart); } else { request.requestURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } parsingRequestLinePhase = 5; } if ( parsingRequestLinePhase == 5 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 6; } if (parsingRequestLinePhase == 6) { // Mark the current buffer position end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!parsingRequestLineEol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; parsingRequestLineEol = true; } pos++; } if ( (end - parsingRequestLineStart) > 0) { request.protocol().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } else { request.protocol().setString(""); } parsingRequestLine = false; parsingRequestLinePhase = 0; parsingRequestLineEol = false; parsingRequestLineStart = 0; return true; } throw new IllegalStateException("Invalid request line parse phase:"+parsingRequestLinePhase); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
private void expand(int newsize) { if ( newsize > buf.length ) { if (parsingHeader) { throw new IllegalArgumentException( sm.getString("iib.requestheadertoolarge.error")); } // Should not happen log.warn("Expanding buffer size. Old size: " + buf.length + ", new size: " + newsize, new Exception()); byte[] tmp = new byte[newsize]; System.arraycopy(buf,0,tmp,0,buf.length); buf = tmp; } }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } HeaderParseStatus status = HeaderParseStatus.HAVE_MORE_HEADERS; do { status = parseHeader(); } while ( status == HeaderParseStatus.HAVE_MORE_HEADERS ); if (status == HeaderParseStatus.DONE) { parsingHeader = false; end = pos; // Checking that // (1) Headers plus request line size does not exceed its limit // (2) There are enough bytes to avoid expanding the buffer when // reading body // Technically, (2) is technical limitation, (1) is logical // limitation to enforce the meaning of headerBufferSize // From the way how buf is allocated and how blank lines are being // read, it should be enough to check (1) only. if (end - skipBlankLinesBytes > headerBufferSize || buf.length - end < socketReadBufferSize) { throw new IllegalArgumentException( sm.getString("iib.requestheadertoolarge.error")); } return true; } else { return false; } }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
protected boolean fill(boolean timeout, boolean block) throws IOException, EOFException { boolean read = false; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } // Do a simple read with a short timeout read = readSocket(timeout,block)>0; } else { lastValid = pos = end; // Do a simple read with a short timeout read = readSocket(timeout, block)>0; } return read; }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableDataOnly) throws IOException { int start = 0; // // Skipping blank lines // byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; // Mark the current buffer position start = pos; // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, start, pos - start); } pos++; } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; int end = 0; int questionPos = -1; // // Reading the URI // boolean eol = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request eol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (questionPos == -1)) { questionPos = pos; } pos++; } request.unparsedURI().setBytes(buf, start, end - start); if (questionPos >= 0) { request.queryString().setBytes(buf, questionPos + 1, end - questionPos - 1); request.requestURI().setBytes(buf, start, questionPos - start); } else { request.requestURI().setBytes(buf, start, end - start); } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; eol = true; } pos++; } if ((end - start) > 0) { request.protocol().setBytes(buf, start, end - start); } else { request.protocol().setString(""); } return true; }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override protected boolean fill(boolean block) throws IOException { int nRead = 0; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } nRead = inputStream.read(buf, pos, buf.length - lastValid); if (nRead > 0) { lastValid = pos + nRead; } } else { if (buf.length - end < 4500) { // In this case, the request header was really large, so we allocate a // brand new one; the old one will get GCed when subsequent requests // clear all references buf = new byte[buf.length]; end = 0; } pos = end; lastValid = pos; nRead = inputStream.read(buf, pos, buf.length - lastValid); if (nRead > 0) { lastValid = pos + nRead; } } return (nRead > 0); }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableData) throws IOException { int start = 0; // // Skipping blank lines // byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (useAvailableData) { return false; } if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; // Mark the current buffer position start = pos; if (pos >= lastValid) { if (useAvailableData) { return false; } if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, start, pos - start); } pos++; } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; int end = 0; int questionPos = -1; // // Reading the URI // boolean eol = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } // Spec says single SP but it also says be tolerant of HT if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request eol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (questionPos == -1)) { questionPos = pos; } pos++; } request.unparsedURI().setBytes(buf, start, end - start); if (questionPos >= 0) { request.queryString().setBytes(buf, questionPos + 1, end - questionPos - 1); request.requestURI().setBytes(buf, start, questionPos - start); } else { request.requestURI().setBytes(buf, start, end - start); } // Spec says single SP but also says be tolerant of multiple and/or HT while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } // Mark the current buffer position start = pos; end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill()) throw new EOFException(sm.getString("iib.eof.error")); } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; eol = true; } pos++; } if ((end - start) > 0) { request.protocol().setBytes(buf, start, end - start); } else { request.protocol().setString(""); } return true; }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
protected boolean fill() throws IOException { int nRead = 0; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.EAGAIN) { return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } else { if (buf.length - end < 4500) { // In this case, the request header was really large, so we allocate a // brand new one; the old one will get GCed when subsequent requests // clear all references buf = new byte[buf.length]; end = 0; } pos = end; lastValid = pos; bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.ETIMEDOUT || (-nRead) == Status.TIMEUP) { throw new SocketTimeoutException(sm.getString("iib.failedread")); } else if (nRead == 0) { // APR_STATUS_IS_EOF, since native 1.1.22 return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } return (nRead > 0); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int read(ByteBuffer dst) throws IOException { //if we want to take advantage of the expand function, make sure we only use the ApplicationBufferHandler's buffers if ( dst != bufHandler.getReadBuffer() ) throw new IllegalArgumentException("You can only read using the application read buffer provided by the handler."); //are we in the middle of closing or closed? if ( closing || closed) return -1; //did we finish our handshake? if (!handshakeComplete) throw new IllegalStateException("Handshake incomplete, you must complete handshake before reading data."); //read from the network int netread = sc.read(netInBuffer); //did we reach EOF? if so send EOF up one layer. if (netread == -1) return -1; //the data read int read = 0; //the SSL engine result SSLEngineResult unwrap; do { //prepare the buffer netInBuffer.flip(); //unwrap the data unwrap = sslEngine.unwrap(netInBuffer, dst); //compact the buffer netInBuffer.compact(); if ( unwrap.getStatus()==Status.OK || unwrap.getStatus()==Status.BUFFER_UNDERFLOW ) { //we did receive some data, add it to our total read += unwrap.bytesProduced(); //perform any tasks if needed if (unwrap.getHandshakeStatus() == HandshakeStatus.NEED_TASK) tasks(); //if we need more network data, then bail out for now. if ( unwrap.getStatus() == Status.BUFFER_UNDERFLOW ) break; }else if ( unwrap.getStatus()==Status.BUFFER_OVERFLOW && read>0 ) { //buffer overflow can happen, if we have read data, then //empty out the dst buffer before we do another read break; }else { //here we should trap BUFFER_OVERFLOW and call expand on the buffer //for now, throw an exception, as we initialized the buffers //in the constructor throw new IOException("Unable to unwrap data, invalid status: " + unwrap.getStatus()); } } while ( (netInBuffer.position() != 0)); //continue to unwrapping as long as the input buffer has stuff return (read); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int write(ByteBuffer src) throws IOException { if ( src == this.netOutBuffer ) { //we can get here through a recursive call //by using the NioBlockingSelector int written = sc.write(src); return written; } else { //make sure we can handle expand, and that we only use on buffer if ( (!this.isSendFile()) && (src != bufHandler.getWriteBuffer()) ) throw new IllegalArgumentException("You can only write using the application write buffer provided by the handler."); //are we closing or closed? if ( closing || closed) throw new IOException("Channel is in closing state."); //the number of bytes written int written = 0; if (!flush(netOutBuffer)) { //we haven't emptied out the buffer yet return written; } /* * The data buffer is empty, we can reuse the entire buffer. */ netOutBuffer.clear(); SSLEngineResult result = sslEngine.wrap(src, netOutBuffer); written = result.bytesConsumed(); netOutBuffer.flip(); if (result.getStatus() == Status.OK) { if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) tasks(); } else { throw new IOException("Unable to wrap data, invalid engine state: " +result.getStatus()); } //force a flush flush(netOutBuffer); return written; } }
// in java/org/apache/tomcat/util/http/MimeHeaders.java
public MessageBytes getUniqueValue(String name) { MessageBytes result = null; for (int i = 0; i < count; i++) { if (headers[i].getName().equalsIgnoreCase(name)) { if (result == null) { result = headers[i].getValue(); } else { throw new IllegalArgumentException(); } } } return result; }
// in java/org/apache/tomcat/util/http/CookieSupport.java
public static final boolean isV0Separator(final char c) { if (c < 0x20 || c >= 0x7f) { if (c != 0x09) { throw new IllegalArgumentException( "Control character in cookie value or attribute."); } } return V0_SEPARATOR_FLAGS[c]; }
// in java/org/apache/tomcat/util/http/CookieSupport.java
public static final boolean isHttpSeparator(final char c) { if (c < 0x20 || c >= 0x7f) { if (c != 0x09) { throw new IllegalArgumentException( "Control character in cookie value or attribute."); } } return HTTP_SEPARATOR_FLAGS[c]; }
// in java/org/apache/tomcat/util/http/ServerCookie.java
private static String escapeDoubleQuotes(String s, int beginIndex, int endIndex) { if (s == null || s.length() == 0 || s.indexOf('"') == -1) { return s; } StringBuffer b = new StringBuffer(); for (int i = beginIndex; i < endIndex; i++) { char c = s.charAt(i); if (c == '\\' ) { b.append(c); //ignore the character after an escape, just append it if (++i>=endIndex) { throw new IllegalArgumentException("Invalid escape character in cookie value."); } b.append(s.charAt(i)); } else if (c == '"') { b.append('\\').append('"'); } else { b.append(c); } } return b.toString(); }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
public static void cleanDirectory(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (int i = 0; i < files.length; i++) { File file = files[i]; try { forceDelete(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } }
// in java/org/apache/tomcat/util/http/fileupload/FileUtils.java
private static void cleanDirectoryOnExit(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (int i = 0; i < files.length; i++) { File file = files[i]; try { forceDeleteOnExit(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } }
// in java/org/apache/tomcat/util/buf/UDecoder.java
public final String convert(String str, boolean query) { if (str == null) { return null; } if( (!query || str.indexOf( '+' ) < 0) && str.indexOf( '%' ) < 0 ) { return str; } final boolean noSlash = !(ALLOW_ENCODED_SLASH || query); StringBuilder dec = new StringBuilder(); // decoded string output int strPos = 0; int strLen = str.length(); dec.ensureCapacity(str.length()); while (strPos < strLen) { int laPos; // lookahead position // look ahead to next URLencoded metacharacter, if any for (laPos = strPos; laPos < strLen; laPos++) { char laChar = str.charAt(laPos); if ((laChar == '+' && query) || (laChar == '%')) { break; } } // if there were non-metacharacters, copy them all as a block if (laPos > strPos) { dec.append(str.substring(strPos,laPos)); strPos = laPos; } // shortcut out of here if we're at the end of the string if (strPos >= strLen) { break; } // process next metacharacter char metaChar = str.charAt(strPos); if (metaChar == '+') { dec.append(' '); strPos++; continue; } else if (metaChar == '%') { // We throw the original exception - the super will deal with // it // try { char res = (char) Integer.parseInt( str.substring(strPos + 1, strPos + 3), 16); if (noSlash && (res == '/')) { throw new IllegalArgumentException("noSlash"); } dec.append(res); strPos += 3; } } return dec.toString(); }
// in java/org/apache/tomcat/util/res/StringManager.java
public String getString(String key) { if(key == null){ String msg = "key may not have a null value"; throw new IllegalArgumentException(msg); } String str = null; try { // Avoid NPE if bundle is null and treat it like an MRE if (bundle != null) { str = bundle.getString(key); } } catch(MissingResourceException mre) { //bad: shouldn't mask an exception the following way: // str = "[cannot find message associated with key '" + key + // "' due to " + mre + "]"; // because it hides the fact that the String was missing // from the calling code. //good: could just throw the exception (or wrap it in another) // but that would probably cause much havoc on existing // code. //better: consistent with container pattern to // simply return null. Calling code can then do // a null check. str = null; } return str; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void addAttributeChangeNotificationListener (NotificationListener listener, String name, Object handback) throws IllegalArgumentException { if (listener == null) throw new IllegalArgumentException("Listener is null"); if (attributeBroadcaster == null) attributeBroadcaster = new BaseNotificationBroadcaster(); if( log.isDebugEnabled() ) log.debug("addAttributeNotificationListener " + listener); BaseAttributeFilter filter = new BaseAttributeFilter(name); attributeBroadcaster.addNotificationListener (listener, filter, handback); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void removeAttributeChangeNotificationListener (NotificationListener listener, String name) throws ListenerNotFoundException { if (listener == null) throw new IllegalArgumentException("Listener is null"); if (attributeBroadcaster == null) attributeBroadcaster = new BaseNotificationBroadcaster(); // FIXME - currently this removes *all* notifications for this listener attributeBroadcaster.removeNotificationListener(listener); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException { if (listener == null) throw new IllegalArgumentException("Listener is null"); if( log.isDebugEnabled() ) log.debug("addNotificationListener " + listener); if (generalBroadcaster == null) generalBroadcaster = new BaseNotificationBroadcaster(); generalBroadcaster.addNotificationListener (listener, filter, handback); // We'll send the attribute change notifications to all listeners ( who care ) // The normal filtering can be used. // The problem is that there is no other way to add attribute change listeners // to a model mbean ( AFAIK ). I suppose the spec should be fixed. if (attributeBroadcaster == null) attributeBroadcaster = new BaseNotificationBroadcaster(); if( log.isDebugEnabled() ) log.debug("addAttributeNotificationListener " + listener); attributeBroadcaster.addNotificationListener (listener, filter, handback); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { if (listener == null) throw new IllegalArgumentException("Listener is null"); if (generalBroadcaster == null) generalBroadcaster = new BaseNotificationBroadcaster(); generalBroadcaster.removeNotificationListener(listener); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
public static Object convert(String object, Class<?> paramType) { Object result = null; if ("java.lang.String".equals(paramType.getName())) { result = object; } else if ("java.lang.Integer".equals(paramType.getName()) || "int".equals(paramType.getName())) { try { result = new Integer(object); } catch (NumberFormatException ex) { } // Try a setFoo ( boolean ) } else if ("java.lang.Boolean".equals(paramType.getName()) || "boolean".equals(paramType.getName())) { result = Boolean.valueOf(object); // Try a setFoo ( InetAddress ) } else if ("java.net.InetAddress".equals(paramType .getName())) { try { result = InetAddress.getByName(object); } catch (UnknownHostException exc) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Unable to resolve host name:" + object); } // Unknown type } else { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Unknown type " + paramType.getName()); } if (result == null) { throw new IllegalArgumentException("Can't convert argument: " + object); } return result; }
// in java/org/apache/el/lang/ELArithmetic.java
protected final Number coerce(final Object obj) { if (isNumber(obj)) { return coerce((Number) obj); } if (obj == null || "".equals(obj)) { return coerce(ZERO); } if (obj instanceof String) { return coerce((String) obj); } if (obj instanceof Character) { return coerce(Short.valueOf((short) ((Character) obj).charValue())); } throw new IllegalArgumentException(MessageFactory.get("error.convert", obj, obj.getClass(), "Number")); }
// in java/org/apache/catalina/startup/ContextConfig.java
private void convertJsp(ServletDef servletDef, Map<String,String> jspInitParams) { servletDef.setServletClass(org.apache.catalina.core.Constants.JSP_SERVLET_CLASS); String jspFile = servletDef.getJspFile(); if ((jspFile != null) && !jspFile.startsWith("/")) { if (context.isServlet22()) { if(log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.jspFile.warning", jspFile)); } jspFile = "/" + jspFile; } else { throw new IllegalArgumentException (sm.getString("contextConfig.jspFile.error", jspFile)); } } servletDef.getParameterMap().put("jspFile", jspFile); servletDef.setJspFile(null); for (Map.Entry<String, String> initParam: jspInitParams.entrySet()) { servletDef.addInitParameter(initParam.getKey(), initParam.getValue()); } }
// in java/org/apache/catalina/startup/ContextConfig.java
protected void processAnnotationWebServlet(String className, AnnotationEntry ae, WebXml fragment) { String servletName = null; // must search for name s. Spec Servlet API 3.0 - 8.2.3.3.n.ii page 81 ElementValuePair[] evps = ae.getElementValuePairs(); for (ElementValuePair evp : evps) { String name = evp.getNameString(); if ("name".equals(name)) { servletName = evp.getValue().stringifyValue(); break; } } if (servletName == null) { // classname is default servletName as annotation has no name! servletName = className; } ServletDef servletDef = fragment.getServlets().get(servletName); boolean isWebXMLservletDef; if (servletDef == null) { servletDef = new ServletDef(); servletDef.setServletName(servletName); servletDef.setServletClass(className); isWebXMLservletDef = false; } else { isWebXMLservletDef = true; } boolean urlPatternsSet = false; String[] urlPatterns = null; // ElementValuePair[] evps = ae.getElementValuePairs(); for (ElementValuePair evp : evps) { String name = evp.getNameString(); if ("value".equals(name) || "urlPatterns".equals(name)) { if (urlPatternsSet) { throw new IllegalArgumentException(sm.getString( "contextConfig.urlPatternValue", className)); } urlPatternsSet = true; urlPatterns = processAnnotationsStringArray(evp.getValue()); } else if ("description".equals(name)) { if (servletDef.getDescription() == null) { servletDef.setDescription(evp.getValue().stringifyValue()); } } else if ("displayName".equals(name)) { if (servletDef.getDisplayName() == null) { servletDef.setDisplayName(evp.getValue().stringifyValue()); } } else if ("largeIcon".equals(name)) { if (servletDef.getLargeIcon() == null) { servletDef.setLargeIcon(evp.getValue().stringifyValue()); } } else if ("smallIcon".equals(name)) { if (servletDef.getSmallIcon() == null) { servletDef.setSmallIcon(evp.getValue().stringifyValue()); } } else if ("asyncSupported".equals(name)) { if (servletDef.getAsyncSupported() == null) { servletDef.setAsyncSupported(evp.getValue() .stringifyValue()); } } else if ("loadOnStartup".equals(name)) { if (servletDef.getLoadOnStartup() == null) { servletDef .setLoadOnStartup(evp.getValue().stringifyValue()); } } else if ("initParams".equals(name)) { Map<String, String> initParams = processAnnotationWebInitParams(evp .getValue()); if (isWebXMLservletDef) { Map<String, String> webXMLInitParams = servletDef .getParameterMap(); for (Map.Entry<String, String> entry : initParams .entrySet()) { if (webXMLInitParams.get(entry.getKey()) == null) { servletDef.addInitParameter(entry.getKey(), entry .getValue()); } } } else { for (Map.Entry<String, String> entry : initParams .entrySet()) { servletDef.addInitParameter(entry.getKey(), entry .getValue()); } } } } if (!isWebXMLservletDef && urlPatterns != null) { fragment.addServlet(servletDef); } if (urlPatterns != null) { if (!fragment.getServletMappings().containsValue(servletName)) { for (String urlPattern : urlPatterns) { fragment.addServletMapping(urlPattern, servletName); } } } }
// in java/org/apache/catalina/startup/ContextConfig.java
protected void processAnnotationWebFilter(String className, AnnotationEntry ae, WebXml fragment) { String filterName = null; // must search for name s. Spec Servlet API 3.0 - 8.2.3.3.n.ii page 81 ElementValuePair[] evps = ae.getElementValuePairs(); for (ElementValuePair evp : evps) { String name = evp.getNameString(); if ("filterName".equals(name)) { filterName = evp.getValue().stringifyValue(); break; } } if (filterName == null) { // classname is default filterName as annotation has no name! filterName = className; } FilterDef filterDef = fragment.getFilters().get(filterName); FilterMap filterMap = new FilterMap(); boolean isWebXMLfilterDef; if (filterDef == null) { filterDef = new FilterDef(); filterDef.setFilterName(filterName); filterDef.setFilterClass(className); isWebXMLfilterDef = false; } else { isWebXMLfilterDef = true; } boolean urlPatternsSet = false; boolean dispatchTypesSet = false; String[] urlPatterns = null; for (ElementValuePair evp : evps) { String name = evp.getNameString(); if ("value".equals(name) || "urlPatterns".equals(name)) { if (urlPatternsSet) { throw new IllegalArgumentException(sm.getString( "contextConfig.urlPatternValue", className)); } urlPatterns = processAnnotationsStringArray(evp.getValue()); urlPatternsSet = urlPatterns.length > 0; for (String urlPattern : urlPatterns) { filterMap.addURLPattern(urlPattern); } } else if ("servletNames".equals(name)) { String[] servletNames = processAnnotationsStringArray(evp .getValue()); for (String servletName : servletNames) { filterMap.addServletName(servletName); } } else if ("dispatcherTypes".equals(name)) { String[] dispatcherTypes = processAnnotationsStringArray(evp .getValue()); dispatchTypesSet = dispatcherTypes.length > 0; for (String dispatcherType : dispatcherTypes) { filterMap.setDispatcher(dispatcherType); } } else if ("description".equals(name)) { if (filterDef.getDescription() == null) { filterDef.setDescription(evp.getValue().stringifyValue()); } } else if ("displayName".equals(name)) { if (filterDef.getDisplayName() == null) { filterDef.setDisplayName(evp.getValue().stringifyValue()); } } else if ("largeIcon".equals(name)) { if (filterDef.getLargeIcon() == null) { filterDef.setLargeIcon(evp.getValue().stringifyValue()); } } else if ("smallIcon".equals(name)) { if (filterDef.getSmallIcon() == null) { filterDef.setSmallIcon(evp.getValue().stringifyValue()); } } else if ("asyncSupported".equals(name)) { if (filterDef.getAsyncSupported() == null) { filterDef .setAsyncSupported(evp.getValue().stringifyValue()); } } else if ("initParams".equals(name)) { Map<String, String> initParams = processAnnotationWebInitParams(evp .getValue()); if (isWebXMLfilterDef) { Map<String, String> webXMLInitParams = filterDef .getParameterMap(); for (Map.Entry<String, String> entry : initParams .entrySet()) { if (webXMLInitParams.get(entry.getKey()) == null) { filterDef.addInitParameter(entry.getKey(), entry .getValue()); } } } else { for (Map.Entry<String, String> entry : initParams .entrySet()) { filterDef.addInitParameter(entry.getKey(), entry .getValue()); } } } } if (!isWebXMLfilterDef) { fragment.addFilter(filterDef); filterMap.setFilterName(filterName); fragment.addFilterMapping(filterMap); } if (urlPatternsSet || dispatchTypesSet) { Set<FilterMap> fmap = fragment.getFilterMappings(); FilterMap descMap = null; for (FilterMap map : fmap) { if (filterName.equals(map.getFilterName())) { descMap = map; break; } } if (descMap != null) { String[] urlsPatterns = descMap.getURLPatterns(); if (urlPatternsSet && (urlsPatterns == null || urlsPatterns.length == 0)) { for (String urlPattern : filterMap.getURLPatterns()) { descMap.addURLPattern(urlPattern); } } String[] dispatcherNames = descMap.getDispatcherNames(); if (dispatchTypesSet && (dispatcherNames == null || dispatcherNames.length == 0)) { for (String dis : filterMap.getDispatcherNames()) { descMap.setDispatcher(dis); } } } } }
// in java/org/apache/catalina/startup/WebAnnotationSet.java
private static void checkBeanNamingConventions(Method method) { if (!method.getName().startsWith("set") || method.getName().length() < 4 || method.getParameterTypes().length != 1 || !method.getReturnType().getName().equals("void")) { throw new IllegalArgumentException("Invalid method resource injection annotation."); } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isLoginConfigSet){ throw new IllegalArgumentException( "<login-config> element is limited to 1 occurrence"); } isLoginConfigSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isJspConfigSet){ throw new IllegalArgumentException( "<jsp-config> element is limited to 1 occurrence"); } isJspConfigSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isSessionConfigSet){ throw new IllegalArgumentException( "<session-config> element is limited to 1 occurrence"); } isSessionConfigSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (isNameSet){ throw new IllegalArgumentException(WebRuleSet.sm.getString( "webRuleSet.nameCount")); } isNameSet = true; }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (fragment) { digester.getLogger().warn( WebRuleSet.sm.getString("webRuleSet.absoluteOrdering")); } if (isAbsoluteOrderingSet) { throw new IllegalArgumentException(WebRuleSet.sm.getString( "webRuleSet.absoluteOrderingCount")); } else { isAbsoluteOrderingSet = true; } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (!fragment) { digester.getLogger().warn( WebRuleSet.sm.getString("webRuleSet.relativeOrdering")); } if (isRelativeOrderingSet) { throw new IllegalArgumentException(WebRuleSet.sm.getString( "webRuleSet.relativeOrderingCount")); } else { isRelativeOrderingSet = true; } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { WebXml webXml = (WebXml) digester.peek(digester.getCount() - 1); // If we have a public ID, this is not a 2.4 or later webapp boolean havePublicId = (webXml.getPublicId() != null); // havePublicId and isServlet24OrLater should be mutually exclusive if (havePublicId == isServlet24OrLater) { throw new IllegalArgumentException( "taglib definition not consistent with specification version"); } }
// in java/org/apache/catalina/startup/ExpandWar.java
public static String expand(Host host, URL war, String pathname) throws IOException { // Make sure that there is no such directory already existing File docBase = new File(host.getAppBaseFile(), pathname); if (docBase.exists()) { // War file is already installed return (docBase.getAbsolutePath()); } // Create the new document base directory docBase.mkdir(); // Expand the WAR into the new document base directory String canonicalDocBasePrefix = docBase.getCanonicalPath(); if (!canonicalDocBasePrefix.endsWith(File.separator)) { canonicalDocBasePrefix += File.separator; } JarURLConnection juc = (JarURLConnection) war.openConnection(); juc.setUseCaches(false); JarFile jarFile = null; InputStream input = null; boolean success = false; try { jarFile = juc.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String name = jarEntry.getName(); File expandedFile = new File(docBase, name); if (!expandedFile.getCanonicalPath().startsWith( canonicalDocBasePrefix)) { // Trying to expand outside the docBase // Throw an exception to stop the deployment throw new IllegalArgumentException( sm.getString("expandWar.illegalPath",war, name, expandedFile.getCanonicalPath(), canonicalDocBasePrefix)); } int last = name.lastIndexOf('/'); if (last >= 0) { File parent = new File(docBase, name.substring(0, last)); if (!parent.mkdirs() && !parent.isDirectory()) { throw new IOException( sm.getString("expandWar.createFailed", parent)); } } if (name.endsWith("/")) { continue; } input = jarFile.getInputStream(jarEntry); if(null == input) throw new ZipException(sm.getString("expandWar.missingJarEntry", jarEntry.getName())); // Bugzilla 33636 expand(input, expandedFile); long lastModified = jarEntry.getTime(); if ((lastModified != -1) && (lastModified != 0)) { expandedFile.setLastModified(lastModified); } input.close(); input = null; } success = true; } catch (IOException e) { throw e; } finally { if (!success) { // If something went wrong, delete expanded dir to keep things // clean deleteDir(docBase); } if (input != null) { try { input.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } input = null; } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } } // Return the absolute path to our new document base directory return (docBase.getAbsolutePath()); }
// in java/org/apache/catalina/startup/ExpandWar.java
public static void validate(Host host, URL war, String pathname) throws IOException { File docBase = new File(host.getAppBaseFile(), pathname); // Calculate the document base directory String canonicalDocBasePrefix = docBase.getCanonicalPath(); if (!canonicalDocBasePrefix.endsWith(File.separator)) { canonicalDocBasePrefix += File.separator; } JarURLConnection juc = (JarURLConnection) war.openConnection(); juc.setUseCaches(false); JarFile jarFile = null; try { jarFile = juc.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String name = jarEntry.getName(); File expandedFile = new File(docBase, name); if (!expandedFile.getCanonicalPath().startsWith( canonicalDocBasePrefix)) { // Entry located outside the docBase // Throw an exception to stop the deployment throw new IllegalArgumentException( sm.getString("expandWar.illegalPath",war, name, expandedFile.getCanonicalPath(), canonicalDocBasePrefix)); } } } catch (IOException e) { throw e; } finally { if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } } }
// in java/org/apache/catalina/realm/RealmBase.java
Override public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce, String qop, String realm, String md5a2) { // In digest auth, digests are always lower case String md5a1 = getDigest(username, realm).toLowerCase(Locale.ENGLISH); if (md5a1 == null) return null; String serverDigestValue; if (qop == null) { serverDigestValue = md5a1 + ":" + nonce + ":" + md5a2; } else { serverDigestValue = md5a1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + md5a2; } byte[] valueBytes = null; try { valueBytes = serverDigestValue.getBytes(getDigestCharset()); } catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); } String serverDigest = null; // Bugzilla 32137 synchronized(md5Helper) { serverDigest = md5Encoder.encode(md5Helper.digest(valueBytes)); } if (log.isDebugEnabled()) { log.debug("Digest : " + clientDigest + " Username:" + username + " ClientSigest:" + clientDigest + " nonce:" + nonce + " nc:" + nc + " cnonce:" + cnonce + " qop:" + qop + " realm:" + realm + "md5a2:" + md5a2 + " Server digest:" + serverDigest); } if (serverDigest.equals(clientDigest)) { return getPrincipal(username); } return null; }
// in java/org/apache/catalina/realm/RealmBase.java
protected String digest(String credentials) { // If no MessageDigest instance is specified, return unchanged if (hasMessageDigest() == false) return (credentials); // Digest the user credentials and return as hexadecimal synchronized (this) { try { md.reset(); byte[] bytes = null; try { bytes = credentials.getBytes(getDigestCharset()); } catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); } md.update(bytes); return (HexUtils.toHexString(md.digest())); } catch (Exception e) { log.error(sm.getString("realmBase.digest"), e); return (credentials); } } }
// in java/org/apache/catalina/realm/RealmBase.java
protected String getDigest(String username, String realmName) { if (md5Helper == null) { try { md5Helper = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("Couldn't get MD5 digest: ", e); throw new IllegalStateException(e.getMessage()); } } if (hasMessageDigest()) { // Use pre-generated digest return getPassword(username); } String digestValue = username + ":" + realmName + ":" + getPassword(username); byte[] valueBytes = null; try { valueBytes = digestValue.getBytes(getDigestCharset()); } catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); } byte[] digest = null; // Bugzilla 32137 synchronized(md5Helper) { digest = md5Helper.digest(valueBytes); } return md5Encoder.encode(digest); }
// in java/org/apache/catalina/mbeans/MBeanFactory.java
public String createValve(String className, String parent) throws Exception { // Look for the parent ObjectName parentName = new ObjectName(parent); Container container = getParentContainerFromParent(parentName); if (container == null) { // TODO throw new IllegalArgumentException(); } Valve valve = (Valve) Class.forName(className).newInstance(); container.getPipeline().addValve(valve); if (valve instanceof JmxEnabled) { return ((JmxEnabled) valve).getObjectName().toString(); } else { return null; } }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
protected void createMBeans(String name, UserDatabase database) throws Exception { // Create the MBean for the UserDatabase itself if (log.isDebugEnabled()) { log.debug("Creating UserDatabase MBeans for resource " + name); log.debug("Database=" + database); } if (MBeanUtils.createMBean(database) == null) { throw new IllegalArgumentException ("Cannot create UserDatabase MBean for resource " + name); } // Create the MBeans for each defined Role Iterator<Role> roles = database.getRoles(); while (roles.hasNext()) { Role role = roles.next(); if (log.isDebugEnabled()) { log.debug(" Creating Role MBean for role " + role); } if (MBeanUtils.createMBean(role) == null) { throw new IllegalArgumentException ("Cannot create Role MBean for role " + role); } } // Create the MBeans for each defined Group Iterator<Group> groups = database.getGroups(); while (groups.hasNext()) { Group group = groups.next(); if (log.isDebugEnabled()) { log.debug(" Creating Group MBean for group " + group); } if (MBeanUtils.createMBean(group) == null) { throw new IllegalArgumentException ("Cannot create Group MBean for group " + group); } } // Create the MBeans for each defined User Iterator<User> users = database.getUsers(); while (users.hasNext()) { User user = users.next(); if (log.isDebugEnabled()) { log.debug(" Creating User MBean for user " + user); } if (MBeanUtils.createMBean(user) == null) { throw new IllegalArgumentException ("Cannot create User MBean for user " + user); } } }
// in java/org/apache/catalina/mbeans/UserMBean.java
public void addGroup(String groupname) { User user = (User) this.resource; if (user == null) { return; } Group group = user.getUserDatabase().findGroup(groupname); if (group == null) { throw new IllegalArgumentException ("Invalid group name '" + groupname + "'"); } user.addGroup(group); }
// in java/org/apache/catalina/mbeans/UserMBean.java
public void addRole(String rolename) { User user = (User) this.resource; if (user == null) { return; } Role role = user.getUserDatabase().findRole(rolename); if (role == null) { throw new IllegalArgumentException ("Invalid role name '" + rolename + "'"); } user.addRole(role); }
// in java/org/apache/catalina/mbeans/UserMBean.java
public void removeGroup(String groupname) { User user = (User) this.resource; if (user == null) { return; } Group group = user.getUserDatabase().findGroup(groupname); if (group == null) { throw new IllegalArgumentException ("Invalid group name '" + groupname + "'"); } user.removeGroup(group); }
// in java/org/apache/catalina/mbeans/UserMBean.java
public void removeRole(String rolename) { User user = (User) this.resource; if (user == null) { return; } Role role = user.getUserDatabase().findRole(rolename); if (role == null) { throw new IllegalArgumentException ("Invalid role name '" + rolename + "'"); } user.removeRole(role); }
// in java/org/apache/catalina/mbeans/GroupMBean.java
public void addRole(String rolename) { Group group = (Group) this.resource; if (group == null) { return; } Role role = group.getUserDatabase().findRole(rolename); if (role == null) { throw new IllegalArgumentException ("Invalid role name '" + rolename + "'"); } group.addRole(role); }
// in java/org/apache/catalina/mbeans/GroupMBean.java
public void removeRole(String rolename) { Group group = (Group) this.resource; if (group == null) { return; } Role role = group.getUserDatabase().findRole(rolename); if (role == null) { throw new IllegalArgumentException ("Invalid role name '" + rolename + "'"); } group.removeRole(role); }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
public String addEnvironment(String envName, String type, String value) throws MalformedObjectNameException { NamingResources nresources = (NamingResources) this.resource; if (nresources == null) { return null; } ContextEnvironment env = nresources.findEnvironment(envName); if (env != null) { throw new IllegalArgumentException ("Invalid environment name - already exists '" + envName + "'"); } env = new ContextEnvironment(); env.setName(envName); env.setType(type); env.setValue(value); nresources.addEnvironment(env); // Return the corresponding MBean name ManagedBean managed = registry.findManagedBean("ContextEnvironment"); ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), env); return (oname.toString()); }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
public String addResource(String resourceName, String type) throws MalformedObjectNameException { NamingResources nresources = (NamingResources) this.resource; if (nresources == null) { return null; } ContextResource resource = nresources.findResource(resourceName); if (resource != null) { throw new IllegalArgumentException ("Invalid resource name - already exists'" + resourceName + "'"); } resource = new ContextResource(); resource.setName(resourceName); resource.setType(type); nresources.addResource(resource); // Return the corresponding MBean name ManagedBean managed = registry.findManagedBean("ContextResource"); ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), resource); return (oname.toString()); }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
public String addResourceLink(String resourceLinkName, String type) throws MalformedObjectNameException { NamingResources nresources = (NamingResources) this.resource; if (nresources == null) { return null; } ContextResourceLink resourceLink = nresources.findResourceLink(resourceLinkName); if (resourceLink != null) { throw new IllegalArgumentException ("Invalid resource link name - already exists'" + resourceLinkName + "'"); } resourceLink = new ContextResourceLink(); resourceLink.setName(resourceLinkName); resourceLink.setType(type); nresources.addResourceLink(resourceLink); // Return the corresponding MBean name ManagedBean managed = registry.findManagedBean("ContextResourceLink"); ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), resourceLink); return (oname.toString()); }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
public void removeEnvironment(String envName) { NamingResources nresources = (NamingResources) this.resource; if (nresources == null) { return; } ContextEnvironment env = nresources.findEnvironment(envName); if (env == null) { throw new IllegalArgumentException ("Invalid environment name '" + envName + "'"); } nresources.removeEnvironment(envName); }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
public void removeResource(String resourceName) { resourceName = ObjectName.unquote(resourceName); NamingResources nresources = (NamingResources) this.resource; if (nresources == null) { return; } ContextResource resource = nresources.findResource(resourceName); if (resource == null) { throw new IllegalArgumentException ("Invalid resource name '" + resourceName + "'"); } nresources.removeResource(resourceName); }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
public void removeResourceLink(String resourceLinkName) { resourceLinkName = ObjectName.unquote(resourceLinkName); NamingResources nresources = (NamingResources) this.resource; if (nresources == null) { return; } ContextResourceLink resourceLink = nresources.findResourceLink(resourceLinkName); if (resourceLink == null) { throw new IllegalArgumentException ("Invalid resource Link name '" + resourceLinkName + "'"); } nresources.removeResourceLink(resourceLinkName); }
// in java/org/apache/catalina/filters/AddDefaultCharsetFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { super.init(filterConfig); if (encoding == null || encoding.length() == 0 || encoding.equalsIgnoreCase("default")) { encoding = DEFAULT_ENCODING; } else if (encoding.equalsIgnoreCase("system")) { encoding = Charset.defaultCharset().name(); } else if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException(sm.getString( "addDefaultCharset.unsupportedCharset", encoding)); } }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
Override public Group createGroup(String groupname, String description) { if (groupname == null || groupname.length() == 0) { String msg = sm.getString("memoryUserDatabase.nullGroup"); log.warn(msg); throw new IllegalArgumentException(msg); } MemoryGroup group = new MemoryGroup(this, groupname, description); synchronized (groups) { groups.put(group.getGroupname(), group); } return (group); }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
Override public Role createRole(String rolename, String description) { if (rolename == null || rolename.length() == 0) { String msg = sm.getString("memoryUserDatabase.nullRole"); log.warn(msg); throw new IllegalArgumentException(msg); } MemoryRole role = new MemoryRole(this, rolename, description); synchronized (roles) { roles.put(role.getRolename(), role); } return (role); }
// in java/org/apache/catalina/users/MemoryUserDatabase.java
Override public User createUser(String username, String password, String fullName) { if (username == null || username.length() == 0) { String msg = sm.getString("memoryUserDatabase.nullUser"); log.warn(msg); throw new IllegalArgumentException(msg); } MemoryUser user = new MemoryUser(this, username, password, fullName); synchronized (users) { users.put(user.getUsername(), user); } return (user); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected List<Session> getSessionsForName(ContextName cn, StringManager smClient) { if ((cn == null) || !(cn.getPath().startsWith("/") || cn.getPath().equals(""))) { String path = null; if (cn != null) { path = cn.getPath(); } throw new IllegalArgumentException(smClient.getString( "managerServlet.invalidPath", RequestUtil.filter(path))); } Context ctxt = (Context) host.findChild(cn.getName()); if (null == ctxt) { throw new IllegalArgumentException(smClient.getString( "managerServlet.noContext", RequestUtil.filter(cn.getDisplayName()))); } Manager manager = ctxt.getManager(); List<Session> sessions = new ArrayList<Session>(); sessions.addAll(Arrays.asList(manager.findSessions())); if (manager instanceof DistributedManager && showProxySessions) { // Add dummy proxy sessions Set<String> sessionIds = ((DistributedManager) manager).getSessionIdsFull(); // Remove active (primary and backup) session IDs from full list for (Session session : sessions) { sessionIds.remove(session.getId()); } // Left with just proxy sessions - add them for (String sessionId : sessionIds) { sessions.add(new DummyProxySession(sessionId)); } } return sessions; }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
Override public void addChannelListener(ChannelListener channelListener) { if (!this.channelListeners.contains(channelListener) ) { this.channelListeners.add(channelListener); } else { throw new IllegalArgumentException("Listener already exists:"+channelListener+"["+channelListener.getClass().getName()+"]"); } }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
protected synchronized void internalStart(int svc) throws ChannelException { try { boolean valid = false; //make sure we don't pass down any flags that are unrelated to the bottom layer svc = svc & Channel.DEFAULT; if (startLevel == Channel.DEFAULT) return; //we have already started up all components if (svc == 0 ) return;//nothing to start if (svc == (svc & startLevel)) throw new ChannelException("Channel already started for level:"+svc); //must start the receiver first so that we can coordinate the port it //listens to with the local membership settings if ( Channel.SND_RX_SEQ==(svc & Channel.SND_RX_SEQ) ) { clusterReceiver.setMessageListener(this); clusterReceiver.start(); //synchronize, big time FIXME membershipService.setLocalMemberProperties(getClusterReceiver().getHost(), getClusterReceiver().getPort(), getClusterReceiver().getSecurePort(), getClusterReceiver().getUdpPort()); valid = true; } if ( Channel.SND_TX_SEQ==(svc & Channel.SND_TX_SEQ) ) { clusterSender.start(); valid = true; } if ( Channel.MBR_RX_SEQ==(svc & Channel.MBR_RX_SEQ) ) { membershipService.setMembershipListener(this); if (membershipService instanceof McastService) { ((McastService)membershipService).setMessageListener(this); } membershipService.start(MembershipService.MBR_RX); valid = true; } if ( Channel.MBR_TX_SEQ==(svc & Channel.MBR_TX_SEQ) ) { membershipService.start(MembershipService.MBR_TX); valid = true; } if ( !valid) { throw new IllegalArgumentException("Invalid start level, valid levels are:SND_RX_SEQ,SND_TX_SEQ,MBR_TX_SEQ,MBR_RX_SEQ"); } startLevel = (startLevel | svc); }catch ( ChannelException cx ) { throw cx; }catch ( Exception x ) { throw new ChannelException(x); } }
// in java/org/apache/catalina/tribes/group/ChannelCoordinator.java
protected synchronized void internalStop(int svc) throws ChannelException { try { //make sure we don't pass down any flags that are unrelated to the bottom layer svc = svc & Channel.DEFAULT; if (startLevel == 0) return; //we have already stopped up all components if (svc == 0 ) return;//nothing to stop boolean valid = false; if ( Channel.SND_RX_SEQ==(svc & Channel.SND_RX_SEQ) ) { clusterReceiver.stop(); clusterReceiver.setMessageListener(null); valid = true; } if ( Channel.SND_TX_SEQ==(svc & Channel.SND_TX_SEQ) ) { clusterSender.stop(); valid = true; } if ( Channel.MBR_RX_SEQ==(svc & Channel.MBR_RX_SEQ) ) { membershipService.stop(MembershipService.MBR_RX); membershipService.setMembershipListener(null); valid = true; } if ( Channel.MBR_TX_SEQ==(svc & Channel.MBR_TX_SEQ) ) { valid = true; membershipService.stop(MembershipService.MBR_TX); } if ( !valid) { throw new IllegalArgumentException("Invalid start level, valid levels are:SND_RX_SEQ,SND_TX_SEQ,MBR_TX_SEQ,MBR_RX_SEQ"); } startLevel = (startLevel & (~svc)); }catch ( Exception x ) { throw new ChannelException(x); } finally { } }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
public static MemberImpl getMember(byte[] data, int offset, int length, MemberImpl member) { //package looks like //start package TRIBES_MBR_BEGIN.length //package length - 4 bytes //alive - 8 bytes //port - 4 bytes //secure port - 4 bytes //udp port - 4 bytes //host length - 1 byte //host - hl bytes //clen - 4 bytes //command - clen bytes //dlen - 4 bytes //domain - dlen bytes //uniqueId - 16 bytes //payload length - 4 bytes //payload plen bytes //end package TRIBES_MBR_END.length int pos = offset; if (XByteBuffer.firstIndexOf(data,offset,TRIBES_MBR_BEGIN)!=pos) { throw new IllegalArgumentException("Invalid package, should start with:"+org.apache.catalina.tribes.util.Arrays.toString(TRIBES_MBR_BEGIN)); } if ( length < (TRIBES_MBR_BEGIN.length+4) ) { throw new ArrayIndexOutOfBoundsException("Member package to small to validate."); } pos += TRIBES_MBR_BEGIN.length; int bodylength = XByteBuffer.toInt(data,pos); pos += 4; if ( length < (bodylength+4+TRIBES_MBR_BEGIN.length+TRIBES_MBR_END.length) ) { throw new ArrayIndexOutOfBoundsException("Not enough bytes in member package."); } int endpos = pos+bodylength; if (XByteBuffer.firstIndexOf(data,endpos,TRIBES_MBR_END)!=endpos) { throw new IllegalArgumentException("Invalid package, should end with:"+org.apache.catalina.tribes.util.Arrays.toString(TRIBES_MBR_END)); } byte[] alived = new byte[8]; System.arraycopy(data, pos, alived, 0, 8); pos += 8; byte[] portd = new byte[4]; System.arraycopy(data, pos, portd, 0, 4); pos += 4; byte[] sportd = new byte[4]; System.arraycopy(data, pos, sportd, 0, 4); pos += 4; byte[] uportd = new byte[4]; System.arraycopy(data, pos, uportd, 0, 4); pos += 4; byte hl = data[pos++]; byte[] addr = new byte[hl]; System.arraycopy(data, pos, addr, 0, hl); pos += hl; int cl = XByteBuffer.toInt(data, pos); pos += 4; byte[] command = new byte[cl]; System.arraycopy(data, pos, command, 0, command.length); pos += command.length; int dl = XByteBuffer.toInt(data, pos); pos += 4; byte[] domain = new byte[dl]; System.arraycopy(data, pos, domain, 0, domain.length); pos += domain.length; byte[] uniqueId = new byte[16]; System.arraycopy(data, pos, uniqueId, 0, 16); pos += 16; int pl = XByteBuffer.toInt(data, pos); pos += 4; byte[] payload = new byte[pl]; System.arraycopy(data, pos, payload, 0, payload.length); pos += payload.length; member.setHost(addr); member.setPort(XByteBuffer.toInt(portd, 0)); member.setSecurePort(XByteBuffer.toInt(sportd, 0)); member.setUdpPort(XByteBuffer.toInt(uportd, 0)); member.setMemberAliveTime(XByteBuffer.toLong(alived, 0)); member.setUniqueId(uniqueId); member.payload = payload; member.domain = domain; member.command = command; member.dataPkg = new byte[length]; System.arraycopy(data, offset, member.dataPkg, 0, length); return member; }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
public void setPayload(byte[] payload) { byte[] oldpayload = this.payload; this.payload = payload!=null?payload:new byte[0]; if ( this.getData(true,true).length > McastServiceImpl.MAX_PACKET_SIZE ) { this.payload = oldpayload; throw new IllegalArgumentException("Payload is to large for tribes to handle."); } }
// in java/org/apache/catalina/tribes/membership/McastService.java
Override public void setLocalMemberProperties(String listenHost, int listenPort, int securePort, int udpPort) { properties.setProperty("tcpListenHost",listenHost); properties.setProperty("tcpListenPort",String.valueOf(listenPort)); properties.setProperty("udpListenPort",String.valueOf(udpPort)); properties.setProperty("tcpSecurePort",String.valueOf(securePort)); try { if (localMember != null) { localMember.setHostname(listenHost); localMember.setPort(listenPort); } else { localMember = new MemberImpl(listenHost, listenPort, 0); localMember.setUniqueId(UUIDGenerator.randomUUID(true)); localMember.setPayload(getPayload()); localMember.setDomain(getDomain()); } localMember.setSecurePort(securePort); localMember.setUdpPort(udpPort); localMember.getData(true, true); }catch ( IOException x ) { throw new IllegalArgumentException(x); } }
// in java/org/apache/catalina/tribes/membership/McastService.java
protected void hasProperty(Properties properties, String name){ if ( properties.getProperty(name)==null) throw new IllegalArgumentException("McastService:Required property \""+name+"\" is missing."); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public synchronized void start(int level) throws IOException { boolean valid = false; if ( (level & Channel.MBR_RX_SEQ)==Channel.MBR_RX_SEQ ) { if ( receiver != null ) throw new IllegalStateException("McastService.receive already running."); try { if ( sender == null ) socket.joinGroup(address); }catch (IOException iox) { log.error("Unable to join multicast group, make sure your system has multicasting enabled."); throw iox; } doRunReceiver = true; receiver = new ReceiverThread(); receiver.setDaemon(true); receiver.start(); valid = true; } if ( (level & Channel.MBR_TX_SEQ)==Channel.MBR_TX_SEQ ) { if ( sender != null ) throw new IllegalStateException("McastService.send already running."); if ( receiver == null ) socket.joinGroup(address); //make sure at least one packet gets out there send(false); doRunSender = true; sender = new SenderThread(sendFrequency); sender.setDaemon(true); sender.start(); //we have started the receiver, but not yet waited for membership to establish valid = true; } if (!valid) { throw new IllegalArgumentException("Invalid start level. Only acceptable levels are Channel.MBR_RX_SEQ and Channel.MBR_TX_SEQ"); } //pause, once or twice waitForMembers(level); startLevel = (startLevel | level); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public synchronized boolean stop(int level) throws IOException { boolean valid = false; if ( (level & Channel.MBR_RX_SEQ)==Channel.MBR_RX_SEQ ) { valid = true; doRunReceiver = false; if ( receiver !=null ) receiver.interrupt(); receiver = null; } if ( (level & Channel.MBR_TX_SEQ)==Channel.MBR_TX_SEQ ) { valid = true; doRunSender = false; if ( sender != null )sender.interrupt(); sender = null; } if (!valid) { throw new IllegalArgumentException("Invalid stop level. Only acceptable levels are Channel.MBR_RX_SEQ and Channel.MBR_TX_SEQ"); } startLevel = (startLevel & (~level)); //we're shutting down, send a shutdown message and close the socket if ( startLevel == 0 ) { //send a stop message member.setCommand(Member.SHUTDOWN_PAYLOAD); member.getData(true, true); send(false); //leave mcast group try {socket.leaveGroup(address);}catch ( Exception ignore){} try {socket.close();}catch ( Exception ignore){} member.setServiceStartTime(-1); } return (startLevel == 0); }
// in java/org/apache/catalina/tribes/util/StringManager.java
public String getString(String key) { if(key == null){ String msg = "key may not have a null value"; throw new IllegalArgumentException(msg); } String str = null; try { str = bundle.getString(key); } catch(MissingResourceException mre) { //bad: shouldn't mask an exception the following way: // str = "[cannot find message associated with key '" + key + "' due to " + mre + "]"; // because it hides the fact that the String was missing // from the calling code. //good: could just throw the exception (or wrap it in another) // but that would probably cause much havoc on existing // code. //better: consistent with container pattern to // simply return null. Calling code can then do // a null check. str = null; } return str; }
// in java/org/apache/catalina/session/FileStore.java
private File directory() throws IOException { if (this.directory == null) { return (null); } if (this.directoryFile != null) { // NOTE: Race condition is harmless, so do not synchronize return (this.directoryFile); } File file = new File(this.directory); if (!file.isAbsolute()) { Container container = manager.getContainer(); if (container instanceof Context) { ServletContext servletContext = ((Context) container).getServletContext(); File work = (File) servletContext.getAttribute(ServletContext.TEMPDIR); file = new File(work, this.directory); } else { throw new IllegalArgumentException ("Parent Container is not a Context"); } } if (!file.exists() || !file.isDirectory()) { if (!file.delete() && file.exists()) { throw new IOException( sm.getString("fileStore.deleteFailed", file)); } if (!file.mkdirs() && !file.isDirectory()) { throw new IOException( sm.getString("fileStore.createFailed", file)); } } this.directoryFile = file; return (file); }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
Override public void setContainer(Container container) { if (container != null && !(container instanceof Context)) { throw new IllegalArgumentException (sm.getString("authenticator.notContext")); } super.setContainer(container); this.context = (Context) container; }
// in java/org/apache/catalina/deploy/WebXml.java
public void addAfterOrderingOthers() { if (before.contains(ORDER_OTHERS)) { throw new IllegalArgumentException(sm.getString( "webXml.multipleOther")); } after.add(ORDER_OTHERS); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addBeforeOrderingOthers() { if (after.contains(ORDER_OTHERS)) { throw new IllegalArgumentException(sm.getString( "webXml.multipleOther")); } before.add(ORDER_OTHERS); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addFilter(FilterDef filter) { if (filters.containsKey(filter.getFilterName())) { // Filter names must be unique within a web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateFilter", filter.getFilterName())); } filters.put(filter.getFilterName(), filter); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addTaglib(String uri, String location) { if (taglibs.containsKey(uri)) { // Taglib URIs must be unique within a web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateTaglibUri", uri)); } taglibs.put(uri, location); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addEnvEntry(ContextEnvironment envEntry) { if (envEntries.containsKey(envEntry.getName())) { // env-entry names must be unique within a web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateEnvEntry", envEntry.getName())); } envEntries.put(envEntry.getName(),envEntry); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addResourceRef(ContextResource resourceRef) { if (resourceRefs.containsKey(resourceRef.getName())) { // resource-ref names must be unique within a web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateResourceRef", resourceRef.getName())); } resourceRefs.put(resourceRef.getName(), resourceRef); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addResourceEnvRef(ContextResourceEnvRef resourceEnvRef) { if (resourceEnvRefs.containsKey(resourceEnvRef.getName())) { // resource-env-ref names must be unique within a web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateResourceEnvRef", resourceEnvRef.getName())); } resourceEnvRefs.put(resourceEnvRef.getName(), resourceEnvRef); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addMessageDestinationRef( MessageDestinationRef messageDestinationRef) { if (messageDestinationRefs.containsKey( messageDestinationRef.getName())) { // message-destination-ref names must be unique within a // web(-fragment).xml throw new IllegalArgumentException(sm.getString( "webXml.duplicateMessageDestinationRef", messageDestinationRef.getName())); } messageDestinationRefs.put(messageDestinationRef.getName(), messageDestinationRef); }
// in java/org/apache/catalina/deploy/WebXml.java
public void addMessageDestination( MessageDestination messageDestination) { if (messageDestinations.containsKey( messageDestination.getName())) { // message-destination names must be unique within a // web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateMessageDestination", messageDestination.getName())); } messageDestinations.put(messageDestination.getName(), messageDestination); }
// in java/org/apache/catalina/deploy/WebXml.java
public static Set<WebXml> orderWebFragments(WebXml application, Map<String,WebXml> fragments) { Set<WebXml> orderedFragments = new LinkedHashSet<WebXml>(); boolean absoluteOrdering = (application.getAbsoluteOrdering() != null); if (absoluteOrdering) { // Only those fragments listed should be processed Set<String> requestedOrder = application.getAbsoluteOrdering(); for (String requestedName : requestedOrder) { if (WebXml.ORDER_OTHERS.equals(requestedName)) { // Add all fragments not named explicitly at this point for (Entry<String, WebXml> entry : fragments.entrySet()) { if (!requestedOrder.contains(entry.getKey())) { WebXml fragment = entry.getValue(); if (fragment != null) { orderedFragments.add(fragment); } } } } else { WebXml fragment = fragments.get(requestedName); if (fragment != null) { orderedFragments.add(fragment); } else { log.warn(sm.getString("webXml.wrongFragmentName",requestedName)); } } } } else { List<String> order = new LinkedList<String>(); // Start by adding all fragments - order doesn't matter order.addAll(fragments.keySet()); // Now go through and move elements to start/end depending on if // they specify others for (WebXml fragment : fragments.values()) { String name = fragment.getName(); if (fragment.getBeforeOrdering().contains(WebXml.ORDER_OTHERS)) { // Move to beginning order.remove(name); order.add(0, name); } else if (fragment.getAfterOrdering().contains(WebXml.ORDER_OTHERS)) { // Move to end order.remove(name); order.add(name); } } // Now apply remaining ordering for (WebXml fragment : fragments.values()) { String name = fragment.getName(); for (String before : fragment.getBeforeOrdering()) { if (!before.equals(WebXml.ORDER_OTHERS) && order.contains(before) && order.indexOf(before) < order.indexOf(name)) { order.remove(name); order.add(order.indexOf(before), name); } } for (String after : fragment.getAfterOrdering()) { if (!after.equals(WebXml.ORDER_OTHERS) && order.contains(after) && order.indexOf(after) > order.indexOf(name)) { order.remove(name); order.add(order.indexOf(after) + 1, name); } } } // Finally check ordering was applied correctly - if there are // errors then that indicates circular references for (WebXml fragment : fragments.values()) { String name = fragment.getName(); for (String before : fragment.getBeforeOrdering()) { if (!before.equals(WebXml.ORDER_OTHERS) && order.contains(before) && order.indexOf(before) < order.indexOf(name)) { throw new IllegalArgumentException( sm.getString("webXml.mergeConflictOrder")); } } for (String after : fragment.getAfterOrdering()) { if (!after.equals(WebXml.ORDER_OTHERS) && order.contains(after) && order.indexOf(after) > order.indexOf(name)) { throw new IllegalArgumentException( sm.getString("webXml.mergeConflictOrder")); } } } // Build the ordered list for (String name : order) { orderedFragments.add(fragments.get(name)); } } return orderedFragments; }
// in java/org/apache/catalina/ha/session/DeltaSession.java
public void setAttribute(String name, Object value, boolean notify,boolean addDeltaRequest) { // Name cannot be null if (name == null) throw new IllegalArgumentException(sm.getString("standardSession.setAttribute.namenull")); // Null value is the same as removeAttribute() if (value == null) { removeAttribute(name); return; } try { lock(); super.setAttribute(name,value, notify); if (addDeltaRequest && deltaRequest != null && !exclude(name)) { deltaRequest.setAttribute(name, value); } } finally { unlock(); } }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
public void execute(DeltaSession session, boolean notifyListeners) { if ( !this.sessionId.equals( session.getId() ) ) throw new java.lang.IllegalArgumentException("Session id mismatch, not executing the delta request"); session.access(); for ( int i=0; i<actions.size(); i++ ) { AttributeInfo info = actions.get(i); switch ( info.getType() ) { case TYPE_ATTRIBUTE: { if ( info.getAction() == ACTION_SET ) { if ( log.isTraceEnabled() ) log.trace("Session.setAttribute('"+info.getName()+"', '"+info.getValue()+"')"); session.setAttribute(info.getName(), info.getValue(),notifyListeners,false); } else { if ( log.isTraceEnabled() ) log.trace("Session.removeAttribute('"+info.getName()+"')"); session.removeAttribute(info.getName(),notifyListeners,false); } break; }//case case TYPE_ISNEW: { if ( log.isTraceEnabled() ) log.trace("Session.setNew('"+info.getValue()+"')"); session.setNew(((Boolean)info.getValue()).booleanValue(),false); break; }//case case TYPE_MAXINTERVAL: { if ( log.isTraceEnabled() ) log.trace("Session.setMaxInactiveInterval('"+info.getValue()+"')"); session.setMaxInactiveInterval(((Integer)info.getValue()).intValue(),false); break; }//case case TYPE_PRINCIPAL: { Principal p = null; if ( info.getAction() == ACTION_SET ) { SerializablePrincipal sp = (SerializablePrincipal)info.getValue(); p = sp.getPrincipal(); } session.setPrincipal(p,false); break; }//case case TYPE_AUTHTYPE: { String authType = null; if ( info.getAction() == ACTION_SET ) { authType = (String)info.getValue(); } session.setAuthType(authType,false); break; }//case default : throw new java.lang.IllegalArgumentException("Invalid attribute info type="+info); }//switch }//for session.endAccess(); reset(); }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public boolean writeMessage(FileMessage msg) throws IllegalArgumentException, IOException { if (!openForWrite) throw new IllegalArgumentException( "Can't write message, this factory is reading."); if (log.isDebugEnabled()) log.debug("Message " + msg + " data " + HexUtils.toHexString(msg.getData()) + " data length " + msg.getDataLength() + " out " + out); if (msg.getMessageNumber() <= lastMessageProcessed.get()) { // Duplicate of message already processed log.warn("Receive Message again -- Sender ActTimeout too short [ name: " + msg.getContextName() + " war: " + msg.getFileName() + " data: " + HexUtils.toHexString(msg.getData()) + " data length: " + msg.getDataLength() + " ]"); return false; } FileMessage previous = msgBuffer.put(Long.valueOf(msg.getMessageNumber()), msg); if (previous !=null) { // Duplicate of message not yet processed log.warn("Receive Message again -- Sender ActTimeout too short [ name: " + msg.getContextName() + " war: " + msg.getFileName() + " data: " + HexUtils.toHexString(msg.getData()) + " data length: " + msg.getDataLength() + " ]"); return false; } FileMessage next = null; synchronized (this) { if (!isWriting) { next = msgBuffer.get(Long.valueOf(lastMessageProcessed.get() + 1)); if (next != null) { isWriting = true; } else { return false; } } else { return false; } } while (next != null) { out.write(next.getData(), 0, next.getDataLength()); lastMessageProcessed.incrementAndGet(); out.flush(); if (next.getMessageNumber() == next.getTotalNrOfMsgs()) { out.close(); cleanup(); return true; } synchronized(this) { next = msgBuffer.get(Long.valueOf(lastMessageProcessed.get() + 1)); if (next == null) { isWriting = false; } } } return false; }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
protected void checkState(boolean openForWrite) throws IllegalArgumentException { if (this.openForWrite != openForWrite) { cleanup(); if (openForWrite) throw new IllegalArgumentException( "Can't write message, this factory is reading."); else throw new IllegalArgumentException( "Can't read message, this factory is writing."); } if (this.closed) { cleanup(); throw new IllegalArgumentException("Factory has been closed."); } }
// in java/org/apache/catalina/ssi/SSIFsize.java
public String repeat(char aChar, int numChars) { if (numChars < 0) { throw new IllegalArgumentException("Num chars can't be negative"); } StringBuilder buf = new StringBuilder(); for (int i = 0; i < numChars; i++) { buf.append(aChar); } return buf.toString(); }
// in java/org/apache/catalina/ssi/SSIMediator.java
protected String encode(String value, String encoding) { String retVal = null; if (encoding.equalsIgnoreCase("url")) { retVal = urlEncoder.encode(value); } else if (encoding.equalsIgnoreCase("none")) { retVal = value; } else if (encoding.equalsIgnoreCase("entity")) { retVal = HttpMessages.filter(value); } else { //This shouldn't be possible throw new IllegalArgumentException("Unknown encoding: " + encoding); } return retVal; }
// in java/org/apache/catalina/connector/Connector.java
public void setParseBodyMethods(String methods) { HashSet<String> methodSet = new HashSet<String>(); if( null != methods ) { methodSet.addAll(Arrays.asList(methods.split("\\s*,\\s*"))); } if( methodSet.contains("TRACE") ) { throw new IllegalArgumentException(sm.getString("coyoteConnector.parseBodyMethodNoTrace")); } this.parseBodyMethods = methods; this.parseBodyMethodsSet = methodSet; }
// in java/org/apache/catalina/connector/Request.java
Override public void setAttribute(String name, Object value) { // Name cannot be null if (name == null) { throw new IllegalArgumentException (sm.getString("coyoteRequest.setAttribute.namenull")); } // Null value is the same as removeAttribute() if (value == null) { removeAttribute(name); return; } // Special attributes SpecialAttributeAdapter adapter = specialAttributes.get(name); if (adapter != null) { adapter.set(this, name, value); return; } // Add or replace the specified attribute // Check for read only attribute // requests are per thread so synchronization unnecessary if (readOnlyAttributes.containsKey(name)) { return; } // Do the security check before any updates are made if (Globals.IS_SECURITY_ENABLED && name.equals(Globals.SENDFILE_FILENAME_ATTR)) { // Use the canonical file name to avoid any possible symlink and // relative path issues String canonicalPath; try { canonicalPath = new File(value.toString()).getCanonicalPath(); } catch (IOException e) { throw new SecurityException(sm.getString( "coyoteRequest.sendfileNotCanonical", value), e); } // Sendfile is performed in Tomcat's security context so need to // check if the web app is permitted to access the file while still // in the web app's security context System.getSecurityManager().checkRead(canonicalPath); // Update the value so the canonical path is used value = canonicalPath; } Object oldValue = attributes.put(name, value); // Pass special attributes to the native layer if (name.startsWith("org.apache.tomcat.")) { coyoteRequest.setAttribute(name, value); } // Notify interested application event listeners notifyAttributeAssigned(name, value, oldValue); }
// in java/org/apache/catalina/connector/Request.java
Override public long getDateHeader(String name) { String value = getHeader(name); if (value == null) { return (-1L); } // Attempt to convert the date header in a variety of formats long result = FastHttpDateFormat.parseDate(value, formats); if (result != (-1L)) { return result; } throw new IllegalArgumentException(value); }
// in java/org/apache/catalina/connector/Request.java
protected String unescape(String s) { if (s==null) { return null; } if (s.indexOf('\\') == -1) { return s; } StringBuilder buf = new StringBuilder(); for (int i=0; i<s.length(); i++) { char c = s.charAt(i); if (c!='\\') { buf.append(c); } else { if (++i >= s.length()) { throw new IllegalArgumentException();//invalid escape, hence invalid cookie } c = s.charAt(i); buf.append(c); } } return buf.toString(); }
// in java/org/apache/catalina/connector/Response.java
private void normalize(CharChunk cc) { if (cc.endsWith("/.") || cc.endsWith("/..")) { try { cc.append('/'); } catch (IOException e) { throw new IllegalArgumentException(cc.toString(), e); } } char[] c = cc.getChars(); int start = cc.getStart(); int end = cc.getEnd(); int index = 0; int startIndex = 0; // Advance past the first three / characters (should place index just // scheme://host[:port] for (int i = 0; i < 3; i++) { startIndex = cc.indexOf('/', startIndex + 1); } // Remove /./ index = startIndex; while (true) { index = cc.indexOf("/./", 0, 3, index); if (index < 0) { break; } copyChars(c, start + index, start + index + 2, end - start - index - 2); end = end - 2; cc.setEnd(end); } // Remove /../ index = startIndex; int pos; while (true) { index = cc.indexOf("/../", 0, 4, index); if (index < 0) { break; } // Prevent from going outside our context if (index == startIndex) { throw new IllegalArgumentException(); } int index2 = -1; for (pos = start + index - 1; (pos >= 0) && (index2 < 0); pos --) { if (c[pos] == (byte) '/') { index2 = pos; } } copyChars(c, start + index2, start + index + 3, end - start - index - 3); end = end + index2 - index - 3; cc.setEnd(end); index = index2; }
// in java/org/apache/catalina/connector/InputBuffer.java
Override public long skip(long n) throws IOException { if (closed) { throw new IOException(sm.getString("inputBuffer.streamClosed")); } if (n < 0) { throw new IllegalArgumentException(); } long nRead = 0; while (nRead < n) { if (cb.getLength() >= n) { cb.setOffset(cb.getStart() + (int) n); nRead = n; } else { nRead += cb.getLength(); cb.setOffset(cb.getEnd()); int toRead = 0; if (cb.getChars().length < (n - nRead)) { toRead = cb.getChars().length; } else { toRead = (int) (n - nRead); } int nb = realReadChars(cb.getChars(), 0, toRead); if (nb < 0) { break; } } } return nRead; }
// in java/org/apache/catalina/core/ApplicationFilterRegistration.java
Override public boolean setInitParameter(String name, String value) { if (name == null || value == null) { throw new IllegalArgumentException( sm.getString("applicationFilterRegistration.nullInitParam", name, value)); } if (getInitParameter(name) != null) { return false; } filterDef.addInitParameter(name, value); return true; }
// in java/org/apache/catalina/core/ApplicationFilterRegistration.java
Override public Set<String> setInitParameters(Map<String, String> initParameters) { Set<String> conflicts = new HashSet<String>(); for (Map.Entry<String, String> entry : initParameters.entrySet()) { if (entry.getKey() == null || entry.getValue() == null) { throw new IllegalArgumentException(sm.getString( "applicationFilterRegistration.nullInitParams", entry.getKey(), entry.getValue())); } if (getInitParameter(entry.getKey()) != null) { conflicts.add(entry.getKey()); } } // Have to add in a separate loop since spec requires no updates at all // if there is an issue for (Map.Entry<String, String> entry : initParameters.entrySet()) { setInitParameter(entry.getKey(), entry.getValue()); } return conflicts; }
// in java/org/apache/catalina/core/StandardHost.java
Override public void setName(String name) { if (name == null) throw new IllegalArgumentException (sm.getString("standardHost.nullName")); name = name.toLowerCase(Locale.ENGLISH); // Internally all names are lower case String oldName = this.name; this.name = name; support.firePropertyChange("name", oldName, this.name); }
// in java/org/apache/catalina/core/StandardHost.java
Override public void addChild(Container child) { child.addLifecycleListener(new MemoryLeakTrackingListener()); if (!(child instanceof Context)) throw new IllegalArgumentException (sm.getString("standardHost.notContext")); super.addChild(child); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public RequestDispatcher getRequestDispatcher(String path) { // Validate the path argument if (path == null) return (null); if (!path.startsWith("/")) throw new IllegalArgumentException (sm.getString ("applicationContext.requestDispatcher.iae", path)); // Get query string String queryString = null; String normalizedPath = path; int pos = normalizedPath.indexOf('?'); if (pos >= 0) { queryString = normalizedPath.substring(pos + 1); normalizedPath = normalizedPath.substring(0, pos); } normalizedPath = RequestUtil.normalize(normalizedPath); if (normalizedPath == null) return (null); pos = normalizedPath.length(); // Use the thread local URI and mapping data DispatchData dd = dispatchData.get(); if (dd == null) { dd = new DispatchData(); dispatchData.set(dd); } MessageBytes uriMB = dd.uriMB; uriMB.recycle(); // Use the thread local mapping data MappingData mappingData = dd.mappingData; // Map the URI CharChunk uriCC = uriMB.getCharChunk(); try { uriCC.append(context.getPath(), 0, context.getPath().length()); /* * Ignore any trailing path params (separated by ';') for mapping * purposes */ int semicolon = normalizedPath.indexOf(';'); if (pos >= 0 && semicolon > pos) { semicolon = -1; } uriCC.append(normalizedPath, 0, semicolon > 0 ? semicolon : pos); context.getMapper().map(uriMB, mappingData); if (mappingData.wrapper == null) { return (null); } /* * Append any trailing path params (separated by ';') that were * ignored for mapping purposes, so that they're reflected in the * RequestDispatcher's requestURI */ if (semicolon > 0) { uriCC.append(normalizedPath, semicolon, pos - semicolon); } } catch (Exception e) { // Should never happen log(sm.getString("applicationContext.mapping.error"), e); return (null); } Wrapper wrapper = (Wrapper) mappingData.wrapper; String wrapperPath = mappingData.wrapperPath.toString(); String pathInfo = mappingData.pathInfo.toString(); mappingData.recycle(); // Construct a RequestDispatcher to process this request return new ApplicationDispatcher (wrapper, uriCC.toString(), wrapperPath, pathInfo, queryString, null); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public Set<String> getResourcePaths(String path) { // Validate the path argument if (path == null) { return null; } if (!path.startsWith("/")) { throw new IllegalArgumentException (sm.getString("applicationContext.resourcePaths.iae", path)); } String normalizedPath = RequestUtil.normalize(path); if (normalizedPath == null) return (null); DirContext resources = context.getResources(); if (resources != null) { return (getResourcePathsInternal(resources, normalizedPath)); } return (null); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public void setAttribute(String name, Object value) { // Name cannot be null if (name == null) throw new IllegalArgumentException (sm.getString("applicationContext.setAttribute.namenull")); // Null value is the same as removeAttribute() if (value == null) { removeAttribute(name); return; } Object oldValue = null; boolean replaced = false; // Add or replace the specified attribute // Check for read only attribute if (readOnlyAttributes.containsKey(name)) return; oldValue = attributes.get(name); if (oldValue != null) replaced = true; attributes.put(name, value); // Notify interested application event listeners Object listeners[] = context.getApplicationEventListeners(); if ((listeners == null) || (listeners.length == 0)) return; ServletContextAttributeEvent event = null; if (replaced) event = new ServletContextAttributeEvent(context.getServletContext(), name, oldValue); else event = new ServletContextAttributeEvent(context.getServletContext(), name, value); for (int i = 0; i < listeners.length; i++) { if (!(listeners[i] instanceof ServletContextAttributeListener)) continue; ServletContextAttributeListener listener = (ServletContextAttributeListener) listeners[i]; try { if (replaced) { context.fireContainerEvent ("beforeContextAttributeReplaced", listener); listener.attributeReplaced(event); context.fireContainerEvent("afterContextAttributeReplaced", listener); } else { context.fireContainerEvent("beforeContextAttributeAdded", listener); listener.attributeAdded(event); context.fireContainerEvent("afterContextAttributeAdded", listener); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (replaced) context.fireContainerEvent("afterContextAttributeReplaced", listener); else context.fireContainerEvent("afterContextAttributeAdded", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); } } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public void setSessionTrackingModes( Set<SessionTrackingMode> sessionTrackingModes) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException( sm.getString("applicationContext.setSessionTracking.ise", getContextPath())); } // Check that only supported tracking modes have been requested for (SessionTrackingMode sessionTrackingMode : sessionTrackingModes) { if (!supportedSessionTrackingModes.contains(sessionTrackingMode)) { throw new IllegalArgumentException(sm.getString( "applicationContext.setSessionTracking.iae.invalid", sessionTrackingMode.toString(), getContextPath())); } } // Check SSL has not be configured with anything else if (sessionTrackingModes.contains(SessionTrackingMode.SSL)) { if (sessionTrackingModes.size() > 1) { throw new IllegalArgumentException(sm.getString( "applicationContext.setSessionTracking.iae.ssl", getContextPath())); } } this.sessionTrackingModes = sessionTrackingModes; }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public void addListener(Class<? extends EventListener> listenerClass) { EventListener listener; try { listener = createListener(listenerClass); } catch (ServletException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.init", listenerClass.getName()), e); } addListener(listener); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public void addListener(String className) { try { Object obj = context.getInstanceManager().newInstance(className); if (!(obj instanceof EventListener)) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", className)); } EventListener listener = (EventListener) obj; addListener(listener); } catch (IllegalAccessException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (NamingException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (InstantiationException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends EventListener> void addListener(T t) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException( sm.getString("applicationContext.addListener.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. boolean match = false; if (t instanceof ServletContextAttributeListener || t instanceof ServletRequestListener || t instanceof ServletRequestAttributeListener || t instanceof HttpSessionAttributeListener) { context.addApplicationEventListener(t); match = true; } if (t instanceof HttpSessionListener || (t instanceof ServletContextListener && newServletContextListenerAllowed)) { context.addApplicationLifecycleListener(t); match = true; } if (match) return; if (t instanceof ServletContextListener) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.sclNotAllowed", t.getClass().getName())); } else { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", t.getClass().getName())); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends EventListener> T createListener(Class<T> c) throws ServletException { try { @SuppressWarnings("unchecked") T listener = (T) context.getInstanceManager().newInstance(c.getName()); if (listener instanceof ServletContextListener || listener instanceof ServletContextAttributeListener || listener instanceof ServletRequestListener || listener instanceof ServletRequestAttributeListener || listener instanceof HttpSessionListener || listener instanceof HttpSessionAttributeListener) { return listener; } throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", listener.getClass().getName())); } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public void declareRoles(String... roleNames) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addRole.ise", getContextPath())); } if (roleNames == null) { throw new IllegalArgumentException( sm.getString("applicationContext.roles.iae", getContextPath())); } for (String role : roleNames) { if (role == null || "".equals(role)) { throw new IllegalArgumentException( sm.getString("applicationContext.role.iae", getContextPath())); } context.addSecurityRole(role); } }
// in java/org/apache/catalina/core/ContainerBase.java
private void addChildInternal(Container child) { if( log.isDebugEnabled() ) log.debug("Add child " + child + " " + this); synchronized(children) { if (children.get(child.getName()) != null) throw new IllegalArgumentException("addChild: Child name '" + child.getName() + "' is not unique"); child.setParent(this); // May throw IAE children.put(child.getName(), child); } // Start child // Don't do this inside sync block - start can be a slow process and // locking the children object can cause problems elsewhere if ((getState().isAvailable() || LifecycleState.STARTING_PREP.equals(getState())) && startChildren) { try { child.start(); } catch (LifecycleException e) { log.error("ContainerBase.addChild: start: ", e); throw new IllegalStateException ("ContainerBase.addChild: start: " + e); } } fireContainerEvent(ADD_CHILD_EVENT, child); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected void populateAnnotationsCache(Class<?> clazz, Map<String, String> injections) throws IllegalAccessException, InvocationTargetException, NamingException { List<AnnotationCacheEntry> annotations = null; while (clazz != null) { AnnotationCacheEntry[] annotationsArray = null; synchronized (annotationCache) { annotationsArray = annotationCache.get(clazz); } if (annotationsArray == null) { if (annotations == null) { annotations = new ArrayList<AnnotationCacheEntry>(); } else { annotations.clear(); } if (context != null) { // Initialize fields annotations for resource injection if // JNDI is enabled Field[] fields = null; if (Globals.IS_SECURITY_ENABLED) { final Class<?> clazz2 = clazz; fields = AccessController.doPrivileged( new PrivilegedAction<Field[]>(){ @Override public Field[] run(){ return clazz2.getDeclaredFields(); } }); } else { fields = clazz.getDeclaredFields(); } for (Field field : fields) { if (injections != null && injections.containsKey(field.getName())) { annotations.add(new AnnotationCacheEntry( field.getName(), null, injections.get(field.getName()), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(Resource.class)) { Resource annotation = field.getAnnotation(Resource.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(EJB.class)) { EJB annotation = field.getAnnotation(EJB.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(WebServiceRef.class)) { WebServiceRef annotation = field.getAnnotation(WebServiceRef.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(PersistenceContext.class)) { PersistenceContext annotation = field.getAnnotation(PersistenceContext.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(PersistenceUnit.class)) { PersistenceUnit annotation = field.getAnnotation(PersistenceUnit.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } } } // Initialize methods annotations Method[] methods = null; if (Globals.IS_SECURITY_ENABLED) { final Class<?> clazz2 = clazz; methods = AccessController.doPrivileged( new PrivilegedAction<Method[]>(){ @Override public Method[] run(){ return clazz2.getDeclaredMethods(); } }); } else { methods = clazz.getDeclaredMethods(); } Method postConstruct = null; Method preDestroy = null; for (Method method : methods) { String methodName = method.getName(); if (context != null) { // Resource injection only if JNDI is enabled if (injections != null && methodName.startsWith("set") && methodName.length() > 3) { String fieldName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); if (injections.containsKey(fieldName)) { annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), injections.get(method.getName()), AnnotationCacheEntryType.SETTER)); break; } } if (method.isAnnotationPresent(Resource.class)) { Resource annotation = method.getAnnotation(Resource.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(EJB.class)) { EJB annotation = method.getAnnotation(EJB.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(WebServiceRef.class)) { WebServiceRef annotation = method.getAnnotation(WebServiceRef.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(PersistenceContext.class)) { PersistenceContext annotation = method.getAnnotation(PersistenceContext.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(PersistenceUnit.class)) { PersistenceUnit annotation = method.getAnnotation(PersistenceUnit.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } } if (method.isAnnotationPresent(PostConstruct.class)) { if ((postConstruct != null) || (method.getParameterTypes().length != 0) || (Modifier.isStatic(method.getModifiers())) || (method.getExceptionTypes().length > 0) || (!method.getReturnType().getName().equals("void"))) { throw new IllegalArgumentException( "Invalid PostConstruct annotation"); } postConstruct = method; } if (method.isAnnotationPresent(PreDestroy.class)) { if ((preDestroy != null || method.getParameterTypes().length != 0) || (Modifier.isStatic(method.getModifiers())) || (method.getExceptionTypes().length > 0) || (!method.getReturnType().getName().equals("void"))) { throw new IllegalArgumentException( "Invalid PreDestroy annotation"); } preDestroy = method; } } if (postConstruct != null) { annotations.add(new AnnotationCacheEntry( postConstruct.getName(), postConstruct.getParameterTypes(), null, AnnotationCacheEntryType.POST_CONSTRUCT)); } if (preDestroy != null) { annotations.add(new AnnotationCacheEntry( preDestroy.getName(), preDestroy.getParameterTypes(), null, AnnotationCacheEntryType.PRE_DESTROY)); } if (annotations.isEmpty()) { // Use common object to save memory annotationsArray = ANNOTATIONS_EMPTY; } else { annotationsArray = annotations.toArray( new AnnotationCacheEntry[annotations.size()]); } synchronized (annotationCache) { annotationCache.put(clazz, annotationsArray); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected static void lookupMethodResource(Context context, Object instance, Method method, String name, Class<?> clazz) throws NamingException, IllegalAccessException, InvocationTargetException { if (!method.getName().startsWith("set") || method.getName().length() < 4 || method.getParameterTypes().length != 1 || !method.getReturnType().getName().equals("void")) { throw new IllegalArgumentException("Invalid method resource injection annotation"); } Object lookedupResource; boolean accessibility; String normalizedName = normalize(name); if ((normalizedName != null) && (normalizedName.length() > 0)) { lookedupResource = context.lookup(normalizedName); } else { lookedupResource = context.lookup( clazz.getName() + "/" + getName(method)); } synchronized (method) { accessibility = method.isAccessible(); method.setAccessible(true); method.invoke(instance, lookedupResource); method.setAccessible(accessibility); } }
// in java/org/apache/catalina/core/NamingContextListener.java
public void addEnvironment(ContextEnvironment env) { Object value = null; // Instantiating a new instance of the correct object type, and // initializing it. String type = env.getType(); try { if (type.equals("java.lang.String")) { value = env.getValue(); } else if (type.equals("java.lang.Byte")) { if (env.getValue() == null) { value = Byte.valueOf((byte) 0); } else { value = Byte.decode(env.getValue()); } } else if (type.equals("java.lang.Short")) { if (env.getValue() == null) { value = Short.valueOf((short) 0); } else { value = Short.decode(env.getValue()); } } else if (type.equals("java.lang.Integer")) { if (env.getValue() == null) { value = Integer.valueOf(0); } else { value = Integer.decode(env.getValue()); } } else if (type.equals("java.lang.Long")) { if (env.getValue() == null) { value = Long.valueOf(0); } else { value = Long.decode(env.getValue()); } } else if (type.equals("java.lang.Boolean")) { value = Boolean.valueOf(env.getValue()); } else if (type.equals("java.lang.Double")) { if (env.getValue() == null) { value = Double.valueOf(0); } else { value = Double.valueOf(env.getValue()); } } else if (type.equals("java.lang.Float")) { if (env.getValue() == null) { value = Float.valueOf(0); } else { value = Float.valueOf(env.getValue()); } } else if (type.equals("java.lang.Character")) { if (env.getValue() == null) { value = Character.valueOf((char) 0); } else { if (env.getValue().length() == 1) { value = Character.valueOf(env.getValue().charAt(0)); } else { throw new IllegalArgumentException(); } } } else { logger.error(sm.getString("naming.invalidEnvEntryType", env.getName())); } } catch (NumberFormatException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", env.getName())); } catch (IllegalArgumentException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", env.getName())); } // Binding the object to the appropriate name if (value != null) { try { if (logger.isDebugEnabled()) logger.debug(" Adding environment entry " + env.getName()); createSubcontexts(envCtx, env.getName()); envCtx.bind(env.getName(), value); } catch (NamingException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", e)); } } }
// in java/org/apache/catalina/core/StandardContext.java
Override public void setLoginConfig(LoginConfig config) { // Validate the incoming property value if (config == null) throw new IllegalArgumentException (sm.getString("standardContext.loginConfig.required")); String loginPage = config.getLoginPage(); if ((loginPage != null) && !loginPage.startsWith("/")) { if (isServlet22()) { if(log.isDebugEnabled()) log.debug(sm.getString("standardContext.loginConfig.loginWarning", loginPage)); config.setLoginPage("/" + loginPage); } else { throw new IllegalArgumentException (sm.getString("standardContext.loginConfig.loginPage", loginPage)); } } String errorPage = config.getErrorPage(); if ((errorPage != null) && !errorPage.startsWith("/")) { if (isServlet22()) { if(log.isDebugEnabled()) log.debug(sm.getString("standardContext.loginConfig.errorWarning", errorPage)); config.setErrorPage("/" + errorPage); } else { throw new IllegalArgumentException (sm.getString("standardContext.loginConfig.errorPage", errorPage)); } } // Process the property setting change LoginConfig oldLoginConfig = this.loginConfig; this.loginConfig = config; support.firePropertyChange("loginConfig", oldLoginConfig, this.loginConfig); }
// in java/org/apache/catalina/core/StandardContext.java
Override public void setWrapperClass(String wrapperClassName) { this.wrapperClassName = wrapperClassName; try { wrapperClass = Class.forName(wrapperClassName); if (!StandardWrapper.class.isAssignableFrom(wrapperClass)) { throw new IllegalArgumentException( sm.getString("standardContext.invalidWrapperClass", wrapperClassName)); } } catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException(cnfe.getMessage()); } }
// in java/org/apache/catalina/core/StandardContext.java
Override public void addChild(Container child) { // Global JspServlet Wrapper oldJspServlet = null; if (!(child instanceof Wrapper)) { throw new IllegalArgumentException (sm.getString("standardContext.notWrapper")); } boolean isJspServlet = "jsp".equals(child.getName()); // Allow webapp to override JspServlet inherited from global web.xml. if (isJspServlet) { oldJspServlet = (Wrapper) findChild("jsp"); if (oldJspServlet != null) { removeChild(oldJspServlet); } } super.addChild(child); if (isJspServlet && oldJspServlet != null) { /* * The webapp-specific JspServlet inherits all the mappings * specified in the global web.xml, and may add additional ones. */ String[] jspMappings = oldJspServlet.findMappings(); for (int i=0; jspMappings!=null && i<jspMappings.length; i++) { addServletMapping(jspMappings[i], child.getName()); } } }
// in java/org/apache/catalina/core/StandardContext.java
Override public void addConstraint(SecurityConstraint constraint) { // Validate the proposed constraint SecurityCollection collections[] = constraint.findCollections(); for (int i = 0; i < collections.length; i++) { String patterns[] = collections[i].findPatterns(); for (int j = 0; j < patterns.length; j++) { patterns[j] = adjustURLPattern(patterns[j]); if (!validateURLPattern(patterns[j])) throw new IllegalArgumentException (sm.getString ("standardContext.securityConstraint.pattern", patterns[j])); } if (collections[i].findMethods().length > 0 && collections[i].findOmittedMethods().length > 0) { throw new IllegalArgumentException(sm.getString( "standardContext.securityConstraint.mixHttpMethod")); } } // Add this constraint to the set for our web application synchronized (constraintsLock) { SecurityConstraint results[] = new SecurityConstraint[constraints.length + 1]; for (int i = 0; i < constraints.length; i++) results[i] = constraints[i]; results[constraints.length] = constraint; constraints = results; } }
// in java/org/apache/catalina/core/StandardContext.java
Override public void addErrorPage(ErrorPage errorPage) { // Validate the input parameters if (errorPage == null) throw new IllegalArgumentException (sm.getString("standardContext.errorPage.required")); String location = errorPage.getLocation(); if ((location != null) && !location.startsWith("/")) { if (isServlet22()) { if(log.isDebugEnabled()) log.debug(sm.getString("standardContext.errorPage.warning", location)); errorPage.setLocation("/" + location); } else { throw new IllegalArgumentException (sm.getString("standardContext.errorPage.error", location)); } } // Add the specified error page to our internal collections String exceptionType = errorPage.getExceptionType(); if (exceptionType != null) { synchronized (exceptionPages) { exceptionPages.put(exceptionType, errorPage); } } else { synchronized (statusPages) { if (errorPage.getErrorCode() == 200) { this.okErrorPage = errorPage; } statusPages.put(Integer.valueOf(errorPage.getErrorCode()), errorPage); } } fireContainerEvent("addErrorPage", errorPage); }
// in java/org/apache/catalina/core/StandardContext.java
private void validateFilterMap(FilterMap filterMap) { // Validate the proposed filter mapping String filterName = filterMap.getFilterName(); String[] servletNames = filterMap.getServletNames(); String[] urlPatterns = filterMap.getURLPatterns(); if (findFilterDef(filterName) == null) throw new IllegalArgumentException (sm.getString("standardContext.filterMap.name", filterName)); if (!filterMap.getMatchAllServletNames() && !filterMap.getMatchAllUrlPatterns() && (servletNames.length == 0) && (urlPatterns.length == 0)) throw new IllegalArgumentException (sm.getString("standardContext.filterMap.either")); // FIXME: Older spec revisions may still check this /* if ((servletNames.length != 0) && (urlPatterns.length != 0)) throw new IllegalArgumentException (sm.getString("standardContext.filterMap.either")); */ for (int i = 0; i < urlPatterns.length; i++) { if (!validateURLPattern(urlPatterns[i])) { throw new IllegalArgumentException (sm.getString("standardContext.filterMap.pattern", urlPatterns[i])); } } }
// in java/org/apache/catalina/core/StandardContext.java
Override public void addParameter(String name, String value) { // Validate the proposed context initialization parameter if ((name == null) || (value == null)) throw new IllegalArgumentException (sm.getString("standardContext.parameter.required")); if (parameters.get(name) != null) throw new IllegalArgumentException (sm.getString("standardContext.parameter.duplicate", name)); // Add this parameter to our defined set synchronized (parameters) { parameters.put(name, value); } fireContainerEvent("addParameter", name); }
// in java/org/apache/catalina/core/StandardContext.java
Override public void addServletMapping(String pattern, String name, boolean jspWildCard) { // Validate the proposed mapping if (findChild(name) == null) throw new IllegalArgumentException (sm.getString("standardContext.servletMap.name", name)); String decodedPattern = adjustURLPattern(RequestUtil.URLDecode(pattern)); if (!validateURLPattern(decodedPattern)) throw new IllegalArgumentException (sm.getString("standardContext.servletMap.pattern", decodedPattern)); // Add this mapping to our registered set synchronized (servletMappingsLock) { String name2 = servletMappings.get(decodedPattern); if (name2 != null) { // Don't allow more than one servlet on the same pattern Wrapper wrapper = (Wrapper) findChild(name2); wrapper.removeMapping(decodedPattern); mapper.removeWrapper(decodedPattern); } servletMappings.put(decodedPattern, name); } Wrapper wrapper = (Wrapper) findChild(name); wrapper.addMapping(decodedPattern); // Update context mapper mapper.addWrapper(decodedPattern, wrapper, jspWildCard, resourceOnlyServlets.contains(name)); fireContainerEvent("addServletMapping", decodedPattern); }
// in java/org/apache/catalina/core/StandardContext.java
Override public void removeChild(Container child) { if (!(child instanceof Wrapper)) { throw new IllegalArgumentException (sm.getString("standardContext.notWrapper")); } super.removeChild(child); }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public void setParent(Container container) { if ((container != null) && !(container instanceof Context)) throw new IllegalArgumentException (sm.getString("standardWrapper.notContext")); if (container instanceof StandardContext) { swallowOutput = ((StandardContext)container).getSwallowOutput(); unloadDelay = ((StandardContext)container).getUnloadDelay(); } super.setParent(container); }
// in java/org/apache/catalina/core/ApplicationServletRegistration.java
Override public boolean setInitParameter(String name, String value) { if (name == null || value == null) { throw new IllegalArgumentException( sm.getString("applicationFilterRegistration.nullInitParam", name, value)); } if (getInitParameter(name) != null) { return false; } wrapper.addInitParameter(name, value); return true; }
// in java/org/apache/catalina/core/ApplicationServletRegistration.java
Override public Set<String> setInitParameters(Map<String, String> initParameters) { Set<String> conflicts = new HashSet<String>(); for (Map.Entry<String, String> entry : initParameters.entrySet()) { if (entry.getKey() == null || entry.getValue() == null) { throw new IllegalArgumentException(sm.getString( "applicationFilterRegistration.nullInitParams", entry.getKey(), entry.getValue())); } if (getInitParameter(entry.getKey()) != null) { conflicts.add(entry.getKey()); } } // Have to add in a separate loop since spec requires no updates at all // if there is an issue if (conflicts.isEmpty()) { for (Map.Entry<String, String> entry : initParameters.entrySet()) { setInitParameter(entry.getKey(), entry.getValue()); } } return conflicts; }
// in java/org/apache/catalina/core/ApplicationServletRegistration.java
Override public Set<String> setServletSecurity(ServletSecurityElement constraint) { if (constraint == null) { throw new IllegalArgumentException(sm.getString( "applicationServletRegistration.setServletSecurity.iae", getName(), context.getName())); } if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException(sm.getString( "applicationServletRegistration.setServletSecurity.ise", getName(), context.getName())); } return context.addServletSecurity(this, constraint); }
// in java/org/apache/catalina/core/StandardEngine.java
Override public void addChild(Container child) { if (!(child instanceof Host)) throw new IllegalArgumentException (sm.getString("standardEngine.notHost")); super.addChild(child); }
// in java/org/apache/catalina/core/StandardEngine.java
Override public void setParent(Container container) { throw new IllegalArgumentException (sm.getString("standardEngine.notParent")); }
// in java/org/apache/catalina/util/RequestUtil.java
public static String URLDecode(byte[] bytes, String enc, boolean isQuery) { if (bytes == null) return null; int len = bytes.length; int ix = 0; int ox = 0; while (ix < len) { byte b = bytes[ix++]; // Get byte to test if (b == '+' && isQuery) { b = (byte)' '; } else if (b == '%') { if (ix + 2 > len) { throw new IllegalArgumentException( sm.getString("requestUtil.urlDecode.missingDigit")); } b = (byte) ((convertHexDigit(bytes[ix++]) << 4) + convertHexDigit(bytes[ix++])); } bytes[ox++] = b; } if (enc != null) { try { return new String(bytes, 0, ox, B2CConverter.getCharset(enc)); } catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee); } return null; } } return new String(bytes, 0, ox); }
// in java/org/apache/catalina/util/RequestUtil.java
private static byte convertHexDigit( byte b ) { if ((b >= '0') && (b <= '9')) return (byte)(b - '0'); if ((b >= 'a') && (b <= 'f')) return (byte)(b - 'a' + 10); if ((b >= 'A') && (b <= 'F')) return (byte)(b - 'A' + 10); throw new IllegalArgumentException( sm.getString("requestUtil.convertHexDigit.notHex", Character.valueOf((char)b))); }
// in java/javax/servlet/http/HttpUtils.java
public static Hashtable<String,String[]> parsePostData(int len, ServletInputStream in) { // XXX // should a length of 0 be an IllegalArgumentException // cheap hack to return an empty hash if (len <=0) return new Hashtable<String,String[]>(); if (in == null) { throw new IllegalArgumentException(); } // Make sure we read the entire POSTed body. byte[] postedBytes = new byte [len]; try { int offset = 0; do { int inputLen = in.read (postedBytes, offset, len - offset); if (inputLen <= 0) { String msg = lStrings.getString("err.io.short_read"); throw new IllegalArgumentException (msg); } offset += inputLen; } while ((len - offset) > 0); } catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); } // XXX we shouldn't assume that the only kind of POST body // is FORM data encoded using ASCII or ISO Latin/1 ... or // that the body should always be treated as FORM data. try { String postedBody = new String(postedBytes, 0, len, "8859_1"); return parseQueryString(postedBody); } catch (java.io.UnsupportedEncodingException e) { // XXX function should accept an encoding parameter & throw this // exception. Otherwise throw something expected. throw new IllegalArgumentException(e.getMessage(), e); } }
// in java/javax/servlet/http/HttpUtils.java
private static String parseName(String s, StringBuilder sb) { sb.setLength(0); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '+': sb.append(' '); break; case '%': try { sb.append((char) Integer.parseInt(s.substring(i+1, i+3), 16)); i += 2; } catch (NumberFormatException e) { // XXX // need to be more specific about illegal arg throw new IllegalArgumentException(); } catch (StringIndexOutOfBoundsException e) { String rest = s.substring(i); sb.append(rest); if (rest.length()==2) i++; } break; default: sb.append(c); break; } } return sb.toString(); }
// in java/javax/servlet/ServletResponseWrapper.java
public void setResponse(ServletResponse response) { if (response == null) { throw new IllegalArgumentException("Response cannot be null"); } this.response = response; }
// in java/javax/servlet/ServletSecurityElement.java
private void addHttpMethodConstraints( Collection<HttpMethodConstraintElement> httpMethodConstraints) { if (httpMethodConstraints == null) { return; } for (HttpMethodConstraintElement constraint : httpMethodConstraints) { String method = constraint.getMethodName(); if (methodConstraints.containsKey(method)) { throw new IllegalArgumentException( "Duplicate method name: " + method); } methodConstraints.put(method, constraint); } }
// in java/javax/servlet/ServletRequestWrapper.java
public void setRequest(ServletRequest request) { if (request == null) { throw new IllegalArgumentException("Request cannot be null"); } this.request = request; }
// in java/javax/el/ArrayELResolver.java
private static final int coerce(Object property) { if (property instanceof Number) { return ((Number) property).intValue(); } if (property instanceof Character) { return ((Character) property).charValue(); } if (property instanceof Boolean) { return (((Boolean) property).booleanValue() ? 1 : 0); } if (property instanceof String) { return Integer.parseInt((String) property); } throw new IllegalArgumentException(property != null ? property.toString() : "null"); }
// in java/javax/el/ListELResolver.java
private static final int coerce(Object property) { if (property instanceof Number) { return ((Number) property).intValue(); } if (property instanceof Character) { return ((Character) property).charValue(); } if (property instanceof Boolean) { return (((Boolean) property).booleanValue() ? 1 : 0); } if (property instanceof String) { return Integer.parseInt((String) property); } throw new IllegalArgumentException(property != null ? property.toString() : "null"); }
19
            
// in java/org/apache/naming/resources/WARDirContext.java
catch (Exception e) { throw new IllegalArgumentException (sm.getString("warResources.invalidWar", e.getMessage())); }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (Exception e) { throw new IllegalArgumentException(sm.getString( "resources.invalidCache", cacheClassName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IOException ioe) { throw new IllegalArgumentException( sm.getString("webappClassLoader.validationErrorJarPath", jarEntry2.getName()), ioe); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/tribes/membership/McastService.java
catch ( IOException x ) { throw new IllegalArgumentException(x); }
// in java/org/apache/catalina/connector/Response.java
catch (IOException e) { throw new IllegalArgumentException(cc.toString(), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ServletException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.init", listenerClass.getName()), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException(cnfe.getMessage()); }
// in java/org/apache/catalina/util/CharsetMapper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new IllegalArgumentException(t.toString()); }
// in java/javax/servlet/http/HttpUtils.java
catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); }
// in java/javax/servlet/http/HttpUtils.java
catch (java.io.UnsupportedEncodingException e) { // XXX function should accept an encoding parameter & throw this // exception. Otherwise throw something expected. throw new IllegalArgumentException(e.getMessage(), e); }
// in java/javax/servlet/http/HttpUtils.java
catch (NumberFormatException e) { // XXX // need to be more specific about illegal arg throw new IllegalArgumentException(); }
9
            
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) throws IOException, IllegalStateException, IllegalArgumentException { }
// in java/org/apache/tomcat/util/modeler/BaseNotificationBroadcaster.java
Override public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException { synchronized (entries) { // Optimization to coalesce attribute name filters if (filter instanceof BaseAttributeFilter) { BaseAttributeFilter newFilter = (BaseAttributeFilter) filter; Iterator<BaseNotificationBroadcasterEntry> items = entries.iterator(); while (items.hasNext()) { BaseNotificationBroadcasterEntry item = items.next(); if ((item.listener == listener) && (item.filter != null) && (item.filter instanceof BaseAttributeFilter) && (item.handback == handback)) { BaseAttributeFilter oldFilter = (BaseAttributeFilter) item.filter; String newNames[] = newFilter.getNames(); String oldNames[] = oldFilter.getNames(); if (newNames.length == 0) { oldFilter.clear(); } else { if (oldNames.length != 0) { for (int i = 0; i < newNames.length; i++) oldFilter.addAttribute(newNames[i]); } } return; } } } // General purpose addition of a new entry entries.add(new BaseNotificationBroadcasterEntry (listener, filter, handback)); } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void addAttributeChangeNotificationListener (NotificationListener listener, String name, Object handback) throws IllegalArgumentException { if (listener == null) throw new IllegalArgumentException("Listener is null"); if (attributeBroadcaster == null) attributeBroadcaster = new BaseNotificationBroadcaster(); if( log.isDebugEnabled() ) log.debug("addAttributeNotificationListener " + listener); BaseAttributeFilter filter = new BaseAttributeFilter(name); attributeBroadcaster.addNotificationListener (listener, filter, handback); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException { if (listener == null) throw new IllegalArgumentException("Listener is null"); if( log.isDebugEnabled() ) log.debug("addNotificationListener " + listener); if (generalBroadcaster == null) generalBroadcaster = new BaseNotificationBroadcaster(); generalBroadcaster.addNotificationListener (listener, filter, handback); // We'll send the attribute change notifications to all listeners ( who care ) // The normal filtering can be used. // The problem is that there is no other way to add attribute change listeners // to a model mbean ( AFAIK ). I suppose the spec should be fixed. if (attributeBroadcaster == null) attributeBroadcaster = new BaseNotificationBroadcaster(); if( log.isDebugEnabled() ) log.debug("addAttributeNotificationListener " + listener); attributeBroadcaster.addNotificationListener (listener, filter, handback); }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public FileMessage readMessage(FileMessage f) throws IllegalArgumentException, IOException { checkState(false); int length = in.read(data); if (length == -1) { cleanup(); return null; } else { f.setData(data, length); f.setTotalLength(size); f.setTotalNrOfMsgs(totalNrOfMessages); f.setMessageNumber(++nrOfMessagesProcessed); return f; }//end if }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
public boolean writeMessage(FileMessage msg) throws IllegalArgumentException, IOException { if (!openForWrite) throw new IllegalArgumentException( "Can't write message, this factory is reading."); if (log.isDebugEnabled()) log.debug("Message " + msg + " data " + HexUtils.toHexString(msg.getData()) + " data length " + msg.getDataLength() + " out " + out); if (msg.getMessageNumber() <= lastMessageProcessed.get()) { // Duplicate of message already processed log.warn("Receive Message again -- Sender ActTimeout too short [ name: " + msg.getContextName() + " war: " + msg.getFileName() + " data: " + HexUtils.toHexString(msg.getData()) + " data length: " + msg.getDataLength() + " ]"); return false; } FileMessage previous = msgBuffer.put(Long.valueOf(msg.getMessageNumber()), msg); if (previous !=null) { // Duplicate of message not yet processed log.warn("Receive Message again -- Sender ActTimeout too short [ name: " + msg.getContextName() + " war: " + msg.getFileName() + " data: " + HexUtils.toHexString(msg.getData()) + " data length: " + msg.getDataLength() + " ]"); return false; } FileMessage next = null; synchronized (this) { if (!isWriting) { next = msgBuffer.get(Long.valueOf(lastMessageProcessed.get() + 1)); if (next != null) { isWriting = true; } else { return false; } } else { return false; } } while (next != null) { out.write(next.getData(), 0, next.getDataLength()); lastMessageProcessed.incrementAndGet(); out.flush(); if (next.getMessageNumber() == next.getTotalNrOfMsgs()) { out.close(); cleanup(); return true; } synchronized(this) { next = msgBuffer.get(Long.valueOf(lastMessageProcessed.get() + 1)); if (next == null) { isWriting = false; } } } return false; }
// in java/org/apache/catalina/ha/deploy/FileMessageFactory.java
protected void checkState(boolean openForWrite) throws IllegalArgumentException { if (this.openForWrite != openForWrite) { cleanup(); if (openForWrite) throw new IllegalArgumentException( "Can't write message, this factory is reading."); else throw new IllegalArgumentException( "Can't read message, this factory is writing."); } if (this.closed) { cleanup(); throw new IllegalArgumentException("Factory has been closed."); } }
// in java/org/apache/catalina/core/StandardContext.java
Override public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object object) throws IllegalArgumentException { broadcaster.addNotificationListener(listener,filter,object); }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object object) throws IllegalArgumentException { broadcaster.addNotificationListener(listener,filter,object); }
31
            
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/jasper/compiler/Parser.java
catch (IllegalArgumentException iae) { // Duplicate attribute err.jspError(reader.mark(), "jsp.error.attribute.duplicate"); }
// in java/org/apache/jasper/compiler/Parser.java
catch (IllegalArgumentException iae) { err.jspError(start, iae.getMessage()); }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
catch (IllegalArgumentException e) { proxyInstance = Proxy.newProxyInstance(tcl, serviceInterfaces, proxy); }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IllegalArgumentException e) { // Leave level set to null }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalArgumentException biae) { //the boolean method had the wrong //parameter types. lets try the other if (setPropertyMethodVoid!=null) { setPropertyMethodVoid.invoke(o, params); return true; }else { throw biae; } }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalArgumentException ex2) { log.warn("IAE " + o + " " + name + " " + value, ex2); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalArgumentException ex2) { log.warn("IAE " + o + " " + name, ex2); }
// in java/org/apache/tomcat/util/log/UserDataHelper.java
catch (IllegalArgumentException iae) { // Ignore - use default tempConfig = Config.INFO_THEN_DEBUG; }
// in java/org/apache/el/lang/ELSupport.java
catch (IllegalArgumentException iae) { throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/parser/AstValue.java
catch (IllegalArgumentException iae) { throw new ELException(iae); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalArgumentException e) { // Ignore: normal error due to dual definition of package }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (IllegalArgumentException e) { log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalArgumentException e) { // Ignore }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalArgumentException illegalArgument) { return true; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch(IllegalArgumentException illegalArgument) { return true; }
// in java/org/apache/catalina/connector/Request.java
catch (IllegalArgumentException e) { return null; }
// in java/org/apache/catalina/connector/Request.java
catch(IllegalArgumentException e) { // Ignore bad cookie }
// in java/org/apache/catalina/connector/Response.java
catch (IllegalArgumentException e) { setStatus(SC_NOT_FOUND); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (IllegalArgumentException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", env.getName())); }
// in java/org/apache/catalina/core/StandardContext.java
catch (IllegalArgumentException e) { log.error("Error initializing resources: " + e.getMessage()); ok = false; }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalArgumentException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (IllegalArgumentException e) { log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); }
// in java/javax/el/ExpressionFactory.java
catch (IllegalArgumentException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalArgumentException e) { throw new ELException(e); }
8
            
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (IllegalArgumentException biae) { //the boolean method had the wrong //parameter types. lets try the other if (setPropertyMethodVoid!=null) { setPropertyMethodVoid.invoke(o, params); return true; }else { throw biae; } }
// in java/org/apache/el/lang/ELSupport.java
catch (IllegalArgumentException iae) { throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); }
// in java/org/apache/el/parser/AstValue.java
catch (IllegalArgumentException iae) { throw new ELException(iae); }
// in java/org/apache/catalina/tribes/io/ReplicationStream.java
catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); }
// in java/org/apache/catalina/util/CustomObjectInputStream.java
catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); }
// in java/javax/el/ExpressionFactory.java
catch (IllegalArgumentException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (IllegalArgumentException e) { throw new ELException(e); }
4
checked (Domain) IllegalBoundaryException
public static class IllegalBoundaryException
            extends IOException {

        private static final long serialVersionUID = 1L;

        /**
         * Constructs an <code>IllegalBoundaryException</code> with no
         * detail message.
         */
        public IllegalBoundaryException() {
            super();
        }

        /**
         * Constructs an <code>IllegalBoundaryException</code> with
         * the specified detail message.
         *
         * @param message The detail message.
         */
        public IllegalBoundaryException(String message) {
            super(message);
        }
    }
1
            
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public void setBoundary(byte[] boundary) throws IllegalBoundaryException { if (boundary.length != boundaryLength - BOUNDARY_PREFIX.length) { throw new IllegalBoundaryException( "The length of a boundary token can not be changed"); } System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length); }
0 1
            
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public void setBoundary(byte[] boundary) throws IllegalBoundaryException { if (boundary.length != boundaryLength - BOUNDARY_PREFIX.length) { throw new IllegalBoundaryException( "The length of a boundary token can not be changed"); } System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length); }
0 0 0
runtime (Lib) IllegalStateException 196
            
// in java/org/apache/jasper/tagplugins/jstl/Util.java
Override public PrintWriter getWriter() { if (isStreamUsed) throw new IllegalStateException("Unexpected internal error during &lt;import&gt: " + "Target servlet called getWriter(), then getOutputStream()"); isWriterUsed = true; return new PrintWriter(sw); }
// in java/org/apache/jasper/tagplugins/jstl/Util.java
Override public ServletOutputStream getOutputStream() { if (isWriterUsed) throw new IllegalStateException("Unexpected internal error during &lt;import&gt: " + "Target servlet called getOutputStream(), then getWriter()"); isStreamUsed = true; return sos; }
// in java/org/apache/jasper/runtime/ServletResponseWrapperInclude.java
Override public ServletOutputStream getOutputStream() throws IOException { throw new IllegalStateException(); }
// in java/org/apache/jasper/runtime/InstanceManagerFactory.java
public static InstanceManager getInstanceManager(ServletConfig config) { InstanceManager instanceManager = (InstanceManager) config.getServletContext().getAttribute(InstanceManager.class.getName()); if (instanceManager == null) { throw new IllegalStateException("No org.apache.tomcat.InstanceManager set in ServletContext"); } return instanceManager; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void _initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) { // initialize state this.servlet = servlet; this.config = servlet.getServletConfig(); this.context = config.getServletContext(); this.errorPageURL = errorPageURL; this.request = request; this.response = response; // initialize application context this.applicationContext = JspApplicationContextImpl.getInstance(context); // Setup session (if required) if (request instanceof HttpServletRequest && needsSession) this.session = ((HttpServletRequest) request).getSession(); if (needsSession && session == null) throw new IllegalStateException( "Page needs a session and none is available"); // initialize the initial out ... depth = -1; if (this.baseOut == null) { this.baseOut = new JspWriterImpl(response, bufferSize, autoFlush); } else { this.baseOut.init(response, bufferSize, autoFlush); } this.out = baseOut; // register names/values as per spec setAttribute(OUT, this.out); setAttribute(REQUEST, request); setAttribute(RESPONSE, response); if (session != null) setAttribute(SESSION, session); setAttribute(PAGE, servlet); setAttribute(CONFIG, config); setAttribute(PAGECONTEXT, this); setAttribute(APPLICATION, context); isIncluded = request.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH) != null; }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private Object doGetAttribute(String name, int scope) { switch (scope) { case PAGE_SCOPE: return attributes.get(name); case REQUEST_SCOPE: return request.getAttribute(name); case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } return session.getAttribute(name); case APPLICATION_SCOPE: return context.getAttribute(name); default: throw new IllegalArgumentException("Invalid scope"); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doSetAttribute(String name, Object o, int scope) { if (o != null) { switch (scope) { case PAGE_SCOPE: attributes.put(name, o); break; case REQUEST_SCOPE: request.setAttribute(name, o); break; case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } session.setAttribute(name, o); break; case APPLICATION_SCOPE: context.setAttribute(name, o); break; default: throw new IllegalArgumentException("Invalid scope"); } } else { removeAttribute(name, scope); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doRemoveAttribute(String name, int scope) { switch (scope) { case PAGE_SCOPE: attributes.remove(name); break; case REQUEST_SCOPE: request.removeAttribute(name); break; case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } session.removeAttribute(name); break; case APPLICATION_SCOPE: context.removeAttribute(name); break; default: throw new IllegalArgumentException("Invalid scope"); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private Enumeration<String> doGetAttributeNamesInScope(int scope) { switch (scope) { case PAGE_SCOPE: return Collections.enumeration(attributes.keySet()); case REQUEST_SCOPE: return request.getAttributeNames(); case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } return session.getAttributeNames(); case APPLICATION_SCOPE: return context.getAttributeNames(); default: throw new IllegalArgumentException("Invalid scope"); } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public final void clear() throws IOException { if ((bufferSize == 0) && (out != null)) // clear() is illegal after any unbuffered output (JSP.5.5) throw new IllegalStateException( getLocalizeMessage("jsp.error.ise_on_clear")); if (flushed) throw new IOException( getLocalizeMessage("jsp.error.attempt_to_clear_flushed_buffer")); ensureOpen(); nextChar = 0; }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void clearBuffer() throws IOException { if (bufferSize == 0) throw new IllegalStateException( getLocalizeMessage("jsp.error.ise_on_clear")); ensureOpen(); nextChar = 0; }
// in java/org/apache/jasper/runtime/JspApplicationContextImpl.java
Override public void addELResolver(ELResolver resolver) throws IllegalStateException { if (resolver == null) { throw new IllegalArgumentException("ELResolver was null"); } if (this.instantiated) { throw new IllegalStateException( "cannot call addELResolver after the first request has been made"); } this.resolvers.add(resolver); }
// in java/org/apache/jasper/compiler/SmapGenerator.java
public synchronized String getString() { // check state and initialize buffer if (outputFileName == null) throw new IllegalStateException(); StringBuilder out = new StringBuilder(); // start the SMAP out.append("SMAP\n"); out.append(outputFileName + '\n'); out.append(defaultStratum + '\n'); // include embedded SMAPs if (doEmbedded) { int nEmbedded = embedded.size(); for (int i = 0; i < nEmbedded; i++) { out.append(embedded.get(i)); } } // print our StratumSections, FileSections, and LineSections int nStrata = strata.size(); for (int i = 0; i < nStrata; i++) { SmapStratum s = strata.get(i); out.append(s.getString()); } // end the SMAP out.append("*E\n"); return out.toString(); }
// in java/org/apache/jasper/compiler/SmapStratum.java
public String getString() { if (inputStartLine == -1 || outputStartLine == -1) throw new IllegalStateException(); StringBuilder out = new StringBuilder(); out.append(inputStartLine); if (lineFileIDSet) out.append("#" + lineFileID); if (inputLineCount != 1) out.append("," + inputLineCount); out.append(":" + outputStartLine); if (outputLineIncrement != 1) out.append("," + outputLineIncrement); out.append('\n'); return out.toString(); }
// in java/org/apache/jasper/JspCompilationContext.java
public Compiler createCompiler() { if (jspCompiler != null ) { return jspCompiler; } jspCompiler = null; if (options.getCompilerClassName() != null) { jspCompiler = createCompiler(options.getCompilerClassName()); } else { if (options.getCompiler() == null) { jspCompiler = createCompiler("org.apache.jasper.compiler.JDTCompiler"); if (jspCompiler == null) { jspCompiler = createCompiler("org.apache.jasper.compiler.AntCompiler"); } } else { jspCompiler = createCompiler("org.apache.jasper.compiler.AntCompiler"); if (jspCompiler == null) { jspCompiler = createCompiler("org.apache.jasper.compiler.JDTCompiler"); } } } if (jspCompiler == null) { throw new IllegalStateException(Localizer.getMessage("jsp.error.compiler")); } jspCompiler.init(this, jsw); return jspCompiler; }
// in java/org/apache/jasper/JspCompilationContext.java
protected void createOutputDir() { String path = null; if (isTagFile()) { String tagName = tagInfo.getTagClassName(); path = tagName.replace('.', File.separatorChar); path = path.substring(0, path.lastIndexOf(File.separatorChar)); } else { path = getServletPackageName().replace('.',File.separatorChar); } // Append servlet or tag handler path to scratch dir try { File base = options.getScratchDir(); baseUrl = base.toURI().toURL(); outputDir = base.getAbsolutePath() + File.separator + path + File.separator; if (!makeOutputDir()) { throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder")); } } catch (MalformedURLException e) { throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"), e); } }
// in java/org/apache/naming/resources/DirContextURLStreamHandler.java
public static DirContext get() { DirContext result = null; Thread currentThread = Thread.currentThread(); ClassLoader currentCL = currentThread.getContextClassLoader(); // Checking CL binding result = clBindings.get(currentCL); if (result != null) return result; // Checking thread biding result = threadBindings.get(currentThread); // Checking parent CL binding currentCL = currentCL.getParent(); while (currentCL != null) { result = clBindings.get(currentCL); if (result != null) return result; currentCL = currentCL.getParent(); } if (result == null) throw new IllegalStateException("Illegal class loader binding"); return result; }
// in java/org/apache/coyote/Response.java
public void reset() throws IllegalStateException { // Reset the headers only if this is the main request, // not for included contentType = null; locale = DEFAULT_LOCALE; contentLanguage = null; characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; contentLength = -1; charsetSet = false; status = 200; message = null; headers.clear(); // Force the PrintWriter to flush its data to the output // stream before resetting the output stream // // Reset the stream if (commited) { //String msg = sm.getString("servletOutputStreamImpl.reset.ise"); throw new IllegalStateException(); } action(ActionCode.RESET, this); }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public void setSslSupport(SSLSupport sslSupport) { // Should never reach this code but in case we do... throw new IllegalStateException( sm.getString("ajpprocessor.ssl.notsupported")); }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
Override public UpgradeInbound getUpgradeInbound() { // Should never reach this code but in case we do... throw new IllegalStateException( sm.getString("ajpprocessor.httpupgrade.notsupported")); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override public boolean parseRequestLine(boolean useAvailableDataOnly) throws IOException { //check state if ( !parsingRequestLine ) return true; // // Skipping blank lines // if ( parsingRequestLinePhase == 0 ) { byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (useAvailableDataOnly) { return false; } // Ignore bytes that were read pos = lastValid = 0; // Do a simple read with a short timeout if ( readSocket(true, false)==0 ) return false; } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; if (pos >= skipBlankLinesSize) { // Move data, to have enough space for further reading // of headers and body System.arraycopy(buf, pos, buf, 0, lastValid - pos); lastValid -= pos; pos = 0; } skipBlankLinesBytes = pos; parsingRequestLineStart = pos; parsingRequestLinePhase = 2; if (log.isDebugEnabled()) { log.debug("Received [" + new String(buf, pos, lastValid - pos, DEFAULT_CHARSET) + "]"); } } if ( parsingRequestLinePhase == 2 ) { // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, parsingRequestLineStart, pos - parsingRequestLineStart); } pos++; } parsingRequestLinePhase = 3; } if ( parsingRequestLinePhase == 3 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 4; } if (parsingRequestLinePhase == 4) { // Mark the current buffer position int end = 0; // // Reading the URI // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request parsingRequestLineEol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (parsingRequestLineQPos == -1)) { parsingRequestLineQPos = pos; } pos++; } request.unparsedURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); if (parsingRequestLineQPos >= 0) { request.queryString().setBytes(buf, parsingRequestLineQPos + 1, end - parsingRequestLineQPos - 1); request.requestURI().setBytes(buf, parsingRequestLineStart, parsingRequestLineQPos - parsingRequestLineStart); } else { request.requestURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } parsingRequestLinePhase = 5; } if ( parsingRequestLinePhase == 5 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 6; } if (parsingRequestLinePhase == 6) { // Mark the current buffer position end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!parsingRequestLineEol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; parsingRequestLineEol = true; } pos++; } if ( (end - parsingRequestLineStart) > 0) { request.protocol().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } else { request.protocol().setString(""); } parsingRequestLine = false; parsingRequestLinePhase = 0; parsingRequestLineEol = false; parsingRequestLineStart = 0; return true; } throw new IllegalStateException("Invalid request line parse phase:"+parsingRequestLinePhase); }
// in java/org/apache/coyote/http11/InternalNioInputBuffer.java
Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } HeaderParseStatus status = HeaderParseStatus.HAVE_MORE_HEADERS; do { status = parseHeader(); } while ( status == HeaderParseStatus.HAVE_MORE_HEADERS ); if (status == HeaderParseStatus.DONE) { parsingHeader = false; end = pos; // Checking that // (1) Headers plus request line size does not exceed its limit // (2) There are enough bytes to avoid expanding the buffer when // reading body // Technically, (2) is technical limitation, (1) is logical // limitation to enforce the meaning of headerBufferSize // From the way how buf is allocated and how blank lines are being // read, it should be enough to check (1) only. if (end - skipBlankLinesBytes > headerBufferSize || buf.length - end < socketReadBufferSize) { throw new IllegalArgumentException( sm.getString("iib.requestheadertoolarge.error")); } return true; } else { return false; } }
// in java/org/apache/coyote/http11/filters/BufferedInputFilter.java
Override public void setRequest(Request request) { // save off the Request body try { while (buffer.doRead(tempRead, request) >= 0) { buffered.append(tempRead); tempRead.recycle(); } } catch(IOException ioe) { // No need for i18n - this isn't going to get logged anywhere throw new IllegalStateException( "Request body too large for buffer"); } }
// in java/org/apache/coyote/http11/InternalInputBuffer.java
Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } while (parseHeader()) { // Loop until we run out of headers } parsingHeader = false; end = pos; return true; }
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } while (parseHeader()) { // Loop until there are no more headers } parsingHeader = false; end = pos; return true; }
// in java/org/apache/coyote/http11/AbstractOutputBuffer.java
public void reset() { if (committed) throw new IllegalStateException(/*FIXME:Put an error message*/); // Recycle Request object response.recycle(); }
// in java/org/apache/coyote/http11/AbstractOutputBuffer.java
private void checkLengthBeforeWrite(int length) throws IllegalStateException { if (pos + length > buf.length) { throw new IllegalStateException( sm.getString("iob.responseheadertoolarge.error")); } }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized void asyncStart(AsyncContextCallback asyncCtxt) { if (state == AsyncState.DISPATCHED) { state = AsyncState.STARTING; this.asyncCtxt = asyncCtxt; } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncStart()", state)); } }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized SocketState asyncPostProcess() { if (state == AsyncState.STARTING) { state = AsyncState.STARTED; return SocketState.LONG; } else if (state == AsyncState.MUST_COMPLETE) { asyncCtxt.fireOnComplete(); state = AsyncState.DISPATCHED; return SocketState.ASYNC_END; } else if (state == AsyncState.COMPLETING) { asyncCtxt.fireOnComplete(); state = AsyncState.DISPATCHED; return SocketState.ASYNC_END; } else if (state == AsyncState.MUST_DISPATCH) { state = AsyncState.DISPATCHING; return SocketState.ASYNC_END; } else if (state == AsyncState.DISPATCHING) { state = AsyncState.DISPATCHED; return SocketState.ASYNC_END; } else if (state == AsyncState.ERROR) { asyncCtxt.fireOnComplete(); state = AsyncState.DISPATCHED; return SocketState.ASYNC_END; //} else if (state == AsyncState.DISPATCHED) { // // No state change // return SocketState.OPEN; } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncPostProcess()", state)); } }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized boolean asyncComplete() { boolean doComplete = false; if (state == AsyncState.STARTING) { state = AsyncState.MUST_COMPLETE; } else if (state == AsyncState.STARTED) { state = AsyncState.COMPLETING; doComplete = true; } else if (state == AsyncState.TIMING_OUT || state == AsyncState.ERROR) { state = AsyncState.MUST_COMPLETE; } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncComplete()", state)); } return doComplete; }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized boolean asyncTimeout() { if (state == AsyncState.STARTED) { state = AsyncState.TIMING_OUT; return true; } else if (state == AsyncState.COMPLETING || state == AsyncState.DISPATCHED) { // NOOP - App called complete between the the timeout firing and // execution reaching this point return false; } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncTimeout()", state)); } }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized boolean asyncDispatch() { boolean doDispatch = false; if (state == AsyncState.STARTING) { state = AsyncState.MUST_DISPATCH; } else if (state == AsyncState.STARTED || state == AsyncState.TIMING_OUT) { state = AsyncState.DISPATCHING; doDispatch = true; } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncDispatch()", state)); } return doDispatch; }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized void asyncDispatched() { if (state == AsyncState.DISPATCHING) { state = AsyncState.DISPATCHED; } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncDispatched()", state)); } }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized void asyncError() { if (state == AsyncState.DISPATCHED || state == AsyncState.TIMING_OUT) { state = AsyncState.ERROR; } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncError()", state)); } }
// in java/org/apache/coyote/AsyncStateMachine.java
public synchronized void asyncRun(Runnable runnable) { if (state == AsyncState.STARTING || state == AsyncState.STARTED) { // Execute the runnable using a container thread from the // Connector's thread pool. Use a wrapper to prevent a memory leak ClassLoader oldCL; if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<ClassLoader> pa = new PrivilegedGetTccl(); oldCL = AccessController.doPrivileged(pa); } else { oldCL = Thread.currentThread().getContextClassLoader(); } try { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( this.getClass().getClassLoader()); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader( this.getClass().getClassLoader()); } processor.getExecutor().execute(runnable); } finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( oldCL); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldCL); } } } else { throw new IllegalStateException( sm.getString("asyncStateMachine.invalidAsyncState", "asyncRun()", state)); } }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int handshake(boolean read, boolean write) throws IOException { if ( handshakeComplete ) return 0; //we have done our initial handshake if (!flush(netOutBuffer)) return SelectionKey.OP_WRITE; //we still have data to write SSLEngineResult handshake = null; while (!handshakeComplete) { switch ( handshakeStatus ) { case NOT_HANDSHAKING: { //should never happen throw new IOException("NOT_HANDSHAKING during handshake"); } case FINISHED: { //we are complete if we have delivered the last package handshakeComplete = !netOutBuffer.hasRemaining(); //return 0 if we are complete, otherwise we still have data to write return handshakeComplete?0:SelectionKey.OP_WRITE; } case NEED_WRAP: { //perform the wrap function handshake = handshakeWrap(write); if ( handshake.getStatus() == Status.OK ){ if (handshakeStatus == HandshakeStatus.NEED_TASK) handshakeStatus = tasks(); } else { //wrap should always work with our buffers throw new IOException("Unexpected status:" + handshake.getStatus() + " during handshake WRAP."); } if ( handshakeStatus != HandshakeStatus.NEED_UNWRAP || (!flush(netOutBuffer)) ) { //should actually return OP_READ if we have NEED_UNWRAP return SelectionKey.OP_WRITE; } //fall down to NEED_UNWRAP on the same call, will result in a //BUFFER_UNDERFLOW if it needs data } //$FALL-THROUGH$ case NEED_UNWRAP: { //perform the unwrap function handshake = handshakeUnwrap(read); if ( handshake.getStatus() == Status.OK ) { if (handshakeStatus == HandshakeStatus.NEED_TASK) handshakeStatus = tasks(); } else if ( handshake.getStatus() == Status.BUFFER_UNDERFLOW ){ //read more data, reregister for OP_READ return SelectionKey.OP_READ; } else { throw new IOException("Invalid handshake status:"+handshakeStatus+" during handshake UNWRAP."); }//switch break; } case NEED_TASK: { handshakeStatus = tasks(); break; } default: throw new IllegalStateException("Invalid handshake status:"+handshakeStatus); }//switch }//while //return 0 if we are complete, otherwise reregister for any activity that //would cause this method to be called again. return handshakeComplete?0:(SelectionKey.OP_WRITE|SelectionKey.OP_READ); }
// in java/org/apache/tomcat/util/net/SecureNioChannel.java
Override public int read(ByteBuffer dst) throws IOException { //if we want to take advantage of the expand function, make sure we only use the ApplicationBufferHandler's buffers if ( dst != bufHandler.getReadBuffer() ) throw new IllegalArgumentException("You can only read using the application read buffer provided by the handler."); //are we in the middle of closing or closed? if ( closing || closed) return -1; //did we finish our handshake? if (!handshakeComplete) throw new IllegalStateException("Handshake incomplete, you must complete handshake before reading data."); //read from the network int netread = sc.read(netInBuffer); //did we reach EOF? if so send EOF up one layer. if (netread == -1) return -1; //the data read int read = 0; //the SSL engine result SSLEngineResult unwrap; do { //prepare the buffer netInBuffer.flip(); //unwrap the data unwrap = sslEngine.unwrap(netInBuffer, dst); //compact the buffer netInBuffer.compact(); if ( unwrap.getStatus()==Status.OK || unwrap.getStatus()==Status.BUFFER_UNDERFLOW ) { //we did receive some data, add it to our total read += unwrap.bytesProduced(); //perform any tasks if needed if (unwrap.getHandshakeStatus() == HandshakeStatus.NEED_TASK) tasks(); //if we need more network data, then bail out for now. if ( unwrap.getStatus() == Status.BUFFER_UNDERFLOW ) break; }else if ( unwrap.getStatus()==Status.BUFFER_OVERFLOW && read>0 ) { //buffer overflow can happen, if we have read data, then //empty out the dst buffer before we do another read break; }else { //here we should trap BUFFER_OVERFLOW and call expand on the buffer //for now, throw an exception, as we initialized the buffers //in the constructor throw new IOException("Unable to unwrap data, invalid status: " + unwrap.getStatus()); } } while ( (netInBuffer.position() != 0)); //continue to unwrapping as long as the input buffer has stuff return (read); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
protected CountDownLatch resetLatch(CountDownLatch latch) { if ( latch==null || latch.getCount() == 0 ) return null; else throw new IllegalStateException("Latch must be at count 0"); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
protected CountDownLatch startLatch(CountDownLatch latch, int cnt) { if ( latch == null || latch.getCount() == 0 ) { return new CountDownLatch(cnt); } else throw new IllegalStateException("Latch must be at count 0 or null."); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
protected void awaitLatch(CountDownLatch latch, long timeout, TimeUnit unit) throws InterruptedException { if ( latch == null ) throw new IllegalStateException("Latch cannot be null"); latch.await(timeout,unit); }
// in java/org/apache/tomcat/util/http/Parameters.java
public void addParameter( String key, String value ) throws IllegalStateException { if( key==null ) { return; } parameterCount ++; if (limit > -1 && parameterCount > limit) { // Processing this parameter will push us over the limit. ISE is // what Request.parseParts() uses for requests that are too big parseFailed = true; throw new IllegalStateException(sm.getString( "parameters.maxCountFail", Integer.valueOf(limit))); } ArrayList<String> values = paramHashValues.get(key); if (values == null) { values = new ArrayList<String>(1); paramHashValues.put(key, values); } values.add(value); }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
private int parseEndOfLine(String headerPart, int end) { int index = end; for (;;) { int offset = headerPart.indexOf('\r', index); if (offset == -1 || offset + 1 >= headerPart.length()) { throw new IllegalStateException( "Expected headers to be terminated by an empty line."); } if (headerPart.charAt(offset + 1) == '\n') { return offset; } index = offset + 1; } }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public InputStream openStream() throws IOException { if (opened) { throw new IllegalStateException( "The stream was already opened."); } if (((Closeable) stream).isClosed()) { throw new FileItemStream.ItemSkippedException(); } return stream; }
// in java/org/apache/tomcat/util/http/fileupload/FileCleaningTracker.java
private synchronized void addTracker(String path, Object marker, FileDeleteStrategy deleteStrategy) { // synchronized block protects reaper if (exitWhenFinished) { throw new IllegalStateException("No new trackers can be added once exitWhenFinished() is called"); } if (reaper == null) { reaper = new Reaper(); reaper.start(); } trackers.add(new Tracker(path, deleteStrategy, marker, q)); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantValue.java
Override public final String toString() { Constant c = constant_pool.getConstant(constantvalue_index); String buf; int i; // Print constant to string depending on its type switch (c.getTag()) { case Constants.CONSTANT_Long: buf = String.valueOf(((ConstantLong) c).getBytes()); break; case Constants.CONSTANT_Float: buf = String.valueOf(((ConstantFloat) c).getBytes()); break; case Constants.CONSTANT_Double: buf = String.valueOf(((ConstantDouble) c).getBytes()); break; case Constants.CONSTANT_Integer: buf = String.valueOf(((ConstantInteger) c).getBytes()); break; case Constants.CONSTANT_String: i = ((ConstantString) c).getStringIndex(); c = constant_pool.getConstant(i, Constants.CONSTANT_Utf8); buf = "\"" + Utility.convertString(((ConstantUtf8) c).getBytes()) + "\""; break; default: throw new IllegalStateException("Type of ConstValue invalid: " + c); } return buf; }
// in java/org/apache/tomcat/util/bcel/classfile/Attribute.java
public static final Attribute readAttribute(DataInputStream file, ConstantPool constant_pool) throws IOException, ClassFormatException { ConstantUtf8 c; String name; int name_index; int length; byte tag = Constants.ATTR_UNKNOWN; // Unknown attribute // Get class name from constant pool via `name_index' indirection name_index = file.readUnsignedShort(); c = (ConstantUtf8) constant_pool.getConstant(name_index, Constants.CONSTANT_Utf8); name = c.getBytes(); // Length of data in bytes length = file.readInt(); // Compare strings to find known attribute // System.out.println(name); for (byte i = 0; i < Constants.KNOWN_ATTRIBUTES; i++) { if (name.equals(Constants.ATTRIBUTE_NAMES[i])) { tag = i; // found! break; } } // Call proper constructor, depending on `tag' switch (tag) { case Constants.ATTR_UNKNOWN: AttributeReader r = readers.get(name); if (r != null) { return r.createAttribute(name_index, length, file, constant_pool); } return new Unknown(name_index, length, file, constant_pool); case Constants.ATTR_CONSTANT_VALUE: return new ConstantValue(name_index, length, file, constant_pool); case Constants.ATTR_SOURCE_FILE: return new SourceFile(name_index, length, file, constant_pool); case Constants.ATTR_CODE: return new Code(name_index, length, file, constant_pool); case Constants.ATTR_EXCEPTIONS: return new ExceptionTable(name_index, length, file, constant_pool); case Constants.ATTR_LINE_NUMBER_TABLE: return new LineNumberTable(name_index, length, file, constant_pool); case Constants.ATTR_LOCAL_VARIABLE_TABLE: return new LocalVariableTable(name_index, length, file, constant_pool); case Constants.ATTR_INNER_CLASSES: return new InnerClasses(name_index, length, file, constant_pool); case Constants.ATTR_SYNTHETIC: return new Synthetic(name_index, length, file, constant_pool); case Constants.ATTR_DEPRECATED: return new Deprecated(name_index, length, file, constant_pool); case Constants.ATTR_PMG: return new PMGClass(name_index, length, file, constant_pool); case Constants.ATTR_SIGNATURE: return new Signature(name_index, length, file, constant_pool); case Constants.ATTR_STACK_MAP: return new StackMap(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIME_VISIBLE_ANNOTATIONS: return new RuntimeVisibleAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIMEIN_VISIBLE_ANNOTATIONS: return new RuntimeInvisibleAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS: return new RuntimeVisibleParameterAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_RUNTIMEIN_VISIBLE_PARAMETER_ANNOTATIONS: return new RuntimeInvisibleParameterAnnotations(name_index, length, file, constant_pool); case Constants.ATTR_ANNOTATION_DEFAULT: return new AnnotationDefault(name_index, length, file, constant_pool); case Constants.ATTR_LOCAL_VARIABLE_TYPE_TABLE: return new LocalVariableTypeTable(name_index, length, file, constant_pool); case Constants.ATTR_ENCLOSING_METHOD: return new EnclosingMethod(name_index, length, file, constant_pool); case Constants.ATTR_STACK_MAP_TABLE: return new StackMapTable(name_index, length, file, constant_pool); default: // Never reached throw new IllegalStateException("Unrecognized attribute type tag parsed: " + tag); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (log.isDebugEnabled()) log.debug("loadClass(" + name + ", " + resolve + ")"); Class<?> clazz = null; // Log access to stopped classloader if (!started) { try { throw new IllegalStateException(); } catch (IllegalStateException e) { log.info(sm.getString("webappClassLoader.stopped", name), e); } } // (0) Check our previously loaded local class cache clazz = findLoadedClass0(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.1) Check our previously loaded class cache clazz = findLoadedClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.2) Try loading the class with the system class loader, to prevent // the webapp from overriding J2SE classes try { clazz = system.loadClass(name); if (clazz != null) { if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (0.5) Permission to access this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { securityManager.checkPackageAccess(name.substring(0,i)); } catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); } } } boolean delegateLoad = delegate || filter(name); // (1) Delegate to our parent if requested if (delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader1 " + parent); ClassLoader loader = parent; if (loader == null) loader = system; try { clazz = Class.forName(name, false, loader); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } // (2) Search local repositories if (log.isDebugEnabled()) log.debug(" Searching local repositories"); try { clazz = findClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from local repository"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (3) Delegate to parent unconditionally if (!delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader at end: " + parent); ClassLoader loader = parent; if (loader == null) loader = system; try { clazz = Class.forName(name, false, loader); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } throw new ClassNotFoundException(name); }
// in java/org/apache/catalina/realm/RealmBase.java
protected String getDigest(String username, String realmName) { if (md5Helper == null) { try { md5Helper = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("Couldn't get MD5 digest: ", e); throw new IllegalStateException(e.getMessage()); } } if (hasMessageDigest()) { // Use pre-generated digest return getPassword(username); } String digestValue = username + ":" + realmName + ":" + getPassword(username); byte[] valueBytes = null; try { valueBytes = digestValue.getBytes(getDigestCharset()); } catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); } byte[] digest = null; // Bugzilla 32137 synchronized(md5Helper) { digest = md5Helper.digest(valueBytes); } return md5Encoder.encode(digest); }
// in java/org/apache/catalina/realm/RealmBase.java
static AllRolesMode toMode(String name) { AllRolesMode mode; if( name.equalsIgnoreCase(STRICT_MODE.name) ) mode = STRICT_MODE; else if( name.equalsIgnoreCase(AUTH_ONLY_MODE.name) ) mode = AUTH_ONLY_MODE; else if( name.equalsIgnoreCase(STRICT_AUTH_ONLY_MODE.name) ) mode = STRICT_AUTH_ONLY_MODE; else throw new IllegalStateException("Unknown mode, must be one of: strict, authOnly, strictAuthOnly"); return mode; }
// in java/org/apache/catalina/filters/ExpiresFilter.java
protected Date getExpirationDate(ExpiresConfiguration configuration, XHttpServletResponse response) { Calendar calendar; switch (configuration.getStartingPoint()) { case ACCESS_TIME: calendar = Calendar.getInstance(); break; case LAST_MODIFICATION_TIME: if (response.isLastModifiedHeaderSet()) { try { long lastModified = response.getLastModifiedHeader(); calendar = Calendar.getInstance(); calendar.setTimeInMillis(lastModified); } catch (NumberFormatException e) { // default to now calendar = Calendar.getInstance(); } } else { // Last-Modified header not found, use now calendar = Calendar.getInstance(); } break; default: throw new IllegalStateException(sm.getString( "expiresFilter.unsupportedStartingPoint", configuration.getStartingPoint())); } for (Duration duration : configuration.getDurations()) { calendar.add(duration.getUnit().getCalendardField(), duration.getAmount()); } return calendar.getTime(); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
protected ExpiresConfiguration parseExpiresConfiguration(String inputLine) { String line = inputLine.trim(); StringTokenizer tokenizer = new StringTokenizer(line, " "); String currentToken; try { currentToken = tokenizer.nextToken(); } catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "expiresFilter.startingPointNotFound", line)); } StartingPoint startingPoint; if ("access".equalsIgnoreCase(currentToken) || "now".equalsIgnoreCase(currentToken)) { startingPoint = StartingPoint.ACCESS_TIME; } else if ("modification".equalsIgnoreCase(currentToken)) { startingPoint = StartingPoint.LAST_MODIFICATION_TIME; } else if (!tokenizer.hasMoreTokens() && startsWithIgnoreCase(currentToken, "a")) { startingPoint = StartingPoint.ACCESS_TIME; // trick : convert duration configuration from old to new style tokenizer = new StringTokenizer(currentToken.substring(1) + " seconds", " "); } else if (!tokenizer.hasMoreTokens() && startsWithIgnoreCase(currentToken, "m")) { startingPoint = StartingPoint.LAST_MODIFICATION_TIME; // trick : convert duration configuration from old to new style tokenizer = new StringTokenizer(currentToken.substring(1) + " seconds", " "); } else { throw new IllegalStateException(sm.getString( "expiresFilter.startingPointInvalid", currentToken, line)); } try { currentToken = tokenizer.nextToken(); } catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); } if ("plus".equalsIgnoreCase(currentToken)) { // skip try { currentToken = tokenizer.nextToken(); } catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); } } List<Duration> durations = new ArrayList<Duration>(); while (currentToken != null) { int amount; try { amount = Integer.parseInt(currentToken); } catch (NumberFormatException e) { throw new IllegalStateException(sm.getString( "Invalid duration (number) '{}' in directive '{}'", currentToken, line)); } try { currentToken = tokenizer.nextToken(); } catch (NoSuchElementException e) { throw new IllegalStateException( sm.getString( "Duration unit not found after amount {} in directive '{}'", Integer.valueOf(amount), line)); } DurationUnit durationUnit; if ("years".equalsIgnoreCase(currentToken)) { durationUnit = DurationUnit.YEAR; } else if ("month".equalsIgnoreCase(currentToken) || "months".equalsIgnoreCase(currentToken)) { durationUnit = DurationUnit.MONTH; } else if ("week".equalsIgnoreCase(currentToken) || "weeks".equalsIgnoreCase(currentToken)) { durationUnit = DurationUnit.WEEK; } else if ("day".equalsIgnoreCase(currentToken) || "days".equalsIgnoreCase(currentToken)) { durationUnit = DurationUnit.DAY; } else if ("hour".equalsIgnoreCase(currentToken) || "hours".equalsIgnoreCase(currentToken)) { durationUnit = DurationUnit.HOUR; } else if ("minute".equalsIgnoreCase(currentToken) || "minutes".equalsIgnoreCase(currentToken)) { durationUnit = DurationUnit.MINUTE; } else if ("second".equalsIgnoreCase(currentToken) || "seconds".equalsIgnoreCase(currentToken)) { durationUnit = DurationUnit.SECOND; } else { throw new IllegalStateException( sm.getString( "Invalid duration unit (years|months|weeks|days|hours|minutes|seconds) '{}' in directive '{}'", currentToken, line)); } Duration duration = new Duration(amount, durationUnit); durations.add(duration); if (tokenizer.hasMoreTokens()) { currentToken = tokenizer.nextToken(); } else { currentToken = null; } } return new ExpiresConfiguration(startingPoint, durations); }
// in java/org/apache/catalina/tribes/group/interceptors/FragmentationInterceptor.java
public ChannelMessage assemble() { if ( !complete() ) throw new IllegalStateException("Fragments are missing."); int buffersize = 0; for (int i=0; i<frags.length; i++ ) buffersize += frags[i].getLength(); XByteBuffer buf = new XByteBuffer(buffersize,false); msg.setMessage(buf); for ( int i=0; i<frags.length; i++ ) { msg.getMessage().append(frags[i].getBytesDirect(),0,frags[i].getLength()); } return msg; }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public XByteBuffer extractDataPackage(boolean clearFromBuffer) { int psize = countPackages(true); if (psize == 0) { throw new java.lang.IllegalStateException("No package exists in XByteBuffer"); } int size = toInt(buf, START_DATA.length); XByteBuffer xbuf = BufferPool.getBufferPool().getBuffer(size,false); xbuf.setLength(size); System.arraycopy(buf, START_DATA.length + 4, xbuf.getBytesDirect(), 0, size); if (clearFromBuffer) { int totalsize = START_DATA.length + 4 + size + END_DATA.length; bufSize = bufSize - totalsize; System.arraycopy(buf, totalsize, buf, 0, bufSize); } return xbuf; }
// in java/org/apache/catalina/tribes/transport/PooledSender.java
public synchronized DataSender getSender(long timeout) { long start = System.currentTimeMillis(); while ( true ) { if (!isOpen)throw new IllegalStateException("Queue is closed"); DataSender sender = null; if (notinuse.size() == 0 && inuse.size() < limit) { sender = parent.getNewDataSender(); } else if (notinuse.size() > 0) { sender = notinuse.remove(0); } if (sender != null) { inuse.add(sender); return sender; }//end if long delta = System.currentTimeMillis() - start; if ( delta > timeout && timeout>0) return null; else { try { wait(Math.max(timeout - delta,1)); }catch (InterruptedException x){} }//end if } }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
public synchronized void start(int level) throws IOException { boolean valid = false; if ( (level & Channel.MBR_RX_SEQ)==Channel.MBR_RX_SEQ ) { if ( receiver != null ) throw new IllegalStateException("McastService.receive already running."); try { if ( sender == null ) socket.joinGroup(address); }catch (IOException iox) { log.error("Unable to join multicast group, make sure your system has multicasting enabled."); throw iox; } doRunReceiver = true; receiver = new ReceiverThread(); receiver.setDaemon(true); receiver.start(); valid = true; } if ( (level & Channel.MBR_TX_SEQ)==Channel.MBR_TX_SEQ ) { if ( sender != null ) throw new IllegalStateException("McastService.send already running."); if ( receiver == null ) socket.joinGroup(address); //make sure at least one packet gets out there send(false); doRunSender = true; sender = new SenderThread(sendFrequency); sender.setDaemon(true); sender.start(); //we have started the receiver, but not yet waited for membership to establish valid = true; } if (!valid) { throw new IllegalArgumentException("Invalid start level. Only acceptable levels are Channel.MBR_RX_SEQ and Channel.MBR_TX_SEQ"); } //pause, once or twice waitForMembers(level); startLevel = (startLevel | level); }
// in java/org/apache/catalina/session/ManagerBase.java
Override public Session createSession(String sessionId) { if ((maxActiveSessions >= 0) && (getActiveSessions() >= maxActiveSessions)) { rejectedSessions++; throw new IllegalStateException( sm.getString("managerBase.createSession.ise")); } // Recycle or create a Session instance Session session = createEmptySession(); // Initialize the properties of the new session and return it session.setNew(true); session.setValid(true); session.setCreationTime(System.currentTimeMillis()); session.setMaxInactiveInterval(this.maxInactiveInterval); String id = sessionId; if (id == null) { id = generateSessionId(); } session.setId(id); sessionCounter++; SessionTiming timing = new SessionTiming(session.getCreationTime(), 0); synchronized (sessionCreationTiming) { sessionCreationTiming.add(timing); sessionCreationTiming.poll(); } return (session); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
protected Session swapIn(String id) throws IOException { if (store == null) return null; Object swapInLock = null; /* * The purpose of this sync and these locks is to make sure that a * session is only loaded once. It doesn't matter if the lock is removed * and then another thread enters this method and tries to load the same * session. That thread will re-create a swapIn lock for that session, * quickly find that the session is already in sessions, use it and * carry on. */ synchronized (this) { swapInLock = sessionSwapInLocks.get(id); if (swapInLock == null) { swapInLock = new Object(); sessionSwapInLocks.put(id, swapInLock); } } Session session = null; synchronized (swapInLock) { // First check to see if another thread has loaded the session into // the manager session = sessions.get(id); if (session == null) { try { if (SecurityUtil.isPackageProtectionEnabled()){ try { session = AccessController.doPrivileged( new PrivilegedStoreLoad(id)); } catch (PrivilegedActionException ex) { Exception e = ex.getException(); log.error(sm.getString( "persistentManager.swapInException", id), e); if (e instanceof IOException){ throw (IOException)e; } else if (e instanceof ClassNotFoundException) { throw (ClassNotFoundException)e; } } } else { session = store.load(id); } } catch (ClassNotFoundException e) { String msg = sm.getString( "persistentManager.deserializeError", id); log.error(msg, e); throw new IllegalStateException(msg, e); } if (session != null && !session.isValid()) { log.error(sm.getString( "persistentManager.swapInInvalid", id)); session.expire(); removeSession(id); session = null; } if (session != null) { if(log.isDebugEnabled()) log.debug(sm.getString("persistentManager.swapIn", id)); session.setManager(this); // make sure the listeners know about it. ((StandardSession)session).tellNew(); add(session); ((StandardSession)session).activate(); // endAccess() to ensure timeouts happen correctly. // access() to keep access count correct or it will end up // negative session.access(); session.endAccess(); } } } // Make sure the lock is removed synchronized (this) { sessionSwapInLocks.remove(id); } return (session); }
// in java/org/apache/catalina/session/StandardSession.java
Override public long getThisAccessedTime() { if (!isValidInternal()) { throw new IllegalStateException (sm.getString("standardSession.getThisAccessedTime.ise")); } return (this.thisAccessedTime); }
// in java/org/apache/catalina/session/StandardSession.java
Override public long getLastAccessedTime() { if (!isValidInternal()) { throw new IllegalStateException (sm.getString("standardSession.getLastAccessedTime.ise")); } return (this.lastAccessedTime); }
// in java/org/apache/catalina/session/StandardSession.java
Override public long getCreationTime() { if (!isValidInternal()) throw new IllegalStateException (sm.getString("standardSession.getCreationTime.ise")); return (this.creationTime); }
// in java/org/apache/catalina/session/StandardSession.java
Override public Object getAttribute(String name) { if (!isValidInternal()) throw new IllegalStateException (sm.getString("standardSession.getAttribute.ise")); if (name == null) return null; return (attributes.get(name)); }
// in java/org/apache/catalina/session/StandardSession.java
Override public Enumeration<String> getAttributeNames() { if (!isValidInternal()) throw new IllegalStateException (sm.getString("standardSession.getAttributeNames.ise")); Set<String> names = new HashSet<String>(); names.addAll(attributes.keySet()); return Collections.enumeration(names); }
// in java/org/apache/catalina/session/StandardSession.java
Override public void invalidate() { if (!isValidInternal()) throw new IllegalStateException (sm.getString("standardSession.invalidate.ise")); // Cause this session to expire expire(); }
// in java/org/apache/catalina/session/StandardSession.java
Override public boolean isNew() { if (!isValidInternal()) throw new IllegalStateException (sm.getString("standardSession.isNew.ise")); return (this.isNew); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException { boolean serveContent = content; // Identify the requested resource path String path = getRelativePath(request); if (debug > 0) { if (serveContent) log("DefaultServlet.serveResource: Serving resource '" + path + "' headers and data"); else log("DefaultServlet.serveResource: Serving resource '" + path + "' headers only"); } CacheEntry cacheEntry = resources.lookupCache(path); if (!cacheEntry.exists) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } else { // We're included // SRV.9.3 says we must throw a FNFE throw new FileNotFoundException( sm.getString("defaultServlet.missingResource", requestUri)); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } // If the resource is not a collection, and the resource path // ends with "/" or "\", return NOT FOUND if (cacheEntry.context == null) { if (path.endsWith("/") || (path.endsWith("\\"))) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } } boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST; // Check if the conditions specified in the optional If headers are // satisfied. if (cacheEntry.context == null) { // Checking If headers boolean included = (request.getAttribute( RequestDispatcher.INCLUDE_CONTEXT_PATH) != null); if (!included && !isError && !checkIfHeaders(request, response, cacheEntry.attributes)) { return; } } // Find content type. String contentType = cacheEntry.attributes.getMimeType(); if (contentType == null) { contentType = getServletContext().getMimeType(cacheEntry.name); cacheEntry.attributes.setMimeType(contentType); } ArrayList<Range> ranges = null; long contentLength = -1L; if (cacheEntry.context != null) { // Skip directory listings if we have been configured to // suppress them if (!listings) { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); return; } contentType = "text/html;charset=UTF-8"; } else { if (!isError) { if (useAcceptRanges) { // Accept ranges header response.setHeader("Accept-Ranges", "bytes"); } // Parse range specifier ranges = parseRange(request, response, cacheEntry.attributes); // ETag header response.setHeader("ETag", cacheEntry.attributes.getETag()); // Last-Modified header response.setHeader("Last-Modified", cacheEntry.attributes.getLastModifiedHttp()); } // Get content length contentLength = cacheEntry.attributes.getContentLength(); // Special case for zero length files, which would cause a // (silent) ISE when setting the output buffer size if (contentLength == 0L) { serveContent = false; } } ServletOutputStream ostream = null; PrintWriter writer = null; if (serveContent) { // Trying to retrieve the servlet output stream try { ostream = response.getOutputStream(); } catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } } } // Check to see if a Filter, Valve of wrapper has written some content. // If it has, disable range requests and setting of a content length // since neither can be done reliably. ServletResponse r = response; long contentWritten = 0; while (r instanceof ServletResponseWrapper) { r = ((ServletResponseWrapper) r).getResponse(); } if (r instanceof ResponseFacade) { contentWritten = ((ResponseFacade) r).getContentWritten(); } if (contentWritten > 0) { ranges = FULL; } if ( (cacheEntry.context != null) || isError || ( ((ranges == null) || (ranges.isEmpty())) && (request.getHeader("Range") == null) ) || (ranges == FULL) ) { // Set the appropriate output headers if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if ((cacheEntry.resource != null) && (contentLength >= 0) && (!serveContent || ostream != null)) { if (debug > 0) log("DefaultServlet.serveFile: contentLength=" + contentLength); // Don't set a content length if something else has already // written to the response. if (contentWritten == 0) { if (contentLength < Integer.MAX_VALUE) { response.setContentLength((int) contentLength); } else { // Set the content-length as String to be able to use a // long response.setHeader("content-length", "" + contentLength); } } } InputStream renderResult = null; if (cacheEntry.context != null) { if (serveContent) { // Serve the directory browser renderResult = render(getPathPrefix(request), cacheEntry); } } // Copy the input stream to our output stream (if requested) if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, contentLength, null)) copy(cacheEntry, renderResult, ostream); } else { copy(cacheEntry, renderResult, writer); } } } else { if ((ranges == null) || (ranges.isEmpty())) return; // Partial content response. response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); if (ranges.size() == 1) { Range range = ranges.get(0); response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; if (length < Integer.MAX_VALUE) { response.setContentLength((int) length); } else { // Set the content-length as String to be able to use a long response.setHeader("content-length", "" + length); } if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, range.end - range.start + 1, range)) copy(cacheEntry, ostream, range); } else { // we should not get here throw new IllegalStateException(); } } } else { response.setContentType("multipart/byteranges; boundary=" + mimeSeparation); if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { copy(cacheEntry, ostream, ranges.iterator(), contentType); } else { // we should not get here throw new IllegalStateException(); } } } } }
// in java/org/apache/catalina/ha/session/DeltaSession.java
public void removeAttribute(String name, boolean notify,boolean addDeltaRequest) { // Validate our current state if (!isValid()) throw new IllegalStateException(sm.getString("standardSession.removeAttribute.ise")); removeAttributeInternal(name, notify, addDeltaRequest); }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
Override public PrintWriter getWriter() throws java.io.IOException { if (servletOutputStream == null) { if (printWriter == null) { setCharacterEncoding(getCharacterEncoding()); printWriter = new PrintWriter( new OutputStreamWriter(captureServletOutputStream, getCharacterEncoding())); } return printWriter; } throw new IllegalStateException(); }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
Override public ServletOutputStream getOutputStream() throws java.io.IOException { if (printWriter == null) { if (servletOutputStream == null) { servletOutputStream = captureServletOutputStream; } return servletOutputStream; } throw new IllegalStateException(); }
// in java/org/apache/catalina/connector/Request.java
Override public ServletInputStream getInputStream() throws IOException { if (usingReader) { throw new IllegalStateException (sm.getString("coyoteRequest.getInputStream.ise")); } usingInputStream = true; if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } return inputStream; }
// in java/org/apache/catalina/connector/Request.java
Override public BufferedReader getReader() throws IOException { if (usingInputStream) { throw new IllegalStateException (sm.getString("coyoteRequest.getReader.ise")); } usingReader = true; inputBuffer.checkConverter(); if (reader == null) { reader = new CoyoteReader(inputBuffer); } return reader; }
// in java/org/apache/catalina/connector/Request.java
Override public AsyncContext startAsync(ServletRequest request, ServletResponse response) { if (!isAsyncSupported()) { throw new IllegalStateException("Not supported."); } if (asyncContext == null) { asyncContext = new AsyncContextImpl(this); } asyncContext.setStarted(getContext(), request, response, request==getRequest() && response==getResponse().getResponse()); asyncContext.setTimeout(getConnector().getAsyncTimeout()); return asyncContext; }
// in java/org/apache/catalina/connector/Request.java
Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { if (response.isCommitted()) { throw new IllegalStateException( sm.getString("coyoteRequest.authenticate.ise")); } return context.getAuthenticator().authenticate(this, response); }
// in java/org/apache/catalina/connector/Request.java
private void parseParts() { // Return immediately if the parts have already been parsed if (parts != null || partsParseException != null) { return; } MultipartConfigElement mce = getWrapper().getMultipartConfigElement(); if (mce == null) { if(getContext().getAllowCasualMultipartParsing()) { mce = new MultipartConfigElement(null, connector.getMaxPostSize(), connector.getMaxPostSize(), connector.getMaxPostSize()); } else { parts = Collections.emptyList(); return; } } Parameters parameters = coyoteRequest.getParameters(); parameters.setLimit(getConnector().getMaxParameterCount()); boolean success = false; try { File location; String locationStr = mce.getLocation(); if (locationStr == null || locationStr.length() == 0) { location = ((File) context.getServletContext().getAttribute( ServletContext.TEMPDIR)); } else { // If relative, it is relative to TEMPDIR location = new File(locationStr); if (!location.isAbsolute()) { location = new File( (File) context.getServletContext().getAttribute( ServletContext.TEMPDIR), locationStr).getAbsoluteFile(); } } if (!location.isDirectory()) { partsParseException = new IOException( sm.getString("coyoteRequest.uploadLocationInvalid", location)); return; } // Create a new file upload handler DiskFileItemFactory factory = new DiskFileItemFactory(); try { factory.setRepository(location.getCanonicalFile()); } catch (IOException ioe) { partsParseException = ioe; return; } factory.setSizeThreshold(mce.getFileSizeThreshold()); ServletFileUpload upload = new ServletFileUpload(); upload.setFileItemFactory(factory); upload.setFileSizeMax(mce.getMaxFileSize()); upload.setSizeMax(mce.getMaxRequestSize()); parts = new ArrayList<Part>(); try { List<FileItem> items = upload.parseRequest(this); int maxPostSize = getConnector().getMaxPostSize(); int postSize = 0; String enc = getCharacterEncoding(); Charset charset = null; if (enc != null) { try { charset = B2CConverter.getCharset(enc); } catch (UnsupportedEncodingException e) { // Ignore } } for (FileItem item : items) { ApplicationPart part = new ApplicationPart(item, mce); parts.add(part); if (part.getFilename() == null) { String name = part.getName(); String value = null; try { String encoding = parameters.getEncoding(); if (encoding == null) { encoding = Parameters.DEFAULT_ENCODING; } value = part.getString(encoding); } catch (UnsupportedEncodingException uee) { try { value = part.getString(Parameters.DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { // Should not be possible } } if (maxPostSize > 0) { // Have to calculate equivalent size. Not completely // accurate but close enough. if (charset == null) { // Name length postSize += name.getBytes().length; } else { postSize += name.getBytes(charset).length; } if (value != null) { // Equals sign postSize++; // Value length postSize += part.getSize(); } // Value separator postSize++; if (postSize > maxPostSize) { throw new IllegalStateException(sm.getString( "coyoteRequest.maxPostSizeExceeded")); } } parameters.addParameter(name, value); } } success = true; } catch (InvalidContentTypeException e) { partsParseException = new ServletException(e); } catch (FileUploadBase.SizeException e) { checkSwallowInput(); partsParseException = new IllegalStateException(e); } catch (FileUploadException e) { partsParseException = new IOException(e); } catch (IllegalStateException e) { checkSwallowInput(); partsParseException = e; } } finally { if (partsParseException != null || !success) { parameters.setParseFailed(true); } } }
// in java/org/apache/catalina/connector/Request.java
protected Session doGetSession(boolean create) { // There cannot be a session if no context has been assigned yet if (context == null) { return (null); } // Return the current session if it exists and is valid if ((session != null) && !session.isValid()) { session = null; } if (session != null) { return (session); } // Return the requested session if it exists and is valid Manager manager = null; if (context != null) { manager = context.getManager(); } if (manager == null) { return (null); // Sessions are not supported } if (requestedSessionId != null) { try { session = manager.findSession(requestedSessionId); } catch (IOException e) { session = null; } if ((session != null) && !session.isValid()) { session = null; } if (session != null) { session.access(); return (session); } } // Create a new session if requested and the response is not committed if (!create) { return (null); } if ((context != null) && (response != null) && context.getServletContext().getEffectiveSessionTrackingModes(). contains(SessionTrackingMode.COOKIE) && response.getResponse().isCommitted()) { throw new IllegalStateException (sm.getString("coyoteRequest.sessionCreateCommitted")); } // Attempt to reuse session id if one was submitted in a cookie // Do not reuse the session id if it is from a URL, to prevent possible // phishing attacks // Use the SSL session ID if one is present. if (("/".equals(context.getSessionCookiePath()) && isRequestedSessionIdFromCookie()) || requestedSessionSSL ) { session = manager.createSession(getRequestedSessionId()); } else { session = manager.createSession(null); } // Creating a new session cookie based on that session if ((session != null) && (getContext() != null) && getContext().getServletContext(). getEffectiveSessionTrackingModes().contains( SessionTrackingMode.COOKIE)) { Cookie cookie = ApplicationSessionCookieConfig.createSessionCookie( context, session.getIdInternal(), isSecure()); response.addSessionCookieInternal(cookie); } if (session == null) { return null; } session.access(); return session; }
// in java/org/apache/catalina/connector/Response.java
Override public ServletOutputStream getOutputStream() throws IOException { if (usingWriter) { throw new IllegalStateException (sm.getString("coyoteResponse.getOutputStream.ise")); } usingOutputStream = true; if (outputStream == null) { outputStream = new CoyoteOutputStream(outputBuffer); } return outputStream; }
// in java/org/apache/catalina/connector/Response.java
Override public PrintWriter getWriter() throws IOException { if (usingOutputStream) { throw new IllegalStateException (sm.getString("coyoteResponse.getWriter.ise")); } if (ENFORCE_ENCODING_IN_GET_WRITER) { /* * If the response's character encoding has not been specified as * described in <code>getCharacterEncoding</code> (i.e., the method * just returns the default value <code>ISO-8859-1</code>), * <code>getWriter</code> updates it to <code>ISO-8859-1</code> * (with the effect that a subsequent call to getContentType() will * include a charset=ISO-8859-1 component which will also be * reflected in the Content-Type response header, thereby satisfying * the Servlet spec requirement that containers must communicate the * character encoding used for the servlet response's writer to the * client). */ setCharacterEncoding(getCharacterEncoding()); } usingWriter = true; outputBuffer.checkConverter(); if (writer == null) { writer = new CoyoteWriter(outputBuffer); } return writer; }
// in java/org/apache/catalina/connector/Response.java
public void resetBuffer(boolean resetWriterStreamFlags) { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.resetBuffer.ise")); } outputBuffer.reset(resetWriterStreamFlags); if(resetWriterStreamFlags) { usingOutputStream = false; usingWriter = false; isCharacterEncodingSet = false; } }
// in java/org/apache/catalina/connector/Response.java
Override public void setBufferSize(int size) { if (isCommitted() || !outputBuffer.isNew()) { throw new IllegalStateException (sm.getString("coyoteResponse.setBufferSize.ise")); } outputBuffer.setBufferSize(size); }
// in java/org/apache/catalina/connector/Response.java
Override public void sendError(int status, String message) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendError.ise")); } // Ignore any call from an included servlet if (included) { return; } Wrapper wrapper = getRequest().getWrapper(); if (wrapper != null) { wrapper.incrementErrorCount(); } setError(); coyoteResponse.setStatus(status); coyoteResponse.setMessage(message); // Clear any data content that has been buffered resetBuffer(); // Cause the response to be finished (from the application perspective) setSuspended(true); }
// in java/org/apache/catalina/connector/Response.java
Override public void sendRedirect(String location) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendRedirect.ise")); } // Ignore any call from an included servlet if (included) { return; } // Clear any data content that has been buffered resetBuffer(true); // Generate a temporary redirect to the specified location try { String absolute = toAbsolute(location); setStatus(SC_FOUND); setHeader("Location", absolute); if (getContext().getSendRedirectBody()) { PrintWriter writer = getWriter(); writer.print(sm.getString("coyoteResponse.sendRedirect.note", RequestUtil.filter(absolute))); flushBuffer(); } } catch (IllegalArgumentException e) { setStatus(SC_NOT_FOUND); } // Cause the response to be finished (from the application perspective) setSuspended(true); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Object getAttribute(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getAttribute(name); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Enumeration<String> getAttributeNames() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetAttributePrivilegedAction()); } else { return request.getAttributeNames(); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getCharacterEncoding() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetCharacterEncodingPrivilegedAction()); } else { return request.getCharacterEncoding(); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public void setCharacterEncoding(String env) throws java.io.UnsupportedEncodingException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } request.setCharacterEncoding(env); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public int getContentLength() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getContentLength(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getContentType() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getContentType(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public ServletInputStream getInputStream() throws IOException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getInputStream(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getParameter(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetParameterPrivilegedAction(name)); } else { return request.getParameter(name); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Enumeration<String> getParameterNames() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetParameterNamesPrivilegedAction()); } else { return request.getParameterNames(); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String[] getParameterValues(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } String[] ret = null; /* * Clone the returned array only if there is a security manager * in place, so that performance won't suffer in the non-secure case */ if (SecurityUtil.isPackageProtectionEnabled()){ ret = AccessController.doPrivileged( new GetParameterValuePrivilegedAction(name)); if (ret != null) { ret = ret.clone(); } } else { ret = request.getParameterValues(name); } return ret; }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Map<String,String[]> getParameterMap() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetParameterMapPrivilegedAction()); } else { return request.getParameterMap(); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getProtocol() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getProtocol(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getScheme() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getScheme(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getServerName() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getServerName(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public int getServerPort() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getServerPort(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public BufferedReader getReader() throws IOException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getReader(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getRemoteAddr() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRemoteAddr(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getRemoteHost() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRemoteHost(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public void setAttribute(String name, Object o) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } request.setAttribute(name, o); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public void removeAttribute(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } request.removeAttribute(name); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Locale getLocale() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetLocalePrivilegedAction()); } else { return request.getLocale(); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Enumeration<Locale> getLocales() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetLocalesPrivilegedAction()); } else { return request.getLocales(); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean isSecure() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isSecure(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public RequestDispatcher getRequestDispatcher(String path) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetRequestDispatcherPrivilegedAction(path)); } else { return request.getRequestDispatcher(path); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getRealPath(String path) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRealPath(path); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getAuthType() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getAuthType(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Cookie[] getCookies() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } Cookie[] ret = null; /* * Clone the returned array only if there is a security manager * in place, so that performance won't suffer in the non-secure case */ if (SecurityUtil.isPackageProtectionEnabled()){ ret = AccessController.doPrivileged( new GetCookiesPrivilegedAction()); if (ret != null) { ret = ret.clone(); } } else { ret = request.getCookies(); } return ret; }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public long getDateHeader(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getDateHeader(name); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getHeader(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getHeader(name); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Enumeration<String> getHeaders(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetHeadersPrivilegedAction(name)); } else { return request.getHeaders(name); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Enumeration<String> getHeaderNames() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetHeaderNamesPrivilegedAction()); } else { return request.getHeaderNames(); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public int getIntHeader(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getIntHeader(name); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getMethod() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getMethod(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getPathInfo() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getPathInfo(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getPathTranslated() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getPathTranslated(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getContextPath() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getContextPath(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getQueryString() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getQueryString(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getRemoteUser() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRemoteUser(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean isUserInRole(String role) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isUserInRole(role); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public java.security.Principal getUserPrincipal() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getUserPrincipal(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getRequestedSessionId() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRequestedSessionId(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getRequestURI() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRequestURI(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public StringBuffer getRequestURL() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRequestURL(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getServletPath() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getServletPath(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public HttpSession getSession(boolean create) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (SecurityUtil.isPackageProtectionEnabled()){ return AccessController. doPrivileged(new GetSessionPrivilegedAction(create)); } else { return request.getSession(create); } }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public HttpSession getSession() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return getSession(true); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean isRequestedSessionIdValid() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isRequestedSessionIdValid(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean isRequestedSessionIdFromCookie() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isRequestedSessionIdFromCookie(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean isRequestedSessionIdFromURL() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isRequestedSessionIdFromURL(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean isRequestedSessionIdFromUrl() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isRequestedSessionIdFromURL(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getLocalAddr() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getLocalAddr(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public String getLocalName() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getLocalName(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public int getLocalPort() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getLocalPort(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public int getRemotePort() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRemotePort(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public ServletContext getServletContext() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getServletContext(); }
// in java/org/apache/catalina/connector/CometEventImpl.java
Override public void close() throws IOException { if (request == null) { throw new IllegalStateException(sm.getString("cometEvent.nullRequest")); } request.finishRequest(); response.finishResponse(); if (request.isComet()) { request.cometClose(); } }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
Override public boolean asyncDispatch(org.apache.coyote.Request req, org.apache.coyote.Response res, SocketStatus status) throws Exception { Request request = (Request) req.getNote(ADAPTER_NOTES); Response response = (Response) res.getNote(ADAPTER_NOTES); if (request == null) { throw new IllegalStateException( "Dispatch may only happen on an existing request."); } boolean comet = false; boolean success = true; AsyncContextImpl asyncConImpl = (AsyncContextImpl)request.getAsyncContext(); req.getRequestProcessor().setWorkerThreadName(Thread.currentThread().getName()); try { if (!request.isAsync() && !comet) { // Error or timeout - need to tell listeners the request is over // Have to test this first since state may change while in this // method and this is only required if entering this method in // this state Context ctxt = (Context) request.getMappingData().context; if (ctxt != null) { ctxt.fireRequestDestroyEvent(request); } // Lift any suspension (e.g. if sendError() was used by an async // request) to allow the response to be written to the client response.setSuspended(false); } if (status==SocketStatus.TIMEOUT) { success = true; if (!asyncConImpl.timeout()) { asyncConImpl.setErrorState(null); } } if (request.isAsyncDispatching()) { success = true; connector.getService().getContainer().getPipeline().getFirst().invoke(request, response); Throwable t = (Throwable) request.getAttribute( RequestDispatcher.ERROR_EXCEPTION); if (t != null) { asyncConImpl.setErrorState(t); } } if (request.isComet()) { if (!response.isClosed() && !response.isError()) { if (request.getAvailable() || (request.getContentLength() > 0 && (!request.isParametersParsed()))) { // Invoke a read event right away if there are available bytes if (event(req, res, SocketStatus.OPEN)) { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { // Clear the filter chain, as otherwise it will not be reset elsewhere // since this is a Comet request request.setFilterChain(null); } } if (!request.isAsync() && !comet) { request.finishRequest(); response.finishResponse(); req.action(ActionCode.POST_REQUEST , null); ((Context) request.getMappingData().context).logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); } } catch (IOException e) { success = false; // Ignore } catch (Throwable t) { ExceptionUtils.handleThrowable(t); success = false; log.error(sm.getString("coyoteAdapter.service"), t); } finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!success || (!comet && !request.isAsync())) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } } return success; }
// in java/org/apache/catalina/connector/ResponseFacade.java
public void finish() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } response.setSuspended(true); }
// in java/org/apache/catalina/connector/ResponseFacade.java
public boolean isFinished() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.isSuspended(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
public long getContentWritten() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.getContentWritten(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public String getCharacterEncoding() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.getCharacterEncoding(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void setBufferSize(int size) { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.setBufferSize.ise")); } response.setBufferSize(size); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public int getBufferSize() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.getBufferSize(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void resetBuffer() { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.resetBuffer.ise")); } response.resetBuffer(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public boolean isCommitted() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return (response.isAppCommitted()); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void reset() { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.reset.ise")); } response.reset(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public Locale getLocale() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.getLocale(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public boolean containsHeader(String name) { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.containsHeader(name); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public String encodeURL(String url) { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.encodeURL(url); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public String encodeRedirectURL(String url) { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.encodeRedirectURL(url); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public String encodeUrl(String url) { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.encodeURL(url); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public String encodeRedirectUrl(String url) { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.encodeRedirectURL(url); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void sendError(int sc, String msg) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendError.ise")); } response.setAppCommitted(true); response.sendError(sc, msg); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void sendError(int sc) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendError.ise")); } response.setAppCommitted(true); response.sendError(sc); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void sendRedirect(String location) throws IOException { if (isCommitted()) { throw new IllegalStateException (sm.getString("coyoteResponse.sendRedirect.ise")); } response.setAppCommitted(true); response.sendRedirect(location); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public String getContentType() { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } return response.getContentType(); }
// in java/org/apache/catalina/connector/ResponseFacade.java
Override public void setCharacterEncoding(String arg0) { if (response == null) { throw new IllegalStateException( sm.getString("responseFacade.nullResponse")); } response.setCharacterEncoding(arg0); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
private static void initializeSSL() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { if ("off".equalsIgnoreCase(SSLEngine)) { return; } if (sslInitialized) { //only once per VM return; } sslInitialized = true; String methodName = "randSet"; Class<?> paramTypes[] = new Class[1]; paramTypes[0] = String.class; Object paramValues[] = new Object[1]; paramValues[0] = SSLRandomSeed; Class<?> clazz = Class.forName("org.apache.tomcat.jni.SSL"); Method method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); methodName = "initialize"; paramValues[0] = "on".equalsIgnoreCase(SSLEngine)?null:SSLEngine; method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); if("on".equalsIgnoreCase(FIPSMode)) { log.info(sm.getString("aprListener.initializingFIPS")); int result = SSL.fipsModeSet(1); // success is defined as return value = 1 if(1 == result) { fipsModeActive = true; log.info(sm.getString("aprListener.initializeFIPSSuccess")); } else { // This case should be handled by the native method, // but we'll make absolutely sure, here. String message = sm.getString("aprListener.initializeFIPSFailed"); log.error(message); throw new IllegalStateException(message); } } log.info(sm.getString("aprListener.initializedOpenSSL", SSL.versionString())); sslAvailable = true; }
// in java/org/apache/catalina/core/AprLifecycleListener.java
public void setSSLEngine(String SSLEngine) { if (!SSLEngine.equals(AprLifecycleListener.SSLEngine)) { // Ensure that the SSLEngine is consistent with that used for SSL init if (sslInitialized) { throw new IllegalStateException( sm.getString("aprListener.tooLateForSSLEngine")); } AprLifecycleListener.SSLEngine = SSLEngine; } }
// in java/org/apache/catalina/core/AprLifecycleListener.java
public void setSSLRandomSeed(String SSLRandomSeed) { if (!SSLRandomSeed.equals(AprLifecycleListener.SSLRandomSeed)) { // Ensure that the random seed is consistent with that used for SSL init if (sslInitialized) { throw new IllegalStateException( sm.getString("aprListener.tooLateForSSLRandomSeed")); } AprLifecycleListener.SSLRandomSeed = SSLRandomSeed; } }
// in java/org/apache/catalina/core/AprLifecycleListener.java
public void setFIPSMode(String FIPSMode) { if (!FIPSMode.equals(AprLifecycleListener.FIPSMode)) { // Ensure that the FIPS mode is consistent with that used for SSL init if (sslInitialized) { throw new IllegalStateException( sm.getString("aprListener.tooLateForFIPSMode")); } AprLifecycleListener.FIPSMode = FIPSMode; } }
// in java/org/apache/catalina/core/ApplicationContext.java
private FilterRegistration.Dynamic addFilter(String filterName, String filterClass, Filter filter) throws IllegalStateException { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addFilter.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. FilterDef filterDef = context.findFilterDef(filterName); // Assume a 'complete' FilterRegistration is one that has a class and // a name if (filterDef == null) { filterDef = new FilterDef(); filterDef.setFilterName(filterName); context.addFilterDef(filterDef); } else { if (filterDef.getFilterName() != null && filterDef.getFilterClass() != null) { return null; } } if (filter == null) { filterDef.setFilterClass(filterClass); } else { filterDef.setFilterClass(filter.getClass().getName()); filterDef.setFilter(filter); } return new ApplicationFilterRegistration(filterDef, context); }
// in java/org/apache/catalina/core/ApplicationContext.java
private ServletRegistration.Dynamic addServlet(String servletName, String servletClass, Servlet servlet) throws IllegalStateException { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addServlet.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. Wrapper wrapper = (Wrapper) context.findChild(servletName); // Assume a 'complete' ServletRegistration is one that has a class and // a name if (wrapper == null) { wrapper = context.createWrapper(); wrapper.setName(servletName); context.addChild(wrapper); } else { if (wrapper.getName() != null && wrapper.getServletClass() != null) { if (wrapper.isOverridable()) { wrapper.setOverridable(false); } else { return null; } } } if (servlet == null) { wrapper.setServletClass(servletClass); } else { wrapper.setServletClass(servlet.getClass().getName()); wrapper.setServlet(servlet); } return context.dynamicServletAdded(wrapper); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public void setSessionTrackingModes( Set<SessionTrackingMode> sessionTrackingModes) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException( sm.getString("applicationContext.setSessionTracking.ise", getContextPath())); } // Check that only supported tracking modes have been requested for (SessionTrackingMode sessionTrackingMode : sessionTrackingModes) { if (!supportedSessionTrackingModes.contains(sessionTrackingMode)) { throw new IllegalArgumentException(sm.getString( "applicationContext.setSessionTracking.iae.invalid", sessionTrackingMode.toString(), getContextPath())); } } // Check SSL has not be configured with anything else if (sessionTrackingModes.contains(SessionTrackingMode.SSL)) { if (sessionTrackingModes.size() > 1) { throw new IllegalArgumentException(sm.getString( "applicationContext.setSessionTracking.iae.ssl", getContextPath())); } } this.sessionTrackingModes = sessionTrackingModes; }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends EventListener> void addListener(T t) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException( sm.getString("applicationContext.addListener.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. boolean match = false; if (t instanceof ServletContextAttributeListener || t instanceof ServletRequestListener || t instanceof ServletRequestAttributeListener || t instanceof HttpSessionAttributeListener) { context.addApplicationEventListener(t); match = true; } if (t instanceof HttpSessionListener || (t instanceof ServletContextListener && newServletContextListenerAllowed)) { context.addApplicationLifecycleListener(t); match = true; } if (match) return; if (t instanceof ServletContextListener) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.sclNotAllowed", t.getClass().getName())); } else { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", t.getClass().getName())); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public void declareRoles(String... roleNames) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addRole.ise", getContextPath())); } if (roleNames == null) { throw new IllegalArgumentException( sm.getString("applicationContext.roles.iae", getContextPath())); } for (String role : roleNames) { if (role == null || "".equals(role)) { throw new IllegalArgumentException( sm.getString("applicationContext.role.iae", getContextPath())); } context.addSecurityRole(role); } }
// in java/org/apache/catalina/core/ContainerBase.java
private void addChildInternal(Container child) { if( log.isDebugEnabled() ) log.debug("Add child " + child + " " + this); synchronized(children) { if (children.get(child.getName()) != null) throw new IllegalArgumentException("addChild: Child name '" + child.getName() + "' is not unique"); child.setParent(this); // May throw IAE children.put(child.getName(), child); } // Start child // Don't do this inside sync block - start can be a slow process and // locking the children object can cause problems elsewhere if ((getState().isAvailable() || LifecycleState.STARTING_PREP.equals(getState())) && startChildren) { try { child.start(); } catch (LifecycleException e) { log.error("ContainerBase.addChild: start: ", e); throw new IllegalStateException ("ContainerBase.addChild: start: " + e); } } fireContainerEvent(ADD_CHILD_EVENT, child); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
private void check() { if (request == null) { // AsyncContext has been recycled and should not be being used throw new IllegalStateException(sm.getString( "asyncContextImpl.requestEnded")); } }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
Override public void execute(Runnable command, long timeout, TimeUnit unit) { if ( executor != null ) { executor.execute(command,timeout,unit); } else { throw new IllegalStateException("StandardThreadExecutor not started."); } }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
Override public void execute(Runnable command) { if ( executor != null ) { try { executor.execute(command); } catch (RejectedExecutionException rx) { //there could have been contention around the queue if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException("Work queue full."); } } else throw new IllegalStateException("StandardThreadPool not started."); }
// in java/org/apache/catalina/core/StandardContext.java
Override public synchronized void setResources(DirContext resources) { if (getState().isAvailable()) { throw new IllegalStateException (sm.getString("standardContext.resources.started")); } DirContext oldResources = this.webappResources; if (oldResources == resources) return; if (resources instanceof BaseDirContext) { // Caching ((BaseDirContext) resources).setCached(isCachingAllowed()); ((BaseDirContext) resources).setCacheTTL(getCacheTTL()); ((BaseDirContext) resources).setCacheMaxSize(getCacheMaxSize()); ((BaseDirContext) resources).setCacheObjectMaxSize( getCacheObjectMaxSize()); // Alias support ((BaseDirContext) resources).setAliases(getAliases()); } if (resources instanceof FileDirContext) { ((FileDirContext) resources).setAllowLinking(isAllowLinking()); } this.webappResources = resources; // The proxied resources will be refreshed on start this.resources = null; support.firePropertyChange("resources", oldResources, this.webappResources); }
// in java/org/apache/catalina/core/StandardContext.java
Override public synchronized void reload() { // Validate our current component state if (!getState().isAvailable()) throw new IllegalStateException (sm.getString("standardContext.notStarted", getName())); if(log.isInfoEnabled()) log.info(sm.getString("standardContext.reloadingStarted", getName())); // Stop accepting requests temporarily. setPaused(true); try { stop(); } catch (LifecycleException e) { log.error( sm.getString("standardContext.stoppingContext", getName()), e); } try { start(); } catch (LifecycleException e) { log.error( sm.getString("standardContext.startingContext", getName()), e); } setPaused(false); if(log.isInfoEnabled()) log.info(sm.getString("standardContext.reloadingCompleted", getName())); }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public void addChild(Container child) { throw new IllegalStateException (sm.getString("standardWrapper.notChild")); }
// in java/org/apache/catalina/core/ApplicationServletRegistration.java
Override public Set<String> setServletSecurity(ServletSecurityElement constraint) { if (constraint == null) { throw new IllegalArgumentException(sm.getString( "applicationServletRegistration.setServletSecurity.iae", getName(), context.getName())); } if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException(sm.getString( "applicationServletRegistration.setServletSecurity.ise", getName(), context.getName())); } return context.addServletSecurity(this, constraint); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void doForward(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Reset any output that has been buffered, but keep headers/cookies if (response.isCommitted()) { throw new IllegalStateException (sm.getString("applicationDispatcher.forward.ise")); } try { response.resetBuffer(); } catch (IllegalStateException e) { throw e; } // Set up to handle the specified request and response State state = new State(request, response, false); if (WRAP_SAME_OBJECT) { // Check SRV.8.2 / SRV.14.2.5.1 compliance checkSameObjects(request, response); } wrapResponse(state); // Handle an HTTP named dispatcher forward if ((servletPath == null) && (pathInfo == null)) { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); HttpServletRequest hrequest = state.hrequest; wrequest.setRequestURI(hrequest.getRequestURI()); wrequest.setContextPath(hrequest.getContextPath()); wrequest.setServletPath(hrequest.getServletPath()); wrequest.setPathInfo(hrequest.getPathInfo()); wrequest.setQueryString(hrequest.getQueryString()); processRequest(request,response,state); } // Handle an HTTP path-based forward else { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); String contextPath = context.getPath(); HttpServletRequest hrequest = state.hrequest; if (hrequest.getAttribute( RequestDispatcher.FORWARD_REQUEST_URI) == null) { wrequest.setAttribute(RequestDispatcher.FORWARD_REQUEST_URI, hrequest.getRequestURI()); wrequest.setAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH, hrequest.getContextPath()); wrequest.setAttribute(RequestDispatcher.FORWARD_SERVLET_PATH, hrequest.getServletPath()); wrequest.setAttribute(RequestDispatcher.FORWARD_PATH_INFO, hrequest.getPathInfo()); wrequest.setAttribute(RequestDispatcher.FORWARD_QUERY_STRING, hrequest.getQueryString()); } wrequest.setContextPath(contextPath); wrequest.setRequestURI(requestURI); wrequest.setServletPath(servletPath); wrequest.setPathInfo(pathInfo); if (queryString != null) { wrequest.setQueryString(queryString); wrequest.setQueryParams(queryString); } processRequest(request,response,state); } // This is not a real close in order to support error processing if (wrapper.getLogger().isDebugEnabled() ) wrapper.getLogger().debug(" Disabling the response for futher output"); if (response instanceof ResponseFacade) { ((ResponseFacade) response).finish(); } else { // Servlet SRV.6.2.2. The Request/Response may have been wrapped // and may no longer be instance of RequestFacade if (wrapper.getLogger().isDebugEnabled()){ wrapper.getLogger().debug( " The Response is vehiculed using a wrapper: " + response.getClass().getName() ); } // Close anyway try { PrintWriter writer = response.getWriter(); writer.close(); } catch (IllegalStateException e) { try { ServletOutputStream stream = response.getOutputStream(); stream.close(); } catch (IllegalStateException f) { // Ignore } catch (IOException f) { // Ignore } } catch (IOException e) { // Ignore } } }
// in java/org/apache/catalina/util/ParameterMap.java
Override public void clear() { if (locked) throw new IllegalStateException (sm.getString("parameterMap.locked")); super.clear(); }
// in java/org/apache/catalina/util/ParameterMap.java
Override public V put(K key, V value) { if (locked) throw new IllegalStateException (sm.getString("parameterMap.locked")); return (super.put(key, value)); }
// in java/org/apache/catalina/util/ParameterMap.java
Override public void putAll(Map<? extends K,? extends V> map) { if (locked) throw new IllegalStateException (sm.getString("parameterMap.locked")); super.putAll(map); }
// in java/org/apache/catalina/util/ParameterMap.java
Override public V remove(Object key) { if (locked) throw new IllegalStateException (sm.getString("parameterMap.locked")); return (super.remove(key)); }
// in java/org/apache/catalina/util/ResourceSet.java
Override public boolean add(T o) { if (locked) throw new IllegalStateException (sm.getString("resourceSet.locked")); return (super.add(o)); }
// in java/org/apache/catalina/util/ResourceSet.java
Override public void clear() { if (locked) throw new IllegalStateException (sm.getString("resourceSet.locked")); super.clear(); }
// in java/org/apache/catalina/util/ResourceSet.java
Override public boolean remove(Object o) { if (locked) throw new IllegalStateException (sm.getString("resourceSet.locked")); return (super.remove(o)); }
12
            
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch (ClassNotFoundException ex) { throw new IllegalStateException(ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (MalformedURLException e) { throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"), e); }
// in java/org/apache/coyote/http11/filters/BufferedInputFilter.java
catch(IOException ioe) { // No need for i18n - this isn't going to get logged anywhere throw new IllegalStateException( "Request body too large for buffer"); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { log.error("Couldn't get MD5 digest: ", e); throw new IllegalStateException(e.getMessage()); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "expiresFilter.startingPointNotFound", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { throw new IllegalStateException(sm.getString( "Invalid duration (number) '{}' in directive '{}'", currentToken, line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException( sm.getString( "Duration unit not found after amount {} in directive '{}'", Integer.valueOf(amount), line)); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (ClassNotFoundException e) { String msg = sm.getString( "persistentManager.deserializeError", id); log.error(msg, e); throw new IllegalStateException(msg, e); }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new IllegalStateException(); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.addChild: start: ", e); throw new IllegalStateException ("ContainerBase.addChild: start: " + e); }
22
            
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) throws IOException, IllegalStateException, IllegalArgumentException { }
// in java/org/apache/jasper/runtime/JspApplicationContextImpl.java
Override public void addELResolver(ELResolver resolver) throws IllegalStateException { if (resolver == null) { throw new IllegalArgumentException("ELResolver was null"); } if (this.instantiated) { throw new IllegalStateException( "cannot call addELResolver after the first request has been made"); } this.resolvers.add(resolver); }
// in java/org/apache/coyote/Response.java
public void reset() throws IllegalStateException { // Reset the headers only if this is the main request, // not for included contentType = null; locale = DEFAULT_LOCALE; contentLanguage = null; characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; contentLength = -1; charsetSet = false; status = 200; message = null; headers.clear(); // Force the PrintWriter to flush its data to the output // stream before resetting the output stream // // Reset the stream if (commited) { //String msg = sm.getString("servletOutputStreamImpl.reset.ise"); throw new IllegalStateException(); } action(ActionCode.RESET, this); }
// in java/org/apache/coyote/http11/AbstractOutputBuffer.java
private void checkLengthBeforeWrite(int length) throws IllegalStateException { if (pos + length > buf.length) { throw new IllegalStateException( sm.getString("iob.responseheadertoolarge.error")); } }
// in java/org/apache/tomcat/util/http/Parameters.java
public void addParameter( String key, String value ) throws IllegalStateException { if( key==null ) { return; } parameterCount ++; if (limit > -1 && parameterCount > limit) { // Processing this parameter will push us over the limit. ISE is // what Request.parseParts() uses for requests that are too big parseFailed = true; throw new IllegalStateException(sm.getString( "parameters.maxCountFail", Integer.valueOf(limit))); } ArrayList<String> values = paramHashValues.get(key); if (values == null) { values = new ArrayList<String>(1); paramHashValues.put(key, values); } values.add(value); }
// in java/org/apache/catalina/connector/Request.java
Override public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException { parseParts(); if (partsParseException != null) { if (partsParseException instanceof IOException) { throw (IOException) partsParseException; } else if (partsParseException instanceof IllegalStateException) { throw (IllegalStateException) partsParseException; } else if (partsParseException instanceof ServletException) { throw (ServletException) partsParseException; } } return parts; }
// in java/org/apache/catalina/connector/Request.java
Override public Part getPart(String name) throws IOException, IllegalStateException, ServletException { Collection<Part> c = getParts(); Iterator<Part> iterator = c.iterator(); while (iterator.hasNext()) { Part part = iterator.next(); if (name.equals(part.getName())) { return part; } } return null; }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public AsyncContext startAsync() throws IllegalStateException { return request.startAsync(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public AsyncContext startAsync(ServletRequest request, ServletResponse response) throws IllegalStateException { return this.request.startAsync(request, response); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Collection<Part> getParts() throws IllegalStateException, IOException, ServletException { return request.getParts(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Part getPart(String name) throws IllegalStateException, IOException, ServletException { return request.getPart(name); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public FilterRegistration.Dynamic addFilter(String filterName, String filterClass) throws IllegalStateException { return addFilter(filterName, filterClass, null); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) throws IllegalStateException { return addFilter(filterName, null, filter); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) throws IllegalStateException { return addFilter(filterName, filterClass.getName(), null); }
// in java/org/apache/catalina/core/ApplicationContext.java
private FilterRegistration.Dynamic addFilter(String filterName, String filterClass, Filter filter) throws IllegalStateException { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addFilter.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. FilterDef filterDef = context.findFilterDef(filterName); // Assume a 'complete' FilterRegistration is one that has a class and // a name if (filterDef == null) { filterDef = new FilterDef(); filterDef.setFilterName(filterName); context.addFilterDef(filterDef); } else { if (filterDef.getFilterName() != null && filterDef.getFilterClass() != null) { return null; } } if (filter == null) { filterDef.setFilterClass(filterClass); } else { filterDef.setFilterClass(filter.getClass().getName()); filterDef.setFilter(filter); } return new ApplicationFilterRegistration(filterDef, context); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public ServletRegistration.Dynamic addServlet(String servletName, String servletClass) throws IllegalStateException { return addServlet(servletName, servletClass, null); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) throws IllegalStateException { return addServlet(servletName, null, servlet); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) throws IllegalStateException { return addServlet(servletName, servletClass.getName(), null); }
// in java/org/apache/catalina/core/ApplicationContext.java
private ServletRegistration.Dynamic addServlet(String servletName, String servletClass, Servlet servlet) throws IllegalStateException { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addServlet.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. Wrapper wrapper = (Wrapper) context.findChild(servletName); // Assume a 'complete' ServletRegistration is one that has a class and // a name if (wrapper == null) { wrapper = context.createWrapper(); wrapper.setName(servletName); context.addChild(wrapper); } else { if (wrapper.getName() != null && wrapper.getServletClass() != null) { if (wrapper.isOverridable()) { wrapper.setOverridable(false); } else { return null; } } } if (servlet == null) { wrapper.setServletClass(servletClass); } else { wrapper.setServletClass(servlet.getClass().getName()); wrapper.setServlet(servlet); } return context.dynamicServletAdded(wrapper); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public Collection<Part> getParts() throws IllegalStateException, IOException, ServletException { return this._getHttpServletRequest().getParts(); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public Part getPart(String name) throws IllegalStateException, IOException, ServletException { return this._getHttpServletRequest().getPart(name); }
// in java/javax/servlet/ServletRequestWrapper.java
Override public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { return request.startAsync(servletRequest, servletResponse); }
39
            
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch(IllegalStateException ise) { // Session has been invalidated. // Ignore and fall through to application scope. }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch(IllegalStateException ise) { // Session has been invalidated. // Ignore and fall through to application scope. }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch(IllegalStateException ise) { // Session has been invalidated. // Ignore and fall throw to application scope. }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (IllegalStateException ise) { include(errorPageURL); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IllegalStateException ise) { log.error(Localizer.getMessage("jsp.error.file.not.found", jspUri)); }
// in java/org/apache/juli/ClassLoaderLogManager.java
catch (IllegalStateException ise) { // We are probably already being shutdown. Ignore this error. }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (IllegalStateException ise) { // Hitting limit stops processing further params but does // not cause request to fail. parseFailed = true; UserDataHelper.Mode logMode = maxParamCountLog.getNextMode(); if (logMode != null) { String message = ise.getMessage(); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString( "parameters.maxCountFail.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); break; case DEBUG: log.debug(message); } } break; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (IllegalStateException e) { log.info(sm.getString("webappClassLoader.stopped", name), e); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (IllegalStateException ise) { // at least 1 of the sessions is invalidated req.setAttribute(APPLICATION_ERROR, "Can't sort session list: one session is invalidated"); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (IllegalStateException ise) { if (debug >= 1) { log("Can't invalidate already invalidated session id " + sessionId); } }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (IllegalStateException ise) { if (debug >= 1) { log("Can't remote attribute '" + attributeName + "' for invalidated session id " + sessionId); } }
// in java/org/apache/catalina/manager/JspHelper.java
catch (IllegalStateException ise) { //ignore: invalidated session return ""; }
// in java/org/apache/catalina/manager/JspHelper.java
catch (IllegalStateException ise) { //ignore: invalidated session return ""; }
// in java/org/apache/catalina/manager/JspHelper.java
catch (IllegalStateException ise) { //ignore: invalidated session return ""; }
// in java/org/apache/catalina/manager/JspHelper.java
catch (IllegalStateException ise) { //ignore: invalidated session return ""; }
// in java/org/apache/catalina/manager/JspHelper.java
catch (IllegalStateException ise) { //ignore: invalidated session return ""; }
// in java/org/apache/catalina/manager/util/SessionUtils.java
catch (IllegalStateException ise) { //ignore: invalidated session return null; }
// in java/org/apache/catalina/manager/util/SessionUtils.java
catch (IllegalStateException ise) { //ignore: invalidated session return null; }
// in java/org/apache/catalina/manager/util/SessionUtils.java
catch (IllegalStateException ise) { //ignore: invalidated session return -1; }
// in java/org/apache/catalina/manager/util/SessionUtils.java
catch (IllegalStateException ise) { //ignore: invalidated session return -1; }
// in java/org/apache/catalina/manager/util/SessionUtils.java
catch (IllegalStateException ise) { //ignore: invalidated session return -1; }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (IllegalStateException ise) { log.debug("Unable to decode message.",ise); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (IllegalStateException e) { // Ignore }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (IllegalStateException e) { // Ignore }
// in java/org/apache/catalina/authenticator/SSLAuthenticator.java
catch (IllegalStateException ise) { // Request body was too large for save buffer response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.certificates")); return false; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalStateException e) { // Silent catch }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalStateException e) { // Silent catch }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalStateException e) { // Silent catch }
// in java/org/apache/catalina/ssi/SSIFilter.java
catch (IllegalStateException e) { // Ignore, will try to use a writer }
// in java/org/apache/catalina/connector/Request.java
catch (IllegalStateException e) { checkSwallowInput(); partsParseException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IllegalStateException e) { throw e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IllegalStateException e) { try { ServletOutputStream stream = response.getOutputStream(); stream.close(); } catch (IllegalStateException f) { // Ignore } catch (IOException f) { // Ignore } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IllegalStateException f) { // Ignore }
6
            
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (IllegalStateException e) { throw e; }
0
unknown (Lib) IllegalThreadStateException 0 0 0 1
            
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IllegalThreadStateException e) { try { Thread.sleep(500); } catch (InterruptedException ignored) { // Ignore } }
0 0
unknown (Domain) ImmutableNameNotFoundException
public class ImmutableNameNotFoundException
    extends NameNotFoundException {

    private static final long serialVersionUID = 1L;

    @Override
    public void appendRemainingComponent(String name) {/*NOOP*/}
    @Override
    public void appendRemainingName(Name name) {/*NOOP*/}
    @Override
    public void setRemainingName(Name name) {/*NOOP*/}
    @Override
    public void setResolvedName(Name name) {/*NOOP*/}
    @Override
    public void setRootCause(Throwable e) {/*NOOP*/}

    @Override
    public synchronized Throwable fillInStackTrace() {
        // This class does not provide a stack trace
        return this;
    }
}
0 0 0 0 0 0
unknown (Lib) IndexOutOfBoundsException 4
            
// in java/org/apache/jasper/runtime/BodyContentImpl.java
Override public void write(char[] cbuf, int off, int len) throws IOException { if (writer != null) { writer.write(cbuf, off, len); } else { ensureOpen(); if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } if (len >= bufferSize - nextChar) reAllocBuff (len); System.arraycopy(cbuf, off, cb, nextChar, len); nextChar+=len; } }
// in java/org/apache/jasper/runtime/JspWriterImpl.java
Override public void write(char cbuf[], int off, int len) throws IOException { ensureOpen(); if (bufferSize == 0) { initOut(); out.write(cbuf, off, len); return; } if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } if (len >= bufferSize) { /* If the request length exceeds the size of the output buffer, flush the buffer and then write the data directly. In this way buffered streams will cascade harmlessly. */ if (autoFlush) flushBuffer(); else bufferOverflow(); initOut(); out.write(cbuf, off, len); return; } int b = off, t = off + len; while (b < t) { int d = min(bufferSize - nextChar, t - b); System.arraycopy(cbuf, b, cb, nextChar, d); b += d; nextChar += d; if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); } }
// in java/org/apache/tomcat/util/http/fileupload/ByteArrayOutputStream.java
Override public void write(byte[] b, int off, int len) { if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } synchronized (this) { int newcount = count + len; int remaining = len; int inBufferPos = count - filledBufferSum; while (remaining > 0) { int part = Math.min(remaining, currentBuffer.length - inBufferPos); System.arraycopy(b, off + len - remaining, currentBuffer, inBufferPos, part); remaining -= part; if (remaining > 0) { needNewBuffer(newcount); inBufferPos = 0; } } count = newcount; } }
// in java/org/apache/catalina/tribes/io/XByteBuffer.java
public boolean append(byte[] b, int off, int len) { if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return false; } int newcount = bufSize + len; if (newcount > buf.length) { expand(newcount); } System.arraycopy(b, off, buf, bufSize, len); bufSize = newcount; if ( discard ) { if (bufSize > START_DATA.length && (firstIndexOf(buf, 0, START_DATA) == -1)) { bufSize = 0; log.error("Discarded the package, invalid header"); return false; } } return true; }
0 0 1
            
// in java/javax/el/ListELResolver.java
catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); }
1
            
// in java/javax/el/ListELResolver.java
catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); }
1
unknown (Lib) InstanceNotFoundException 0 0 4
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public DynamicMBean createMBean() throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { return (createMBean(null)); }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public DynamicMBean createMBean(Object instance) throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { BaseModelMBean mbean = null; // Load the ModelMBean implementation class if(getClassName().equals(BASE_MBEAN)) { // Skip introspection mbean = new BaseModelMBean(); } else { Class<?> clazz = null; Exception ex = null; try { clazz = Class.forName(getClassName()); } catch (Exception e) { } if( clazz==null ) { try { ClassLoader cl= Thread.currentThread().getContextClassLoader(); if ( cl != null) clazz= cl.loadClass(getClassName()); } catch (Exception e) { ex=e; } } if( clazz==null) { throw new MBeanException (ex, "Cannot load ModelMBean class " + getClassName()); } try { // Stupid - this will set the default minfo first.... mbean = (BaseModelMBean) clazz.newInstance(); } catch (RuntimeOperationsException e) { throw e; } catch (Exception e) { throw new MBeanException (e, "Cannot instantiate ModelMBean of class " + getClassName()); } } mbean.setManagedBean(this); // Set the managed resource (if any) try { if (instance != null) mbean.setManagedResource(instance, "ObjectReference"); } catch (InstanceNotFoundException e) { throw e; } return (mbean); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
public Object getManagedResource() throws InstanceNotFoundException, InvalidTargetObjectTypeException, MBeanException, RuntimeOperationsException { if (resource == null) throw new RuntimeOperationsException (new IllegalArgumentException("Managed resource is null"), "Managed resource is null"); return resource; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
public void setManagedResource(Object resource, String type) throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { if (resource == null) throw new RuntimeOperationsException (new IllegalArgumentException("Managed resource is null"), "Managed resource is null"); // if (!"objectreference".equalsIgnoreCase(type)) // throw new InvalidTargetObjectTypeException(type); this.resource = resource; this.resourceType = resource.getClass().getName(); // // Make the resource aware of the model mbean. // try { // Method m=resource.getClass().getMethod("setModelMBean", // new Class[] {ModelMBean.class}); // if( m!= null ) { // m.invoke(resource, new Object[] {this}); // } // } catch( NoSuchMethodException t ) { // // ignore // } catch( Throwable t ) { // log.error( "Can't set model mbean ", t ); // } }
30
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (InstanceNotFoundException e) { throw e; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (InstanceNotFoundException e) { log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", on), e); }
29
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (InstanceNotFoundException e) { throw e; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
0
unknown (Lib) InstantiationException 1
            
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
protected TrustManager[] getTrustManagers(String keystoreType, String keystoreProvider, String algorithm) throws Exception { String crlf = endpoint.getCrlFile(); String className = endpoint.getTrustManagerClassName(); if(className != null && className.length() > 0) { ClassLoader classLoader = getClass().getClassLoader(); Class<?> clazz = classLoader.loadClass(className); if(!(TrustManager.class.isAssignableFrom(clazz))){ throw new InstantiationException(sm.getString( "jsse.invalidTrustManagerClassName", className)); } Object trustManagerObject = clazz.newInstance(); TrustManager trustManager = (TrustManager) trustManagerObject; return new TrustManager[]{ trustManager }; } TrustManager[] tms = null; KeyStore trustStore = getTrustStore(keystoreType, keystoreProvider); if (trustStore != null || endpoint.getTrustManagerClassName() != null) { if (crlf == null) { TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init(trustStore); tms = tmf.getTrustManagers(); } else { TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); CertPathParameters params = getParameters(algorithm, crlf, trustStore); ManagerFactoryParameters mfp = new CertPathTrustManagerParameters(params); tmf.init(mfp); tms = tmf.getTrustManagers(); } } return tms; }
0 5
            
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
Filter getFilter() throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { // Return the existing filter instance, if any if (this.filter != null) return (this.filter); // Identify the class loader we will be using String filterClass = filterDef.getFilterClass(); this.filter = (Filter) getInstanceManager().newInstance(filterClass); initFilter(); return (this.filter); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
void setFilterDef(FilterDef filterDef) throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { this.filterDef = filterDef; if (filterDef == null) { // Release any previously allocated filter instance if (this.filter != null){ if (Globals.IS_SECURITY_ENABLED) { try{ SecurityUtil.doAsPrivilege("destroy", filter); } catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); } SecurityUtil.remove(filter); } else { filter.destroy(); } if (!context.getIgnoreAnnotations()) { try { ((StandardContext) context).getInstanceManager().destroyInstance(this.filter); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); } } } this.filter = null; } else { // Allocate a new filter instance if necessary if (filterDef.getFilter() == null) { getFilter(); } } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { Class<?> clazz = loadClassMaybePrivileged(className, classLoader); return newInstance(clazz.newInstance(), clazz); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(final String className, final ClassLoader classLoader) throws IllegalAccessException, NamingException, InvocationTargetException, InstantiationException, ClassNotFoundException { Class<?> clazz = classLoader.loadClass(className); return newInstance(clazz.newInstance(), clazz); }
17
            
// in java/org/apache/jasper/JspCompilationContext.java
catch (InstantiationException e) { log.warn(Localizer.getMessage("jsp.error.compiler"), e); }
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.InstantiationException ie2) { NamingException ne = new NamingException(ie2.getMessage()); ne.setRootCause(ie2); throw ne; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (InstantiationException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (InstantiationException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.InstantiationException", className), e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (InstantiationException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/session/JDBCStore.java
catch (InstantiationException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (InstantiationException e) { ServletException se = new ServletException(e); throw se; }
// in java/javax/el/ExpressionFactory.java
catch (InstantiationException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
15
            
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.InstantiationException ie2) { NamingException ne = new NamingException(ie2.getMessage()); ne.setRootCause(ie2); throw ne; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (InstantiationException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (InstantiationException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.InstantiationException", className), e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
catch (InstantiationException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (InstantiationException e) { ServletException se = new ServletException(e); throw se; }
// in java/javax/el/ExpressionFactory.java
catch (InstantiationException e) { throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
2
unknown (Lib) InterruptedException 0 0 8
            
// in java/org/apache/tomcat/util/net/NioEndpoint.java
protected void awaitLatch(CountDownLatch latch, long timeout, TimeUnit unit) throws InterruptedException { if ( latch == null ) throw new IllegalStateException("Latch cannot be null"); latch.await(timeout,unit); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
public void awaitReadLatch(long timeout, TimeUnit unit) throws InterruptedException { awaitLatch(readLatch,timeout,unit);}
// in java/org/apache/tomcat/util/net/NioEndpoint.java
public void awaitWriteLatch(long timeout, TimeUnit unit) throws InterruptedException { awaitLatch(writeLatch,timeout,unit);}
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
protected void countUpOrAwaitConnection() throws InterruptedException { if (maxConnections==-1) return; LimitLatch latch = connectionLimitLatch; if (latch!=null) latch.countUpOrAwait(); }
// in java/org/apache/tomcat/util/threads/LimitLatch.java
public void countUpOrAwait() throws InterruptedException { if (log.isDebugEnabled()) { log.debug("Counting up["+Thread.currentThread().getName()+"] latch="+getCount()); } sync.acquireSharedInterruptibly(1); }
// in java/org/apache/tomcat/util/threads/TaskQueue.java
public boolean force(Runnable o, long timeout, TimeUnit unit) throws InterruptedException { if ( parent.isShutdown() ) throw new RejectedExecutionException("Executor not running, can't force a command into the queue"); return super.offer(o,timeout,unit); //forces the item onto the queue, to be used if the task is rejected }
// in java/org/apache/tomcat/util/threads/TaskQueue.java
Override public Runnable poll(long timeout, TimeUnit unit) throws InterruptedException { Runnable runnable = super.poll(timeout, unit); if (runnable == null && parent != null) { // the poll timed out, it gives an opportunity to stop the current // thread if needed to avoid memory leaks. parent.stopCurrentThreadIfNeeded(); } return runnable; }
// in java/org/apache/tomcat/util/threads/TaskQueue.java
Override public Runnable take() throws InterruptedException { if (parent != null && parent.currentThreadShouldBeStopped()) { return poll(parent.getKeepAliveTime(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); // yes, this may return null (in case of timeout) which normally // does not occur with take() // but the ThreadPoolExecutor implementation allows this } return super.take(); }
54
            
// in java/org/apache/juli/AsyncFileHandler.java
catch (InterruptedException x) { //allow thread to be interrupted and back out of the publish operation //after this we clear the flag Thread.interrupted(); }
// in java/org/apache/juli/AsyncFileHandler.java
catch (InterruptedException x) { Thread.interrupted(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (InterruptedException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (InterruptedException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (InterruptedException e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (InterruptedException e) { }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (InterruptedException e) { return 0; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (InterruptedException e) { return 0; }
// in java/org/apache/tomcat/spdy/SpdyStream.java
catch (InterruptedException e) { return null; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (InterruptedException ignore) { Thread.interrupted(); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (InterruptedException ignore) { Thread.interrupted(); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (InterruptedException ignore) { }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore and clean the interrupt flag Thread.interrupted(); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/AbstractEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (InterruptedException e) { // yes, ignore }
// in java/org/apache/catalina/startup/HostConfig.java
catch (InterruptedException e1) { // Ignore }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( InterruptedException x ) { interrupted(); }
// in java/org/apache/catalina/tribes/group/RpcChannel.java
catch ( InterruptedException ix ) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/group/interceptors/TcpPingInterceptor.java
catch ( InterruptedException ix ) { interrupted(); }
// in java/org/apache/catalina/tribes/group/interceptors/NonBlockingCoordinator.java
catch ( InterruptedException x ) { Thread.interrupted(); }
// in java/org/apache/catalina/tribes/group/interceptors/SimpleCoordinator.java
catch (final InterruptedException e) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/bio/util/SingleRemoveSynchronizedAddLock.java
catch ( InterruptedException e ) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/bio/util/SingleRemoveSynchronizedAddLock.java
catch ( InterruptedException e ) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch (InterruptedException ti) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/transport/PooledSender.java
catch (InterruptedException x){}
// in java/org/apache/catalina/tribes/transport/RxTaskPool.java
catch (java.lang.InterruptedException x) { Thread.currentThread().interrupt(); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (InterruptedException ignore){}
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (InterruptedException ignore) { }
// in java/org/apache/catalina/valves/SemaphoreValve.java
catch (InterruptedException e) { shouldRelease = false; permitDenied(request, response); return; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (IllegalThreadStateException e) { try { Thread.sleep(500); } catch (InterruptedException ignored) { // Ignore } }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (InterruptedException ignored) { // Ignore }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (InterruptedException e) { log ("Interupted waiting for stderr reader thread"); }
// in java/org/apache/catalina/ssi/SSIExec.java
catch (InterruptedException e) { ssiMediator.log("Couldn't exec file: " + substitutedValue, e); writer.write(configErrMsg); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (InterruptedException e) { // Should never happen }
// in java/org/apache/catalina/core/ContainerBase.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/catalina/core/ContainerBase.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/catalina/core/StandardServer.java
catch (InterruptedException e) { // Ignored }
// in java/org/apache/catalina/core/StandardServer.java
catch( InterruptedException ex ) { // continue and check the flag }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (InterruptedException e) { // Ignore }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (InterruptedException e) { // Ignore }
1
            
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); }
// in java/org/apache/catalina/tribes/transport/ReceiverBase.java
catch ( IOException x) { retries--; if ( retries <= 0 ) { log.info("Unable to bind UDP socket to:"+addr+" throwing error."); throw x; } portstart++; try { Thread.sleep(25); } catch (InterruptedException ti) { Thread.currentThread().interrupt(); } retries = bindUdp(socket,portstart,retries); }
0
unknown (Lib) InterruptedIOException 0 0 0 9
            
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (InterruptedIOException e) { error = true; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (InterruptedIOException e) { error = true; }
0 0
unknown (Lib) IntrospectionException 0 0 0 4
            
// in java/org/apache/jasper/compiler/Generator.java
catch (IntrospectionException ie) { err.jspError(n, "jsp.error.introspect.taghandler", tagHandlerClass.getName(), ie); }
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.beans.IntrospectionException ie) { NamingException ne = new NamingException(ie.getMessage()); ne.setRootCause(ie); throw ne; }
// in java/javax/el/BeanELResolver.java
catch (IntrospectionException e) { // }
// in java/javax/el/BeanELResolver.java
catch (IntrospectionException ie) { throw new ELException(ie); }
2
            
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.beans.IntrospectionException ie) { NamingException ne = new NamingException(ie.getMessage()); ne.setRootCause(ie); throw ne; }
// in java/javax/el/BeanELResolver.java
catch (IntrospectionException ie) { throw new ELException(ie); }
1
unknown (Lib) InvalidAttributeValueException 0 0 0 1
            
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvalidAttributeValueException e) { throw new MBeanException(e); }
1
            
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvalidAttributeValueException e) { throw new MBeanException(e); }
0
checked (Domain) InvalidContentTypeException
public static class InvalidContentTypeException
            extends FileUploadException {
        /** The exceptions UID, for serializing an instance.
         */
        private static final long serialVersionUID = -9073026332015646668L;

        /**
         * Constructs a <code>InvalidContentTypeException</code> with no
         * detail message.
         */
        public InvalidContentTypeException() {
            // Nothing to do.
        }

        /**
         * Constructs an <code>InvalidContentTypeException</code> with
         * the specified detail message.
         *
         * @param message The detail message.
         */
        public InvalidContentTypeException(String message) {
            super(message);
        }
    }
1 0 0 1
            
// in java/org/apache/catalina/connector/Request.java
catch (InvalidContentTypeException e) { partsParseException = new ServletException(e); }
0 0
runtime (Domain) InvalidFileNameException
public class InvalidFileNameException extends RuntimeException {
    private static final long serialVersionUID = 7922042602454350470L;
    private final String name;

    /**
     * Creates a new instance.
     * @param pName The file name causing the exception.
     * @param pMessage A human readable error message.
     */
    public InvalidFileNameException(String pName, String pMessage) {
        super(pMessage);
        name = pName;
    }

    /**
     * Returns the invalid file name.
     */
    public String getName() {
        return name;
    }
}
1
            
// in java/org/apache/tomcat/util/http/fileupload/util/Streams.java
public static String checkFileName(String pFileName) { if (pFileName != null && pFileName.indexOf('\u0000') != -1) { // pFileName.replace("\u0000", "\\0") final StringBuffer sb = new StringBuffer(); for (int i = 0; i < pFileName.length(); i++) { char c = pFileName.charAt(i); switch (c) { case 0: sb.append("\\0"); break; default: sb.append(c); break; } } throw new InvalidFileNameException(pFileName, "Invalid file name: " + sb); } return pFileName; }
0 0 0 0 0
unknown (Lib) InvalidNameException 2
            
// in java/org/apache/catalina/realm/JNDIRealm.java
protected String getDistinguishedName(DirContext context, String base, SearchResult result) throws NamingException { // Get the entry's distinguished name. For relative results, this means // we need to composite a name with the base name, the context name, and // the result name. For non-relative names, use the returned name. if (result.isRelative()) { if (containerLog.isTraceEnabled()) { containerLog.trace(" search returned relative name: " + result.getName()); } NameParser parser = context.getNameParser(""); Name contextName = parser.parse(context.getNameInNamespace()); Name baseName = parser.parse(base); // Bugzilla 32269 Name entryName = parser.parse(new CompositeName(result.getName()).get(0)); Name name = contextName.addAll(baseName); name = name.addAll(entryName); return name.toString(); } else { String absoluteName = result.getName(); if (containerLog.isTraceEnabled()) containerLog.trace(" search returned absolute name: " + result.getName()); try { // Normalize the name by running it through the name parser. NameParser parser = context.getNameParser(""); URI userNameUri = new URI(absoluteName); String pathComponent = userNameUri.getPath(); // Should not ever have an empty path component, since that is /{DN} if (pathComponent.length() < 1 ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); } Name name = parser.parse(pathComponent.substring(1)); return name.toString(); } catch ( URISyntaxException e ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); } } }
1
            
// in java/org/apache/catalina/realm/JNDIRealm.java
catch ( URISyntaxException e ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); }
1
            
// in java/org/apache/naming/resources/WARDirContext.java
private Name getEscapedJndiName(String name) throws InvalidNameException { return new CompositeName(name.replace("'", "\\'").replace("\"", "")); }
2
            
// in java/org/apache/naming/resources/WARDirContext.java
catch (InvalidNameException e) { log.info(sm.getString("resources.invalidName", strName), e); return null; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (InvalidNameException ine) { // Log the problem for posterity containerLog.warn(sm.getString("jndiRealm.exception"), ine); // ignore; this is probably due to a name not fitting // the search path format exactly, as in a fully- // qualified name being munged into a search path // that already contains cn= or vice-versa }
0 0
unknown (Lib) InvalidTargetObjectTypeException 0 0 1
            
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
public Object getManagedResource() throws InstanceNotFoundException, InvalidTargetObjectTypeException, MBeanException, RuntimeOperationsException { if (resource == null) throw new RuntimeOperationsException (new IllegalArgumentException("Managed resource is null"), "Managed resource is null"); return resource; }
28
            
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
28
            
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
0
unknown (Lib) InvocationTargetException 0 0 17
            
// in java/org/apache/catalina/core/AprLifecycleListener.java
private static void terminateAPR() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { String methodName = "terminate"; Method method = Class.forName("org.apache.tomcat.jni.Library") .getMethod(methodName, (Class [])null); method.invoke(null, (Object []) null); aprAvailable = false; aprInitialized = false; sslInitialized = false; // Well we cleaned the pool in terminate. sslAvailable = false; // Well we cleaned the pool in terminate. fipsModeActive = false; }
// in java/org/apache/catalina/core/AprLifecycleListener.java
private static void initializeSSL() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { if ("off".equalsIgnoreCase(SSLEngine)) { return; } if (sslInitialized) { //only once per VM return; } sslInitialized = true; String methodName = "randSet"; Class<?> paramTypes[] = new Class[1]; paramTypes[0] = String.class; Object paramValues[] = new Object[1]; paramValues[0] = SSLRandomSeed; Class<?> clazz = Class.forName("org.apache.tomcat.jni.SSL"); Method method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); methodName = "initialize"; paramValues[0] = "on".equalsIgnoreCase(SSLEngine)?null:SSLEngine; method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); if("on".equalsIgnoreCase(FIPSMode)) { log.info(sm.getString("aprListener.initializingFIPS")); int result = SSL.fipsModeSet(1); // success is defined as return value = 1 if(1 == result) { fipsModeActive = true; log.info(sm.getString("aprListener.initializeFIPSSuccess")); } else { // This case should be handled by the native method, // but we'll make absolutely sure, here. String message = sm.getString("aprListener.initializeFIPSFailed"); log.error(message); throw new IllegalStateException(message); } } log.info(sm.getString("aprListener.initializedOpenSSL", SSL.versionString())); sslAvailable = true; }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
Filter getFilter() throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { // Return the existing filter instance, if any if (this.filter != null) return (this.filter); // Identify the class loader we will be using String filterClass = filterDef.getFilterClass(); this.filter = (Filter) getInstanceManager().newInstance(filterClass); initFilter(); return (this.filter); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
void setFilterDef(FilterDef filterDef) throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { this.filterDef = filterDef; if (filterDef == null) { // Release any previously allocated filter instance if (this.filter != null){ if (Globals.IS_SECURITY_ENABLED) { try{ SecurityUtil.doAsPrivilege("destroy", filter); } catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); } SecurityUtil.remove(filter); } else { filter.destroy(); } if (!context.getIgnoreAnnotations()) { try { ((StandardContext) context).getInstanceManager().destroyInstance(this.filter); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); } } } this.filter = null; } else { // Allocate a new filter instance if necessary if (filterDef.getFilter() == null) { getFilter(); } } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { Class<?> clazz = loadClassMaybePrivileged(className, classLoader); return newInstance(clazz.newInstance(), clazz); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(final String className, final ClassLoader classLoader) throws IllegalAccessException, NamingException, InvocationTargetException, InstantiationException, ClassNotFoundException { Class<?> clazz = classLoader.loadClass(className); return newInstance(clazz.newInstance(), clazz); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public void newInstance(Object o) throws IllegalAccessException, InvocationTargetException, NamingException { newInstance(o, o.getClass()); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
private Object newInstance(Object instance, Class<?> clazz) throws IllegalAccessException, InvocationTargetException, NamingException { if (!ignoreAnnotations) { Map<String, String> injections = injectionMap.get(clazz.getName()); populateAnnotationsCache(clazz, injections); processAnnotations(instance, injections); postConstruct(instance, clazz); } return instance; }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public void destroyInstance(Object instance) throws IllegalAccessException, InvocationTargetException { if (!ignoreAnnotations) { preDestroy(instance, instance.getClass()); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected void postConstruct(Object instance, final Class<?> clazz) throws IllegalAccessException, InvocationTargetException { if (context == null) { // No resource injection return; } Class<?> superClass = clazz.getSuperclass(); if (superClass != Object.class) { postConstruct(instance, superClass); } // At the end the postconstruct annotated // method is invoked AnnotationCacheEntry[] annotations; synchronized (annotationCache) { annotations = annotationCache.get(clazz); } for (AnnotationCacheEntry entry : annotations) { if (entry.getType() == AnnotationCacheEntryType.POST_CONSTRUCT) { Method postConstruct = getMethod(clazz, entry); synchronized (postConstruct) { boolean accessibility = postConstruct.isAccessible(); postConstruct.setAccessible(true); postConstruct.invoke(instance); postConstruct.setAccessible(accessibility); } } } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected void preDestroy(Object instance, final Class<?> clazz) throws IllegalAccessException, InvocationTargetException { Class<?> superClass = clazz.getSuperclass(); if (superClass != Object.class) { preDestroy(instance, superClass); } // At the end the postconstruct annotated // method is invoked AnnotationCacheEntry[] annotations = null; synchronized (annotationCache) { annotations = annotationCache.get(clazz); } if (annotations == null) { // instance not created through the instance manager return; } for (AnnotationCacheEntry entry : annotations) { if (entry.getType() == AnnotationCacheEntryType.PRE_DESTROY) { Method preDestroy = getMethod(clazz, entry); synchronized (preDestroy) { boolean accessibility = preDestroy.isAccessible(); preDestroy.setAccessible(true); preDestroy.invoke(instance); preDestroy.setAccessible(accessibility); } } } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected void populateAnnotationsCache(Class<?> clazz, Map<String, String> injections) throws IllegalAccessException, InvocationTargetException, NamingException { List<AnnotationCacheEntry> annotations = null; while (clazz != null) { AnnotationCacheEntry[] annotationsArray = null; synchronized (annotationCache) { annotationsArray = annotationCache.get(clazz); } if (annotationsArray == null) { if (annotations == null) { annotations = new ArrayList<AnnotationCacheEntry>(); } else { annotations.clear(); } if (context != null) { // Initialize fields annotations for resource injection if // JNDI is enabled Field[] fields = null; if (Globals.IS_SECURITY_ENABLED) { final Class<?> clazz2 = clazz; fields = AccessController.doPrivileged( new PrivilegedAction<Field[]>(){ @Override public Field[] run(){ return clazz2.getDeclaredFields(); } }); } else { fields = clazz.getDeclaredFields(); } for (Field field : fields) { if (injections != null && injections.containsKey(field.getName())) { annotations.add(new AnnotationCacheEntry( field.getName(), null, injections.get(field.getName()), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(Resource.class)) { Resource annotation = field.getAnnotation(Resource.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(EJB.class)) { EJB annotation = field.getAnnotation(EJB.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(WebServiceRef.class)) { WebServiceRef annotation = field.getAnnotation(WebServiceRef.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(PersistenceContext.class)) { PersistenceContext annotation = field.getAnnotation(PersistenceContext.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(PersistenceUnit.class)) { PersistenceUnit annotation = field.getAnnotation(PersistenceUnit.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } } } // Initialize methods annotations Method[] methods = null; if (Globals.IS_SECURITY_ENABLED) { final Class<?> clazz2 = clazz; methods = AccessController.doPrivileged( new PrivilegedAction<Method[]>(){ @Override public Method[] run(){ return clazz2.getDeclaredMethods(); } }); } else { methods = clazz.getDeclaredMethods(); } Method postConstruct = null; Method preDestroy = null; for (Method method : methods) { String methodName = method.getName(); if (context != null) { // Resource injection only if JNDI is enabled if (injections != null && methodName.startsWith("set") && methodName.length() > 3) { String fieldName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); if (injections.containsKey(fieldName)) { annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), injections.get(method.getName()), AnnotationCacheEntryType.SETTER)); break; } } if (method.isAnnotationPresent(Resource.class)) { Resource annotation = method.getAnnotation(Resource.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(EJB.class)) { EJB annotation = method.getAnnotation(EJB.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(WebServiceRef.class)) { WebServiceRef annotation = method.getAnnotation(WebServiceRef.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(PersistenceContext.class)) { PersistenceContext annotation = method.getAnnotation(PersistenceContext.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(PersistenceUnit.class)) { PersistenceUnit annotation = method.getAnnotation(PersistenceUnit.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } } if (method.isAnnotationPresent(PostConstruct.class)) { if ((postConstruct != null) || (method.getParameterTypes().length != 0) || (Modifier.isStatic(method.getModifiers())) || (method.getExceptionTypes().length > 0) || (!method.getReturnType().getName().equals("void"))) { throw new IllegalArgumentException( "Invalid PostConstruct annotation"); } postConstruct = method; } if (method.isAnnotationPresent(PreDestroy.class)) { if ((preDestroy != null || method.getParameterTypes().length != 0) || (Modifier.isStatic(method.getModifiers())) || (method.getExceptionTypes().length > 0) || (!method.getReturnType().getName().equals("void"))) { throw new IllegalArgumentException( "Invalid PreDestroy annotation"); } preDestroy = method; } } if (postConstruct != null) { annotations.add(new AnnotationCacheEntry( postConstruct.getName(), postConstruct.getParameterTypes(), null, AnnotationCacheEntryType.POST_CONSTRUCT)); } if (preDestroy != null) { annotations.add(new AnnotationCacheEntry( preDestroy.getName(), preDestroy.getParameterTypes(), null, AnnotationCacheEntryType.PRE_DESTROY)); } if (annotations.isEmpty()) { // Use common object to save memory annotationsArray = ANNOTATIONS_EMPTY; } else { annotationsArray = annotations.toArray( new AnnotationCacheEntry[annotations.size()]); } synchronized (annotationCache) { annotationCache.put(clazz, annotationsArray); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected void processAnnotations(Object instance, Map<String, String> injections) throws IllegalAccessException, InvocationTargetException, NamingException { if (context == null) { // No resource injection return; } Class<?> clazz = instance.getClass(); while (clazz != null) { AnnotationCacheEntry[] annotations; synchronized (annotationCache) { annotations = annotationCache.get(clazz); } for (AnnotationCacheEntry entry : annotations) { if (entry.getType() == AnnotationCacheEntryType.SETTER) { lookupMethodResource(context, instance, getMethod(clazz, entry), entry.getName(), clazz); } else if (entry.getType() == AnnotationCacheEntryType.FIELD) { lookupFieldResource(context, instance, getField(clazz, entry), entry.getName(), clazz); } } clazz = clazz.getSuperclass(); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected static void lookupMethodResource(Context context, Object instance, Method method, String name, Class<?> clazz) throws NamingException, IllegalAccessException, InvocationTargetException { if (!method.getName().startsWith("set") || method.getName().length() < 4 || method.getParameterTypes().length != 1 || !method.getReturnType().getName().equals("void")) { throw new IllegalArgumentException("Invalid method resource injection annotation"); } Object lookedupResource; boolean accessibility; String normalizedName = normalize(name); if ((normalizedName != null) && (normalizedName.length() > 0)) { lookedupResource = context.lookup(normalizedName); } else { lookedupResource = context.lookup( clazz.getName() + "/" + getName(method)); } synchronized (method) { accessibility = method.isAccessible(); method.setAccessible(true); method.invoke(instance, lookedupResource); method.setAccessible(accessibility); } }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
private Object executeMethod(final Method method, final ApplicationContext context, final Object[] params) throws PrivilegedActionException, IllegalAccessException, InvocationTargetException { if (SecurityUtil.isPackageProtectionEnabled()){ return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>(){ @Override public Object run() throws IllegalAccessException, InvocationTargetException{ return method.invoke(context, params); } }); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
Override public Object run() throws IllegalAccessException, InvocationTargetException{ return method.invoke(context, params); }
24
            
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.reflect.InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } NamingException ne = new NamingException(ite.getMessage()); ne.setRootCause(ite); throw ne; }
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
catch (InvocationTargetException ite) { throw ite.getTargetException(); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); if (log.isDebugEnabled()) log.debug("IntrospectionUtils: InvocationTargetException for " + o.getClass() + " " + name + "=" + value + ")", ie); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); if (log.isDebugEnabled()) log.debug("IntrospectionUtils: InvocationTargetException for " + o.getClass() + " " + name + ")"); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; }
// in java/org/apache/el/parser/AstFunction.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(MessageFactory.get("error.function", this .getOutputName()), cause); }
// in java/org/apache/el/parser/AstValue.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (InvocationTargetException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (InvocationTargetException e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), t); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); ServletException se = new ServletException(e); throw se; }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/javax/el/ExpressionFactory.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
38
            
// in java/org/apache/naming/factory/BeanFactory.java
catch (java.lang.reflect.InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } NamingException ne = new NamingException(ite.getMessage()); ne.setRootCause(ite); throw ne; }
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
catch (InvocationTargetException ite) { throw ite.getTargetException(); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; }
// in java/org/apache/el/parser/AstFunction.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(MessageFactory.get("error.function", this .getOutputName()), cause); }
// in java/org/apache/el/parser/AstValue.java
catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); ServletException se = new ServletException(e); throw se; }
// in java/javax/el/ExpressionFactory.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException( "Unable to create ExpressionFactory of type: " + clazz.getName(), e); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); }
// in java/javax/el/BeanELResolver.java
catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(cause); }
7
checked (Domain) ItemSkippedException
public static class ItemSkippedException extends IOException {
        /**
         * The exceptions serial version UID, which is being used
         * when serializing an exception instance.
         */
        private static final long serialVersionUID = -7280778431581963740L;
    }
4
            
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public int read() throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (available() == 0) { if (makeAvailable() == 0) { return -1; } } ++total; int b = buffer[head++]; if (b >= 0) { return b; } return b + BYTE_POSITIVE_OFFSET; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public int read(byte[] b, int off, int len) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (len == 0) { return 0; } int res = available(); if (res == 0) { res = makeAvailable(); if (res == 0) { return -1; } } res = Math.min(res, len); System.arraycopy(buffer, head, b, off, res); head += res; total += res; return res; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
Override public long skip(long bytes) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } int av = available(); if (av == 0) { av = makeAvailable(); if (av == 0) { return 0; } } long res = Math.min(av, bytes); head += res; return res; }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public InputStream openStream() throws IOException { if (opened) { throw new IllegalStateException( "The stream was already opened."); } if (((Closeable) stream).isClosed()) { throw new FileItemStream.ItemSkippedException(); } return stream; }
0 0 0 0 0
unknown (Lib) JMRuntimeException 0 0 0 1
            
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (JMRuntimeException rme) { Throwable cause = rme.getCause(); if (cause instanceof UnsupportedOperationException) { if (log.isDebugEnabled()) { log.debug("Error getting attribute " + oname + " " + attName, rme); } } else if (cause instanceof NullPointerException) { if (log.isDebugEnabled()) { log.debug("Error getting attribute " + oname + " " + attName, rme); } } else { log.error("Error getting attribute " + oname + " " + attName, rme); } continue; }
0 0
checked (Domain) JasperException
public class JasperException extends javax.servlet.ServletException {

    private static final long serialVersionUID = 1L;

    public JasperException(String reason) {
        super(reason);
    }

    /**
     * Creates a JasperException with the embedded exception and the reason for
     * throwing a JasperException
     */
    public JasperException (String reason, Throwable exception) {
        super(reason, exception);
    }

    /**
     * Creates a JasperException with the embedded exception
     */
    public JasperException (Throwable exception) {
        super(exception);
    }
}
59
            
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object convert(String propertyName, String s, Class<?> t, Class<?> propertyEditorClass) throws JasperException { try { if (s == null) { if (t.equals(Boolean.class) || t.equals(Boolean.TYPE)) s = "false"; else return null; } if (propertyEditorClass != null) { return getValueFromBeanInfoPropertyEditor( t, propertyName, s, propertyEditorClass); } else if ( t.equals(Boolean.class) || t.equals(Boolean.TYPE) ) { if (s.equalsIgnoreCase("on") || s.equalsIgnoreCase("true")) s = "true"; else s = "false"; return Boolean.valueOf(s); } else if ( t.equals(Byte.class) || t.equals(Byte.TYPE) ) { return Byte.valueOf(s); } else if (t.equals(Character.class) || t.equals(Character.TYPE)) { return s.length() > 0 ? Character.valueOf(s.charAt(0)) : null; } else if ( t.equals(Short.class) || t.equals(Short.TYPE) ) { return Short.valueOf(s); } else if ( t.equals(Integer.class) || t.equals(Integer.TYPE) ) { return Integer.valueOf(s); } else if ( t.equals(Float.class) || t.equals(Float.TYPE) ) { return Float.valueOf(s); } else if ( t.equals(Long.class) || t.equals(Long.TYPE) ) { return Long.valueOf(s); } else if ( t.equals(Double.class) || t.equals(Double.TYPE) ) { return Double.valueOf(s); } else if ( t.equals(String.class) ) { return s; } else if ( t.equals(java.io.File.class) ) { return new java.io.File(s); } else if (t.getName().equals("java.lang.Object")) { return new Object[] {s}; } else { return getValueFromPropertyEditorManager( t, propertyName, s); } } catch (Exception ex) { throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
private static void internalIntrospecthelper(Object bean, String prop, String value, ServletRequest request, String param, boolean ignoreMethodNF) throws JasperException { Method method = null; Class<?> type = null; Class<?> propertyEditorClass = null; try { java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(bean.getClass()); if ( info != null ) { java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); for (int i = 0 ; i < pd.length ; i++) { if ( pd[i].getName().equals(prop) ) { method = pd[i].getWriteMethod(); type = pd[i].getPropertyType(); propertyEditorClass = pd[i].getPropertyEditorClass(); break; } } } if ( method != null ) { if (type.isArray()) { if (request == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.setproperty.noindexset")); } Class<?> t = type.getComponentType(); String[] values = request.getParameterValues(param); //XXX Please check. if(values == null) return; if(t.equals(String.class)) { method.invoke(bean, new Object[] { values }); } else { createTypedArray (prop, bean, method, values, t, propertyEditorClass); } } else { if(value == null || (param != null && value.equals(""))) return; Object oval = convert(prop, value, type, propertyEditorClass); if ( oval != null ) method.invoke(bean, new Object[] { oval }); } } } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } if (!ignoreMethodNF && (method == null)) { if (type == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.noproperty", prop, bean.getClass().getName())); } else { throw new JasperException( Localizer.getMessage("jsp.error.beans.nomethod.setproperty", prop, type.getName(), bean.getClass().getName())); } } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void createTypedArray(String propertyName, Object bean, Method method, String[] values, Class<?> t, Class<?> propertyEditorClass) throws JasperException { try { if (propertyEditorClass != null) { Object[] tmpval = new Integer[values.length]; for (int i=0; i<values.length; i++) { tmpval[i] = getValueFromBeanInfoPropertyEditor( t, propertyName, values[i], propertyEditorClass); } method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Integer.class)) { Integer []tmpval = new Integer[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Integer (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Byte.class)) { Byte[] tmpval = new Byte[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Byte (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Boolean.class)) { Boolean[] tmpval = new Boolean[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Boolean.valueOf(values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Short.class)) { Short[] tmpval = new Short[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Short (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Long.class)) { Long[] tmpval = new Long[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Long (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Double.class)) { Double[] tmpval = new Double[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Double (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Float.class)) { Float[] tmpval = new Float[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Float (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Character.class)) { Character[] tmpval = new Character[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Character.valueOf(values[i].charAt(0)); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(int.class)) { int []tmpval = new int[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Integer.parseInt (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(byte.class)) { byte[] tmpval = new byte[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Byte.parseByte (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(boolean.class)) { boolean[] tmpval = new boolean[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = (Boolean.valueOf(values[i])).booleanValue(); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(short.class)) { short[] tmpval = new short[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Short.parseShort (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(long.class)) { long[] tmpval = new long[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Long.parseLong (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(double.class)) { double[] tmpval = new double[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Double.valueOf(values[i]).doubleValue(); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(float.class)) { float[] tmpval = new float[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Float.valueOf(values[i]).floatValue(); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(char.class)) { char[] tmpval = new char[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = values[i].charAt(0); method.invoke (bean, new Object[] {tmpval}); } else { Object[] tmpval = new Integer[values.length]; for (int i=0; i<values.length; i++) { tmpval[i] = getValueFromPropertyEditorManager( t, propertyName, values[i]); } method.invoke (bean, new Object[] {tmpval}); } } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException ("error in invoking method", ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object handleGetProperty(Object o, String prop) throws JasperException { if (o == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.nullbean")); } Object value = null; try { Method method = getReadMethod(o.getClass(), prop); value = method.invoke(o, (Object[]) null); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException (ex); } return value; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetPropertyExpression(Object bean, String prop, String expression, PageContext pageContext, ProtectedFunctionMapper functionMapper ) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { PageContextImpl.proprietaryEvaluate( expression, method.getParameterTypes()[0], pageContext, functionMapper, false ) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, Object value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { value }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, int value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Integer.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, short value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Short.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, long value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Long.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, double value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Double.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, float value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Float.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, char value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Character.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, byte value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Byte.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, boolean value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Boolean.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Method getWriteMethod(Class<?> beanClass, String prop) throws JasperException { Method method = null; Class<?> type = null; try { java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(beanClass); if ( info != null ) { java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); for (int i = 0 ; i < pd.length ; i++) { if ( pd[i].getName().equals(prop) ) { method = pd[i].getWriteMethod(); type = pd[i].getPropertyType(); break; } } } else { // just in case introspection silently fails. throw new JasperException( Localizer.getMessage("jsp.error.beans.nobeaninfo", beanClass.getName())); } } catch (Exception ex) { throw new JasperException (ex); } if (method == null) { if (type == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.noproperty", prop, beanClass.getName())); } else { throw new JasperException( Localizer.getMessage("jsp.error.beans.nomethod.setproperty", prop, type.getName(), beanClass.getName())); } } return method; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Method getReadMethod(Class<?> beanClass, String prop) throws JasperException { Method method = null; Class<?> type = null; try { java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(beanClass); if ( info != null ) { java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); for (int i = 0 ; i < pd.length ; i++) { if ( pd[i].getName().equals(prop) ) { method = pd[i].getReadMethod(); type = pd[i].getPropertyType(); break; } } } else { // just in case introspection silently fails. throw new JasperException( Localizer.getMessage("jsp.error.beans.nobeaninfo", beanClass.getName())); } } catch (Exception ex) { throw new JasperException (ex); } if (method == null) { if (type == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.noproperty", prop, beanClass.getName())); } else { throw new JasperException( Localizer.getMessage("jsp.error.beans.nomethod", prop, beanClass.getName())); } } return method; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object getValueFromBeanInfoPropertyEditor( Class<?> attrClass, String attrName, String attrValue, Class<?> propertyEditorClass) throws JasperException { try { PropertyEditor pe = (PropertyEditor)propertyEditorClass.newInstance(); pe.setAsText(attrValue); return pe.getValue(); } catch (Exception ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object getValueFromPropertyEditorManager( Class<?> attrClass, String attrName, String attrValue) throws JasperException { try { PropertyEditor propEditor = PropertyEditorManager.findEditor(attrClass); if (propEditor != null) { propEditor.setAsText(attrValue); return propEditor.getValue(); } else { throw new IllegalArgumentException( Localizer.getMessage("jsp.error.beans.propertyeditor.notregistered")); } } catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); } }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void jspError(String fname, int line, int column, String errMsg, Exception ex) throws JasperException { throw new JasperException(fname + " (" + Localizer.getMessage("jsp.error.location", Integer.toString(line), Integer.toString(column)) + ") " + errMsg, ex); }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void jspError(String errMsg, Exception ex) throws JasperException { throw new JasperException(errMsg, ex); }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void javacError(JavacErrorDetail[] details) throws JasperException { if (details == null) { return; } Object[] args = null; StringBuilder buf = new StringBuilder(); for (int i=0; i < details.length; i++) { if (details[i].getJspBeginLineNumber() >= 0) { args = new Object[] { Integer.valueOf(details[i].getJspBeginLineNumber()), details[i].getJspFileName() }; buf.append(Constants.NEWLINE); buf.append(Constants.NEWLINE); buf.append(Localizer.getMessage("jsp.error.single.line.number", args)); buf.append(Constants.NEWLINE); buf.append(details[i].getErrorMessage()); buf.append(Constants.NEWLINE); buf.append(details[i].getJspExtract()); } else { args = new Object[] { Integer.valueOf(details[i].getJavaLineNumber()) }; buf.append(Constants.NEWLINE); buf.append(Constants.NEWLINE); buf.append(Localizer.getMessage("jsp.error.java.line.number", args)); buf.append(Constants.NEWLINE); buf.append(details[i].getErrorMessage()); } } buf.append(Constants.NEWLINE); buf.append(Constants.NEWLINE); buf.append("Stacktrace:"); throw new JasperException( Localizer.getMessage("jsp.error.unable.compile") + ": " + buf); }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void javacError(String errorReport, Exception exception) throws JasperException { throw new JasperException( Localizer.getMessage("jsp.error.unable.compile"), exception); }
// in java/org/apache/jasper/compiler/ParserController.java
private void determineSyntaxAndEncoding(String absFileName, JarFile jarFile, String jspConfigPageEnc) throws JasperException, IOException { isXml = false; /* * 'true' if the syntax (XML or standard) of the file is given * from external information: either via a JSP configuration element, * the ".jspx" suffix, or the enclosing file (for included resources) */ boolean isExternal = false; /* * Indicates whether we need to revert from temporary usage of * "ISO-8859-1" back to "UTF-8" */ boolean revert = false; JspConfig jspConfig = ctxt.getOptions().getJspConfig(); JspConfig.JspProperty jspProperty = jspConfig.findJspProperty( absFileName); if (jspProperty.isXml() != null) { // If <is-xml> is specified in a <jsp-property-group>, it is used. isXml = JspUtil.booleanValue(jspProperty.isXml()); isExternal = true; } else if (absFileName.endsWith(".jspx") || absFileName.endsWith(".tagx")) { isXml = true; isExternal = true; } if (isExternal && !isXml) { // JSP (standard) syntax. Use encoding specified in jsp-config // if provided. sourceEnc = jspConfigPageEnc; if (sourceEnc != null) { return; } // We don't know the encoding, so use BOM to determine it sourceEnc = "ISO-8859-1"; } else { // XML syntax or unknown, (auto)detect encoding ... Object[] ret = XMLEncodingDetector.getEncoding(absFileName, jarFile, ctxt, err); sourceEnc = (String) ret[0]; if (((Boolean) ret[1]).booleanValue()) { isEncodingSpecifiedInProlog = true; } if (((Boolean) ret[2]).booleanValue()) { isBomPresent = true; } skip = ((Integer) ret[3]).intValue(); if (!isXml && sourceEnc.equals("UTF-8")) { /* * We don't know if we're dealing with XML or standard syntax. * Therefore, we need to check to see if the page contains * a <jsp:root> element. * * We need to be careful, because the page may be encoded in * ISO-8859-1 (or something entirely different), and may * contain byte sequences that will cause a UTF-8 converter to * throw exceptions. * * It is safe to use a source encoding of ISO-8859-1 in this * case, as there are no invalid byte sequences in ISO-8859-1, * and the byte/character sequences we're looking for (i.e., * <jsp:root>) are identical in either encoding (both UTF-8 * and ISO-8859-1 are extensions of ASCII). */ sourceEnc = "ISO-8859-1"; revert = true; } } if (isXml) { // (This implies 'isExternal' is TRUE.) // We know we're dealing with a JSP document (via JSP config or // ".jspx" suffix), so we're done. return; } /* * At this point, 'isExternal' or 'isXml' is FALSE. * Search for jsp:root action, in order to determine if we're dealing * with XML or standard syntax (unless we already know what we're * dealing with, i.e., when 'isExternal' is TRUE and 'isXml' is FALSE). * No check for XML prolog, since nothing prevents a page from * outputting XML and still using JSP syntax (in this case, the * XML prolog is treated as template text). */ JspReader jspReader = null; try { jspReader = new JspReader(ctxt, absFileName, sourceEnc, jarFile, err); } catch (FileNotFoundException ex) { throw new JasperException(ex); } jspReader.setSingleFile(true); Mark startMark = jspReader.mark(); if (!isExternal) { jspReader.reset(startMark); if (hasJspRoot(jspReader)) { if (revert) { sourceEnc = "UTF-8"; } isXml = true; return; } else { if (revert && isBomPresent) { sourceEnc = "UTF-8"; } isXml = false; } } /* * At this point, we know we're dealing with JSP syntax. * If an XML prolog is provided, it's treated as template text. * Determine the page encoding from the page directive, unless it's * specified via JSP config. */ if (!isBomPresent) { sourceEnc = jspConfigPageEnc; if (sourceEnc == null) { sourceEnc = getPageEncodingForJspSyntax(jspReader, startMark); if (sourceEnc == null) { // Default to "ISO-8859-1" per JSP spec sourceEnc = "ISO-8859-1"; isDefaultPageEncoding = true; } } } }
// in java/org/apache/jasper/compiler/BeanRepository.java
public Class<?> getBeanType(String bean) throws JasperException { Class<?> clazz = null; try { clazz = loader.loadClass(beanTypes.get(bean)); } catch (ClassNotFoundException ex) { throw new JasperException (ex); } return clazz; }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
Override public void visit(Node.CustomTag n) throws JasperException { TagFileInfo tagFileInfo = n.getTagFileInfo(); if (tagFileInfo != null) { String tagFilePath = tagFileInfo.getPath(); if (tagFilePath.startsWith("/META-INF/")) { // For tags in JARs, add the TLD and the tag as a dependency TldLocation location = compiler.getCompilationContext().getTldLocation( tagFileInfo.getTagInfo().getTagLibrary().getURI()); JarResource jarResource = location.getJarResource(); if (jarResource != null) { try { // Add TLD pageInfo.addDependant(jarResource.getEntry(location.getName()).toString(), Long.valueOf(jarResource.getJarFile().getEntry(location.getName()).getTime())); // Add Tag pageInfo.addDependant(jarResource.getEntry(tagFilePath.substring(1)).toString(), Long.valueOf(jarResource.getJarFile().getEntry(tagFilePath.substring(1)).getTime())); } catch (IOException ioe) { throw new JasperException(ioe); } } else { pageInfo.addDependant(tagFilePath, compiler.getCompilationContext().getLastModified( tagFilePath)); } } else { pageInfo.addDependant(tagFilePath, compiler.getCompilationContext().getLastModified( tagFilePath)); } Class<?> c = loadTagFile(compiler, tagFilePath, n.getTagInfo(), pageInfo); n.setTagHandlerClass(c); } visitBody(n); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private synchronized void init() throws JasperException { if (initialized) return; try { tldScanWebXml(); tldScanResourcePaths(WEB_INF); JarScanner jarScanner = JarScannerFactory.getJarScanner(ctxt); if (jarScanner != null) { jarScanner.scan(ctxt, Thread.currentThread().getContextClassLoader(), new TldJarScannerCallback(), noTldJars); } initialized = true; } catch (Exception ex) { throw new JasperException(Localizer.getMessage( "jsp.error.internal.tldinit", ex.getMessage()), ex); } }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
private String getCanonicalName(String className) throws JasperException { Class<?> clazz; ClassLoader tccl; if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<ClassLoader> pa = new PrivilegedGetTccl(); tccl = AccessController.doPrivileged(pa); } else { tccl = Thread.currentThread().getContextClassLoader(); } try { clazz = Class.forName(className, false, tccl); } catch (ClassNotFoundException e) { throw new JasperException(e); } return clazz.getCanonicalName(); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.GetProperty n) throws JasperException { String name = n.getTextAttribute("name"); String property = n.getTextAttribute("property"); n.setBeginJavaLine(out.getJavaLine()); if (beanInfo.checkVariable(name)) { // Bean is defined using useBean, introspect at compile time Class<?> bean = beanInfo.getBeanType(name); String beanName = bean.getCanonicalName(); java.lang.reflect.Method meth = JspRuntimeLibrary .getReadMethod(bean, property); String methodName = meth.getName(); out.printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString(" + "(((" + beanName + ")_jspx_page_context.findAttribute(" + "\"" + name + "\"))." + methodName + "())));"); } else if (!STRICT_GET_PROPERTY || varInfoNames.contains(name)) { // The object is a custom action with an associated // VariableInfo entry for this name. // Get the class name and then introspect at runtime. out.printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString" + "(org.apache.jasper.runtime.JspRuntimeLibrary.handleGetProperty" + "(_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\")));"); } else { StringBuilder msg = new StringBuilder(); msg.append("file:"); msg.append(n.getStart()); msg.append(" jsp:getProperty for bean with name '"); msg.append(name); msg.append( "'. Name was not previously introduced as per JSP.5.3"); throw new JasperException(msg.toString()); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
private static void generateLocalVariables(ServletWriter out, Node n) throws JasperException { Node.ChildInfo ci; if (n instanceof Node.CustomTag) { ci = ((Node.CustomTag) n).getChildInfo(); } else if (n instanceof Node.JspBody) { ci = ((Node.JspBody) n).getChildInfo(); } else if (n instanceof Node.NamedAttribute) { ci = ((Node.NamedAttribute) n).getChildInfo(); } else { // Cannot access err since this method is static, but at // least flag an error. throw new JasperException("Unexpected Node Type"); // err.getString( // "jsp.error.internal.unexpected_node_type" ) ); } if (ci.hasUseBean()) { out.printil("javax.servlet.http.HttpSession session = _jspx_page_context.getSession();"); out.printil("javax.servlet.ServletContext application = _jspx_page_context.getServletContext();"); } if (ci.hasUseBean() || ci.hasIncludeAction() || ci.hasSetProperty() || ci.hasParamAction()) { out.printil("javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest)_jspx_page_context.getRequest();"); } if (ci.hasIncludeAction()) { out.printil("javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse)_jspx_page_context.getResponse();"); } }
// in java/org/apache/jasper/compiler/TagPluginManager.java
private void init(ErrorDispatcher err) throws JasperException { if (initialized) return; InputStream is = ctxt.getResourceAsStream(TAG_PLUGINS_XML); if (is == null) return; TreeNode root = (new ParserUtils()).parseXMLDocument(TAG_PLUGINS_XML, is); if (root == null) { return; } if (!TAG_PLUGINS_ROOT_ELEM.equals(root.getName())) { err.jspError("jsp.error.plugin.wrongRootElement", TAG_PLUGINS_XML, TAG_PLUGINS_ROOT_ELEM); } tagPlugins = new HashMap<String, TagPlugin>(); Iterator<TreeNode> pluginList = root.findChildren("tag-plugin"); while (pluginList.hasNext()) { TreeNode pluginNode = pluginList.next(); TreeNode tagClassNode = pluginNode.findChild("tag-class"); if (tagClassNode == null) { // Error return; } String tagClass = tagClassNode.getBody().trim(); TreeNode pluginClassNode = pluginNode.findChild("plugin-class"); if (pluginClassNode == null) { // Error return; } String pluginClassStr = pluginClassNode.getBody(); TagPlugin tagPlugin = null; try { Class<?> pluginClass = Class.forName(pluginClassStr); tagPlugin = (TagPlugin) pluginClass.newInstance(); } catch (Exception e) { throw new JasperException(e); } if (tagPlugin == null) { return; } tagPlugins.put(tagClass, tagPlugin); } initialized = true; }
// in java/org/apache/jasper/compiler/JspConfig.java
private void processWebDotXml() throws JasperException { WebXml webXml = null; try { webXml = new WebXml(ctxt); TreeNode webApp = null; if (webXml.getInputSource() != null) { ParserUtils pu = new ParserUtils(); webApp = pu.parseXMLDocument(webXml.getSystemId(), webXml.getInputSource()); } if (webApp == null || getVersion(webApp) < 2.4) { defaultIsELIgnored = "true"; defaultDeferedSyntaxAllowedAsLiteral = "true"; return; } if (getVersion(webApp) < 2.5) { defaultDeferedSyntaxAllowedAsLiteral = "true"; } TreeNode jspConfig = webApp.findChild("jsp-config"); if (jspConfig == null) { return; } jspProperties = new Vector<JspPropertyGroup>(); Iterator<TreeNode> jspPropertyList = jspConfig.findChildren("jsp-property-group"); while (jspPropertyList.hasNext()) { TreeNode element = jspPropertyList.next(); Iterator<TreeNode> list = element.findChildren(); Vector<String> urlPatterns = new Vector<String>(); String pageEncoding = null; String scriptingInvalid = null; String elIgnored = null; String isXml = null; Vector<String> includePrelude = new Vector<String>(); Vector<String> includeCoda = new Vector<String>(); String deferredSyntaxAllowedAsLiteral = null; String trimDirectiveWhitespaces = null; String defaultContentType = null; String buffer = null; String errorOnUndeclaredNamespace = null; while (list.hasNext()) { element = list.next(); String tname = element.getName(); if ("url-pattern".equals(tname)) urlPatterns.addElement( element.getBody() ); else if ("page-encoding".equals(tname)) pageEncoding = element.getBody(); else if ("is-xml".equals(tname)) isXml = element.getBody(); else if ("el-ignored".equals(tname)) elIgnored = element.getBody(); else if ("scripting-invalid".equals(tname)) scriptingInvalid = element.getBody(); else if ("include-prelude".equals(tname)) includePrelude.addElement(element.getBody()); else if ("include-coda".equals(tname)) includeCoda.addElement(element.getBody()); else if ("deferred-syntax-allowed-as-literal".equals(tname)) deferredSyntaxAllowedAsLiteral = element.getBody(); else if ("trim-directive-whitespaces".equals(tname)) trimDirectiveWhitespaces = element.getBody(); else if ("default-content-type".equals(tname)) defaultContentType = element.getBody(); else if ("buffer".equals(tname)) buffer = element.getBody(); else if ("error-on-undeclared-namespace".equals(tname)) errorOnUndeclaredNamespace = element.getBody(); } if (urlPatterns.size() == 0) { continue; } // Add one JspPropertyGroup for each URL Pattern. This makes // the matching logic easier. for( int p = 0; p < urlPatterns.size(); p++ ) { String urlPattern = urlPatterns.elementAt( p ); String path = null; String extension = null; if (urlPattern.indexOf('*') < 0) { // Exact match path = urlPattern; } else { int i = urlPattern.lastIndexOf('/'); String file; if (i >= 0) { path = urlPattern.substring(0,i+1); file = urlPattern.substring(i+1); } else { file = urlPattern; } // pattern must be "*", or of the form "*.jsp" if (file.equals("*")) { extension = "*"; } else if (file.startsWith("*.")) { extension = file.substring(file.indexOf('.')+1); } // The url patterns are reconstructed as the following: // path != null, extension == null: / or /foo/bar.ext // path == null, extension != null: *.ext // path != null, extension == "*": /foo/* boolean isStar = "*".equals(extension); if ((path == null && (extension == null || isStar)) || (path != null && !isStar)) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage( "jsp.warning.bad.urlpattern.propertygroup", urlPattern)); } continue; } } JspProperty property = new JspProperty(isXml, elIgnored, scriptingInvalid, pageEncoding, includePrelude, includeCoda, deferredSyntaxAllowedAsLiteral, trimDirectiveWhitespaces, defaultContentType, buffer, errorOnUndeclaredNamespace); JspPropertyGroup propertyGroup = new JspPropertyGroup(path, extension, property); jspProperties.addElement(propertyGroup); } } } catch (Exception ex) { throw new JasperException(ex); } finally { if (webXml != null) { webXml.close(); } } }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public Servlet getServlet() throws ServletException { // DCL on 'reload' requires that 'reload' be volatile // (this also forces a read memory barrier, ensuring the // new servlet object is read consistently) if (reload) { synchronized (this) { // Synchronizing on jsw enables simultaneous loading // of different pages, but not the same page. if (reload) { // This is to maintain the original protocol. destroy(); final Servlet servlet; try { InstanceManager instanceManager = InstanceManagerFactory.getInstanceManager(config); servlet = (Servlet) instanceManager.newInstance(ctxt.getFQCN(), ctxt.getJspLoader()); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JasperException(t); } servlet.init(config); if (!firstTime) { ctxt.getRuntimeContext().incrementJspReloadCount(); } theServlet = servlet; reload = false; // Volatile 'reload' forces in order write of 'theServlet' and new servlet object } } } return theServlet; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public Class<?> loadTagFile() throws JasperException { try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; ctxt.compile(); } } else { if (compileException != null) { throw compileException; } } if (reload) { tagHandlerClass = ctxt.load(); reload = false; } } catch (FileNotFoundException ex) { throw new JasperException(ex); } return tagHandlerClass; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile) throws ServletException, IOException, FileNotFoundException { Servlet servlet; try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if ((available > 0L) && (available < Long.MAX_VALUE)) { if (available > System.currentTimeMillis()) { response.setDateHeader("Retry-After", available); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, Localizer.getMessage("jsp.error.unavailable")); return; } // Wait period has expired. Reset. available = 0; } /* * (1) Compile */ if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; // The following sets reload to true, if necessary ctxt.compile(); } } else { if (compileException != null) { // Throw cached compilation exception throw compileException; } } /* * (2) (Re)load servlet class file */ servlet = getServlet(); // If a page is to be precompiled only, return. if (precompile) { return; } } catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; } catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } try { /* * (3) Handle limitation of number of loaded Jsps */ if (unloadAllowed) { synchronized(this) { if (unloadByCount) { if (unloadHandle == null) { unloadHandle = ctxt.getRuntimeContext().push(this); } else if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { ctxt.getRuntimeContext().makeYoungest(unloadHandle); lastUsageTime = System.currentTimeMillis(); } } else { if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { lastUsageTime = System.currentTimeMillis(); } } } } /* * (4) Service request */ if (servlet instanceof SingleThreadModel) { // sync on the wrapper so that the freshness // of the page is determined right before servicing synchronized (this) { servlet.service(request, response); } } else { servlet.service(request, response); } } catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); } catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
protected JasperException handleJspException(Exception ex) { try { Throwable realException = ex; if (ex instanceof ServletException) { realException = ((ServletException) ex).getRootCause(); } // First identify the stack frame in the trace that represents the JSP StackTraceElement[] frames = realException.getStackTrace(); StackTraceElement jspFrame = null; for (int i=0; i<frames.length; ++i) { if ( frames[i].getClassName().equals(this.getServlet().getClass().getName()) ) { jspFrame = frames[i]; break; } } if (jspFrame == null || this.ctxt.getCompiler().getPageNodes() == null) { // If we couldn't find a frame in the stack trace corresponding // to the generated servlet class or we don't have a copy of the // parsed JSP to hand, we can't really add anything return new JasperException(ex); } int javaLineNumber = jspFrame.getLineNumber(); JavacErrorDetail detail = ErrorDispatcher.createJavacError( jspFrame.getMethodName(), this.ctxt.getCompiler().getPageNodes(), null, javaLineNumber, ctxt); // If the line number is less than one we couldn't find out // where in the JSP things went wrong int jspLineNumber = detail.getJspBeginLineNumber(); if (jspLineNumber < 1) { throw new JasperException(ex); } if (options.getDisplaySourceFragment()) { return new JasperException(Localizer.getMessage ("jsp.exception", detail.getJspFileName(), "" + jspLineNumber) + Constants.NEWLINE + Constants.NEWLINE + detail.getJspExtract() + Constants.NEWLINE + Constants.NEWLINE + "Stacktrace:", ex); } return new JasperException(Localizer.getMessage ("jsp.exception", detail.getJspFileName(), "" + jspLineNumber), ex); } catch (Exception je) { // If anything goes wrong, just revert to the original behaviour if (ex instanceof JasperException) { return (JasperException) ex; } return new JasperException(ex); } }
// in java/org/apache/jasper/JspCompilationContext.java
public Class<?> load() throws JasperException { try { getJspLoader(); String name = getFQCN(); servletClass = jspLoader.loadClass(name); } catch (ClassNotFoundException cex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.load"), cex); } catch (Exception ex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); } removed = 0; return servletClass; }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
public TreeNode parseXMLDocument(String location, InputSource is) throws JasperException { Document document = null; // Perform an XML parse of this document, via JAXP try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(validating); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(entityResolver); builder.setErrorHandler(errorHandler); document = builder.parse(is); } catch (ParserConfigurationException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), ex); } catch (SAXParseException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); } catch (SAXException sx) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), sx); } catch (IOException io) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), io); } // Convert the resulting document to a graph of TreeNodes return (convert(null, document.getDocumentElement())); }
// in java/org/apache/jasper/JspC.java
public void setArgs(String[] arg) throws JasperException { args = arg; String tok; dieLevel = NO_DIE_LEVEL; while ((tok = nextArg()) != null) { if (tok.equals(SWITCH_VERBOSE)) { verbose = true; showSuccess = true; listErrors = true; } else if (tok.equals(SWITCH_OUTPUT_DIR)) { tok = nextArg(); setOutputDir( tok ); } else if (tok.equals(SWITCH_PACKAGE_NAME)) { targetPackage = nextArg(); } else if (tok.equals(SWITCH_COMPILE)) { compile=true; } else if (tok.equals(SWITCH_CLASS_NAME)) { targetClassName = nextArg(); } else if (tok.equals(SWITCH_URI_BASE)) { uriBase=nextArg(); } else if (tok.equals(SWITCH_URI_ROOT)) { setUriroot( nextArg()); } else if (tok.equals(SWITCH_FILE_WEBAPP)) { setUriroot( nextArg()); } else if ( tok.equals( SHOW_SUCCESS ) ) { showSuccess = true; } else if ( tok.equals( LIST_ERRORS ) ) { listErrors = true; } else if (tok.equals(SWITCH_WEBAPP_INC)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = INC_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = ALL_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML_ENCODING)) { setWebXmlEncoding(nextArg()); } else if (tok.equals(SWITCH_ADD_WEBAPP_XML_MAPPINGS)) { setAddWebXmlMappings(true); } else if (tok.equals(SWITCH_MAPPED)) { mappedFile = true; } else if (tok.equals(SWITCH_XPOWERED_BY)) { xpoweredBy = true; } else if (tok.equals(SWITCH_TRIM_SPACES)) { setTrimSpaces(true); } else if (tok.equals(SWITCH_CACHE)) { tok = nextArg(); if ("false".equals(tok)) { caching = false; } else { caching = true; } } else if (tok.equals(SWITCH_CLASSPATH)) { setClassPath(nextArg()); } else if (tok.startsWith(SWITCH_DIE)) { try { dieLevel = Integer.parseInt( tok.substring(SWITCH_DIE.length())); } catch (NumberFormatException nfe) { dieLevel = DEFAULT_DIE_LEVEL; } } else if (tok.equals(SWITCH_HELP)) { helpNeeded = true; } else if (tok.equals(SWITCH_POOLING)) { tok = nextArg(); if ("false".equals(tok)) { poolingEnabled = false; } else { poolingEnabled = true; } } else if (tok.equals(SWITCH_ENCODING)) { setJavaEncoding(nextArg()); } else if (tok.equals(SWITCH_SOURCE)) { setCompilerSourceVM(nextArg()); } else if (tok.equals(SWITCH_TARGET)) { setCompilerTargetVM(nextArg()); } else if (tok.equals(SWITCH_SMAP)) { smapSuppressed = false; } else if (tok.equals(SWITCH_DUMP_SMAP)) { smapDumped = true; } else { if (tok.startsWith("-")) { throw new JasperException("Unrecognized option: " + tok + ". Use -help for help."); } if (!fullstop) { argPos--; } // Start treating the rest as JSP Pages break; } } // Add all extra arguments to the list of files while( true ) { String file = nextFile(); if( file==null ) { break; } pages.add( file ); } }
// in java/org/apache/jasper/JspC.java
protected void processFile(String file) throws JasperException { if (log.isDebugEnabled()) { log.debug("Processing file: " + file); } ClassLoader originalClassLoader = null; try { // set up a scratch/output dir if none is provided if (scratchDir == null) { String temp = System.getProperty("java.io.tmpdir"); if (temp == null) { temp = ""; } scratchDir = new File(new File(temp).getAbsolutePath()); } String jspUri=file.replace('\\','/'); JspCompilationContext clctxt = new JspCompilationContext ( jspUri, this, context, null, rctxt ); /* Override the defaults */ if ((targetClassName != null) && (targetClassName.length() > 0)) { clctxt.setServletClassName(targetClassName); targetClassName = null; } if (targetPackage != null) { clctxt.setServletPackageName(targetPackage); } originalClassLoader = Thread.currentThread().getContextClassLoader(); if( loader==null ) { initClassLoader( clctxt ); } Thread.currentThread().setContextClassLoader(loader); clctxt.setClassLoader(loader); clctxt.setClassPath(classPath); Compiler clc = clctxt.createCompiler(); // If compile is set, generate both .java and .class, if // .jsp file is newer than .class file; // Otherwise only generate .java, if .jsp file is newer than // the .java file if( clc.isOutDated(compile) ) { if (log.isDebugEnabled()) { log.debug(jspUri + " is out dated, compiling..."); } clc.compile(compile, true); } // Generate mapping generateWebMapping( file, clctxt ); if ( showSuccess ) { log.info( "Built File: " + file ); } } catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } } catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); } finally { if(originalClassLoader != null) { Thread.currentThread().setContextClassLoader(originalClassLoader); } } }
// in java/org/apache/jasper/JspC.java
public void execute() throws JasperException { if(log.isDebugEnabled()) { log.debug("execute() starting for " + pages.size() + " pages."); } try { if (uriRoot == null) { if( pages.size() == 0 ) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.missingTarget")); } String firstJsp = pages.get( 0 ); File firstJspF = new File( firstJsp ); if (!firstJspF.exists()) { throw new JasperException( Localizer.getMessage("jspc.error.fileDoesNotExist", firstJsp)); } locateUriRoot( firstJspF ); } if (uriRoot == null) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.no_uriroot")); } File uriRootF = new File(uriRoot); if (!uriRootF.isDirectory()) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.uriroot_not_dir")); } if(context == null) { initServletContext(); } // No explicit pages, we'll process all .jsp in the webapp if (pages.size() == 0) { scanFiles(uriRootF); } initWebXml(); Iterator<String> iter = pages.iterator(); while (iter.hasNext()) { String nextjsp = iter.next().toString(); File fjsp = new File(nextjsp); if (!fjsp.isAbsolute()) { fjsp = new File(uriRootF, nextjsp); } if (!fjsp.exists()) { if (log.isWarnEnabled()) { log.warn (Localizer.getMessage ("jspc.error.fileDoesNotExist", fjsp.toString())); } continue; } String s = fjsp.getAbsolutePath(); if (s.startsWith(uriRoot)) { nextjsp = s.substring(uriRoot.length()); } if (nextjsp.startsWith("." + File.separatorChar)) { nextjsp = nextjsp.substring(2); } processFile(nextjsp); } completeWebXml(); if (addWebXmlMappings) { mergeIntoWebXml(); } } catch (IOException ioe) { throw new JasperException(ioe); } catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { rootCause.printStackTrace(); } throw je; } finally { if (loader != null) { LogFactory.release(loader); } } }
37
            
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException ("error in invoking method", ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (Exception ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); }
// in java/org/apache/jasper/compiler/ParserController.java
catch (FileNotFoundException ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/compiler/BeanRepository.java
catch (ClassNotFoundException ex) { throw new JasperException (ex); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
catch (IOException ioe) { throw new JasperException(ioe); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage( "jsp.error.internal.tldinit", ex.getMessage()), ex); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
catch (ClassNotFoundException e) { throw new JasperException(e); }
// in java/org/apache/jasper/compiler/TagPluginManager.java
catch (Exception e) { throw new JasperException(e); }
// in java/org/apache/jasper/compiler/JspConfig.java
catch (Exception ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JasperException(t); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (FileNotFoundException ex) { throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (ClassNotFoundException cex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.load"), cex); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (Exception ex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (ParserConfigurationException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), ex); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXParseException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXException sx) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), sx); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (IOException io) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), io); }
// in java/org/apache/jasper/JspC.java
catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { throw new JasperException(ioe); }
491
            
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
Override public Void run() throws JasperException { internalIntrospecthelper( bean,prop,value,request,param,ignoreMethodNF); return null; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object convert(String propertyName, String s, Class<?> t, Class<?> propertyEditorClass) throws JasperException { try { if (s == null) { if (t.equals(Boolean.class) || t.equals(Boolean.TYPE)) s = "false"; else return null; } if (propertyEditorClass != null) { return getValueFromBeanInfoPropertyEditor( t, propertyName, s, propertyEditorClass); } else if ( t.equals(Boolean.class) || t.equals(Boolean.TYPE) ) { if (s.equalsIgnoreCase("on") || s.equalsIgnoreCase("true")) s = "true"; else s = "false"; return Boolean.valueOf(s); } else if ( t.equals(Byte.class) || t.equals(Byte.TYPE) ) { return Byte.valueOf(s); } else if (t.equals(Character.class) || t.equals(Character.TYPE)) { return s.length() > 0 ? Character.valueOf(s.charAt(0)) : null; } else if ( t.equals(Short.class) || t.equals(Short.TYPE) ) { return Short.valueOf(s); } else if ( t.equals(Integer.class) || t.equals(Integer.TYPE) ) { return Integer.valueOf(s); } else if ( t.equals(Float.class) || t.equals(Float.TYPE) ) { return Float.valueOf(s); } else if ( t.equals(Long.class) || t.equals(Long.TYPE) ) { return Long.valueOf(s); } else if ( t.equals(Double.class) || t.equals(Double.TYPE) ) { return Double.valueOf(s); } else if ( t.equals(String.class) ) { return s; } else if ( t.equals(java.io.File.class) ) { return new java.io.File(s); } else if (t.getName().equals("java.lang.Object")) { return new Object[] {s}; } else { return getValueFromPropertyEditorManager( t, propertyName, s); } } catch (Exception ex) { throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void introspect(Object bean, ServletRequest request) throws JasperException { Enumeration<String> e = request.getParameterNames(); while ( e.hasMoreElements() ) { String name = e.nextElement(); String value = request.getParameter(name); introspecthelper(bean, name, value, request, name, true); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void introspecthelper(Object bean, String prop, String value, ServletRequest request, String param, boolean ignoreMethodNF) throws JasperException { if( Constants.IS_SECURITY_ENABLED ) { try { PrivilegedIntrospectHelper dp = new PrivilegedIntrospectHelper( bean,prop,value,request,param,ignoreMethodNF); AccessController.doPrivileged(dp); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); throw (JasperException)e; } } else { internalIntrospecthelper( bean,prop,value,request,param,ignoreMethodNF); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
private static void internalIntrospecthelper(Object bean, String prop, String value, ServletRequest request, String param, boolean ignoreMethodNF) throws JasperException { Method method = null; Class<?> type = null; Class<?> propertyEditorClass = null; try { java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(bean.getClass()); if ( info != null ) { java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); for (int i = 0 ; i < pd.length ; i++) { if ( pd[i].getName().equals(prop) ) { method = pd[i].getWriteMethod(); type = pd[i].getPropertyType(); propertyEditorClass = pd[i].getPropertyEditorClass(); break; } } } if ( method != null ) { if (type.isArray()) { if (request == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.setproperty.noindexset")); } Class<?> t = type.getComponentType(); String[] values = request.getParameterValues(param); //XXX Please check. if(values == null) return; if(t.equals(String.class)) { method.invoke(bean, new Object[] { values }); } else { createTypedArray (prop, bean, method, values, t, propertyEditorClass); } } else { if(value == null || (param != null && value.equals(""))) return; Object oval = convert(prop, value, type, propertyEditorClass); if ( oval != null ) method.invoke(bean, new Object[] { oval }); } } } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } if (!ignoreMethodNF && (method == null)) { if (type == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.noproperty", prop, bean.getClass().getName())); } else { throw new JasperException( Localizer.getMessage("jsp.error.beans.nomethod.setproperty", prop, type.getName(), bean.getClass().getName())); } } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void createTypedArray(String propertyName, Object bean, Method method, String[] values, Class<?> t, Class<?> propertyEditorClass) throws JasperException { try { if (propertyEditorClass != null) { Object[] tmpval = new Integer[values.length]; for (int i=0; i<values.length; i++) { tmpval[i] = getValueFromBeanInfoPropertyEditor( t, propertyName, values[i], propertyEditorClass); } method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Integer.class)) { Integer []tmpval = new Integer[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Integer (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Byte.class)) { Byte[] tmpval = new Byte[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Byte (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Boolean.class)) { Boolean[] tmpval = new Boolean[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Boolean.valueOf(values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Short.class)) { Short[] tmpval = new Short[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Short (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Long.class)) { Long[] tmpval = new Long[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Long (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Double.class)) { Double[] tmpval = new Double[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Double (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Float.class)) { Float[] tmpval = new Float[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = new Float (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(Character.class)) { Character[] tmpval = new Character[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Character.valueOf(values[i].charAt(0)); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(int.class)) { int []tmpval = new int[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Integer.parseInt (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(byte.class)) { byte[] tmpval = new byte[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Byte.parseByte (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(boolean.class)) { boolean[] tmpval = new boolean[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = (Boolean.valueOf(values[i])).booleanValue(); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(short.class)) { short[] tmpval = new short[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Short.parseShort (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(long.class)) { long[] tmpval = new long[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Long.parseLong (values[i]); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(double.class)) { double[] tmpval = new double[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Double.valueOf(values[i]).doubleValue(); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(float.class)) { float[] tmpval = new float[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = Float.valueOf(values[i]).floatValue(); method.invoke (bean, new Object[] {tmpval}); } else if (t.equals(char.class)) { char[] tmpval = new char[values.length]; for (int i = 0 ; i < values.length; i++) tmpval[i] = values[i].charAt(0); method.invoke (bean, new Object[] {tmpval}); } else { Object[] tmpval = new Integer[values.length]; for (int i=0; i<values.length; i++) { tmpval[i] = getValueFromPropertyEditorManager( t, propertyName, values[i]); } method.invoke (bean, new Object[] {tmpval}); } } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException ("error in invoking method", ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object handleGetProperty(Object o, String prop) throws JasperException { if (o == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.nullbean")); } Object value = null; try { Method method = getReadMethod(o.getClass(), prop); value = method.invoke(o, (Object[]) null); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException (ex); } return value; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetPropertyExpression(Object bean, String prop, String expression, PageContext pageContext, ProtectedFunctionMapper functionMapper ) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { PageContextImpl.proprietaryEvaluate( expression, method.getParameterTypes()[0], pageContext, functionMapper, false ) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, Object value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { value }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, int value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Integer.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, short value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Short.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, long value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Long.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, double value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Double.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, float value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Float.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, char value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Character.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, byte value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Byte.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void handleSetProperty(Object bean, String prop, boolean value) throws JasperException { try { Method method = getWriteMethod(bean.getClass(), prop); method.invoke(bean, new Object[] { Boolean.valueOf(value) }); } catch (Exception ex) { Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(thr); throw new JasperException(ex); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Method getWriteMethod(Class<?> beanClass, String prop) throws JasperException { Method method = null; Class<?> type = null; try { java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(beanClass); if ( info != null ) { java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); for (int i = 0 ; i < pd.length ; i++) { if ( pd[i].getName().equals(prop) ) { method = pd[i].getWriteMethod(); type = pd[i].getPropertyType(); break; } } } else { // just in case introspection silently fails. throw new JasperException( Localizer.getMessage("jsp.error.beans.nobeaninfo", beanClass.getName())); } } catch (Exception ex) { throw new JasperException (ex); } if (method == null) { if (type == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.noproperty", prop, beanClass.getName())); } else { throw new JasperException( Localizer.getMessage("jsp.error.beans.nomethod.setproperty", prop, type.getName(), beanClass.getName())); } } return method; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Method getReadMethod(Class<?> beanClass, String prop) throws JasperException { Method method = null; Class<?> type = null; try { java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(beanClass); if ( info != null ) { java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); for (int i = 0 ; i < pd.length ; i++) { if ( pd[i].getName().equals(prop) ) { method = pd[i].getReadMethod(); type = pd[i].getPropertyType(); break; } } } else { // just in case introspection silently fails. throw new JasperException( Localizer.getMessage("jsp.error.beans.nobeaninfo", beanClass.getName())); } } catch (Exception ex) { throw new JasperException (ex); } if (method == null) { if (type == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.noproperty", prop, beanClass.getName())); } else { throw new JasperException( Localizer.getMessage("jsp.error.beans.nomethod", prop, beanClass.getName())); } } return method; }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object getValueFromBeanInfoPropertyEditor( Class<?> attrClass, String attrName, String attrValue, Class<?> propertyEditorClass) throws JasperException { try { PropertyEditor pe = (PropertyEditor)propertyEditorClass.newInstance(); pe.setAsText(attrValue); return pe.getValue(); } catch (Exception ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static Object getValueFromPropertyEditorManager( Class<?> attrClass, String attrName, String attrValue) throws JasperException { try { PropertyEditor propEditor = PropertyEditorManager.findEditor(attrClass); if (propEditor != null) { propEditor.setAsText(attrValue); return propEditor.getValue(); } else { throw new IllegalArgumentException( Localizer.getMessage("jsp.error.beans.propertyeditor.notregistered")); } } catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage("jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); } }
// in java/org/apache/jasper/compiler/JspUtil.java
public static void checkScope(String scope, Node n, ErrorDispatcher err) throws JasperException { if (scope != null && !scope.equals("page") && !scope.equals("request") && !scope.equals("session") && !scope.equals("application")) { err.jspError(n, "jsp.error.invalid.scope", scope); } }
// in java/org/apache/jasper/compiler/JspUtil.java
public static void checkAttributes(String typeOfTag, Node n, ValidAttribute[] validAttributes, ErrorDispatcher err) throws JasperException { Attributes attrs = n.getAttributes(); Mark start = n.getStart(); boolean valid = true; // AttributesImpl.removeAttribute is broken, so we do this... int tempLength = (attrs == null) ? 0 : attrs.getLength(); Vector<String> temp = new Vector<String>(tempLength, 1); for (int i = 0; i < tempLength; i++) { @SuppressWarnings("null") // If attrs==null, tempLength == 0 String qName = attrs.getQName(i); if ((!qName.equals("xmlns")) && (!qName.startsWith("xmlns:"))) { temp.addElement(qName); } } // Add names of attributes specified using jsp:attribute Node.Nodes tagBody = n.getBody(); if (tagBody != null) { int numSubElements = tagBody.size(); for (int i = 0; i < numSubElements; i++) { Node node = tagBody.getNode(i); if (node instanceof Node.NamedAttribute) { String attrName = node.getAttributeValue("name"); temp.addElement(attrName); // Check if this value appear in the attribute of the node if (n.getAttributeValue(attrName) != null) { err.jspError(n, "jsp.error.duplicate.name.jspattribute", attrName); } } else { // Nothing can come before jsp:attribute, and only // jsp:body can come after it. break; } } } /* * First check to see if all the mandatory attributes are present. If so * only then proceed to see if the other attributes are valid for the * particular tag. */ String missingAttribute = null; for (int i = 0; i < validAttributes.length; i++) { int attrPos; if (validAttributes[i].mandatory) { attrPos = temp.indexOf(validAttributes[i].name); if (attrPos != -1) { temp.remove(attrPos); valid = true; } else { valid = false; missingAttribute = validAttributes[i].name; break; } } } // If mandatory attribute is missing then the exception is thrown if (!valid) { err.jspError(start, "jsp.error.mandatory.attribute", typeOfTag, missingAttribute); } // Check to see if there are any more attributes for the specified tag. int attrLeftLength = temp.size(); if (attrLeftLength == 0) { return; } // Now check to see if the rest of the attributes are valid too. String attribute = null; for (int j = 0; j < attrLeftLength; j++) { valid = false; attribute = temp.elementAt(j); for (int i = 0; i < validAttributes.length; i++) { if (attribute.equals(validAttributes[i].name)) { valid = true; break; } } if (!valid) { err.jspError(start, "jsp.error.invalid.attribute", typeOfTag, attribute); } } // XXX *could* move EL-syntax validation here... (sb) }
// in java/org/apache/jasper/compiler/JspUtil.java
public static String getTagHandlerClassName(String path, String urn, ErrorDispatcher err) throws JasperException { String className = null; int begin = 0; int index; index = path.lastIndexOf(".tag"); if (index == -1) { err.jspError("jsp.error.tagfile.badSuffix", path); } // It's tempting to remove the ".tag" suffix here, but we can't. // If we remove it, the fully-qualified class name of this tag // could conflict with the package name of other tags. // For instance, the tag file // /WEB-INF/tags/foo.tag // would have fully-qualified class name // org.apache.jsp.tag.web.foo // which would conflict with the package name of the tag file // /WEB-INF/tags/foo/bar.tag index = path.indexOf(WEB_INF_TAGS); if (index != -1) { className = Constants.TAG_FILE_PACKAGE_NAME + ".web"; begin = index + WEB_INF_TAGS.length(); } else { index = path.indexOf(META_INF_TAGS); if (index != -1) { className = getClassNameBase(urn); begin = index + META_INF_TAGS.length(); } else { err.jspError("jsp.error.tagfile.illegalPath", path); } } className += makeJavaPackage(path.substring(begin)); return className; }
// in java/org/apache/jasper/compiler/JspUtil.java
static InputStreamReader getReader(String fname, String encoding, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err) throws JasperException, IOException { return getReader(fname, encoding, jarFile, ctxt, err, 0); }
// in java/org/apache/jasper/compiler/JspUtil.java
static InputStreamReader getReader(String fname, String encoding, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err, int skip) throws JasperException, IOException { InputStreamReader reader = null; InputStream in = getInputStream(fname, jarFile, ctxt); for (int i = 0; i < skip; i++) { in.read(); } try { reader = new InputStreamReader(in, encoding); } catch (UnsupportedEncodingException ex) { err.jspError("jsp.error.unsupported.encoding", encoding); } return reader; }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visitBody(Node n) throws JasperException { SmapStratum smapSave = smap; String innerClass = n.getInnerClassName(); if (innerClass != null) { this.smap = innerClassMap.get(innerClass); } super.visitBody(n); smap = smapSave; }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.Declaration n) throws JasperException { doSmapText(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.Expression n) throws JasperException { doSmapText(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.Scriptlet n) throws JasperException { doSmapText(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.IncludeAction n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.ForwardAction n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.GetProperty n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.SetProperty n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.UseBean n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.PlugIn n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.CustomTag n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.UninterpretedTag n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.JspElement n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.JspText n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.NamedAttribute n) throws JasperException { visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.JspBody n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.InvokeAction n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.DoBodyAction n) throws JasperException { doSmap(n); visitBody(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.ELExpression n) throws JasperException { doSmap(n); }
// in java/org/apache/jasper/compiler/SmapUtil.java
Override public void visit(Node.TemplateText n) throws JasperException { Mark mark = n.getStart(); if (mark == null) { return; } //Add the file information String fileName = mark.getFile(); smap.addFile(unqualify(fileName), fileName); //Add a LineInfo that corresponds to the beginning of this node int iInputStartLine = mark.getLineNumber(); int iOutputStartLine = n.getBeginJavaLine(); int iOutputLineIncrement = breakAtLF? 1: 0; smap.addLineData(iInputStartLine, fileName, 1, iOutputStartLine, iOutputLineIncrement); // Output additional mappings in the text java.util.ArrayList<Integer> extraSmap = n.getExtraSmap(); if (extraSmap != null) { for (int i = 0; i < extraSmap.size(); i++) { iOutputStartLine += iOutputLineIncrement; smap.addLineData( iInputStartLine+extraSmap.get(i).intValue(), fileName, 1, iOutputStartLine, iOutputLineIncrement); } } }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void jspError(String fname, int line, int column, String errMsg, Exception ex) throws JasperException { throw new JasperException(fname + " (" + Localizer.getMessage("jsp.error.location", Integer.toString(line), Integer.toString(column)) + ") " + errMsg, ex); }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void jspError(String errMsg, Exception ex) throws JasperException { throw new JasperException(errMsg, ex); }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void javacError(JavacErrorDetail[] details) throws JasperException { if (details == null) { return; } Object[] args = null; StringBuilder buf = new StringBuilder(); for (int i=0; i < details.length; i++) { if (details[i].getJspBeginLineNumber() >= 0) { args = new Object[] { Integer.valueOf(details[i].getJspBeginLineNumber()), details[i].getJspFileName() }; buf.append(Constants.NEWLINE); buf.append(Constants.NEWLINE); buf.append(Localizer.getMessage("jsp.error.single.line.number", args)); buf.append(Constants.NEWLINE); buf.append(details[i].getErrorMessage()); buf.append(Constants.NEWLINE); buf.append(details[i].getJspExtract()); } else { args = new Object[] { Integer.valueOf(details[i].getJavaLineNumber()) }; buf.append(Constants.NEWLINE); buf.append(Constants.NEWLINE); buf.append(Localizer.getMessage("jsp.error.java.line.number", args)); buf.append(Constants.NEWLINE); buf.append(details[i].getErrorMessage()); } } buf.append(Constants.NEWLINE); buf.append(Constants.NEWLINE); buf.append("Stacktrace:"); throw new JasperException( Localizer.getMessage("jsp.error.unable.compile") + ": " + buf); }
// in java/org/apache/jasper/compiler/DefaultErrorHandler.java
Override public void javacError(String errorReport, Exception exception) throws JasperException { throw new JasperException( Localizer.getMessage("jsp.error.unable.compile"), exception); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.ParamAction n) throws JasperException { if (n.getValue().isExpression()) { scriptingElementSeen = true; } paramActionSeen = true; }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.IncludeAction n) throws JasperException { if (n.getPage().isExpression()) { scriptingElementSeen = true; } includeActionSeen = true; visitBody(n); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.ForwardAction n) throws JasperException { if (n.getPage().isExpression()) { scriptingElementSeen = true; } visitBody(n); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.SetProperty n) throws JasperException { if (n.getValue() != null && n.getValue().isExpression()) { scriptingElementSeen = true; } setPropertySeen = true; }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.UseBean n) throws JasperException { if (n.getBeanName() != null && n.getBeanName().isExpression()) { scriptingElementSeen = true; } usebeanSeen = true; visitBody(n); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.PlugIn n) throws JasperException { if (n.getHeight() != null && n.getHeight().isExpression()) { scriptingElementSeen = true; } if (n.getWidth() != null && n.getWidth().isExpression()) { scriptingElementSeen = true; } visitBody(n); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.CustomTag n) throws JasperException { // Check to see what kinds of element we see as child elements checkSeen( n.getChildInfo(), n ); }
// in java/org/apache/jasper/compiler/Collector.java
private void checkSeen( Node.ChildInfo ci, Node n ) throws JasperException { // save values collected so far boolean scriptingElementSeenSave = scriptingElementSeen; scriptingElementSeen = false; boolean usebeanSeenSave = usebeanSeen; usebeanSeen = false; boolean includeActionSeenSave = includeActionSeen; includeActionSeen = false; boolean paramActionSeenSave = paramActionSeen; paramActionSeen = false; boolean setPropertySeenSave = setPropertySeen; setPropertySeen = false; boolean hasScriptingVarsSave = hasScriptingVars; hasScriptingVars = false; // Scan attribute list for expressions if( n instanceof Node.CustomTag ) { Node.CustomTag ct = (Node.CustomTag)n; Node.JspAttribute[] attrs = ct.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { if (attrs[i].isExpression()) { scriptingElementSeen = true; break; } } } visitBody(n); if( (n instanceof Node.CustomTag) && !hasScriptingVars) { Node.CustomTag ct = (Node.CustomTag)n; hasScriptingVars = ct.getVariableInfos().length > 0 || ct.getTagVariableInfos().length > 0; } // Record if the tag element and its body contains any scriptlet. ci.setScriptless(! scriptingElementSeen); ci.setHasUseBean(usebeanSeen); ci.setHasIncludeAction(includeActionSeen); ci.setHasParamAction(paramActionSeen); ci.setHasSetProperty(setPropertySeen); ci.setHasScriptingVars(hasScriptingVars); // Propagate value of scriptingElementSeen up. scriptingElementSeen = scriptingElementSeen || scriptingElementSeenSave; usebeanSeen = usebeanSeen || usebeanSeenSave; setPropertySeen = setPropertySeen || setPropertySeenSave; includeActionSeen = includeActionSeen || includeActionSeenSave; paramActionSeen = paramActionSeen || paramActionSeenSave; hasScriptingVars = hasScriptingVars || hasScriptingVarsSave; }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.JspElement n) throws JasperException { if (n.getNameAttribute().isExpression()) scriptingElementSeen = true; Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; i < attrs.length; i++) { if (attrs[i].isExpression()) { scriptingElementSeen = true; break; } } visitBody(n); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.JspBody n) throws JasperException { checkSeen( n.getChildInfo(), n ); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.NamedAttribute n) throws JasperException { checkSeen( n.getChildInfo(), n ); }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.Declaration n) throws JasperException { scriptingElementSeen = true; }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.Expression n) throws JasperException { scriptingElementSeen = true; }
// in java/org/apache/jasper/compiler/Collector.java
Override public void visit(Node.Scriptlet n) throws JasperException { scriptingElementSeen = true; }
// in java/org/apache/jasper/compiler/Collector.java
public static void collect(Compiler compiler, Node.Nodes page) throws JasperException { CollectVisitor collectVisitor = new CollectVisitor(); page.visit(collectVisitor); collectVisitor.updatePageInfo(compiler.getPageInfo()); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(Visitor v) throws JasperException { Iterator<Node> iter = list.iterator(); while (iter.hasNext()) { Node n = iter.next(); n.accept(v); } }
// in java/org/apache/jasper/compiler/Node.java
public void visit(Root n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(JspRoot n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(PageDirective n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(TagDirective n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(IncludeDirective n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(TaglibDirective n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(AttributeDirective n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(VariableDirective n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(Comment n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(Declaration n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(Expression n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(Scriptlet n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(ELExpression n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(IncludeAction n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(ForwardAction n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(GetProperty n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(SetProperty n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(ParamAction n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(ParamsAction n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(FallBackAction n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(UseBean n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(PlugIn n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(CustomTag n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(UninterpretedTag n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(JspElement n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(JspText n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(NamedAttribute n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(JspBody n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(InvokeAction n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(DoBodyAction n) throws JasperException { doVisit(n); visitBody(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(TemplateText n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(JspOutput n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Node.java
public void visit(AttributeGenerator n) throws JasperException { doVisit(n); }
// in java/org/apache/jasper/compiler/Compiler.java
private ServletWriter setupContextWriter(String javaFileName) throws FileNotFoundException, JasperException { ServletWriter writer; // Setup the ServletWriter String javaEncoding = ctxt.getOptions().getJavaEncoding(); OutputStreamWriter osw = null; try { osw = new OutputStreamWriter( new FileOutputStream(javaFileName), javaEncoding); } catch (UnsupportedEncodingException ex) { errDispatcher.jspError("jsp.error.needAlternateJavaEncoding", javaEncoding); } writer = new ServletWriter(new PrintWriter(osw)); ctxt.setWriter(writer); return writer; }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile() throws FileNotFoundException, JasperException, Exception { compile(true); }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile(boolean compileClass) throws FileNotFoundException, JasperException, Exception { compile(compileClass, false); }
// in java/org/apache/jasper/compiler/Compiler.java
public void compile(boolean compileClass, boolean jspcMode) throws FileNotFoundException, JasperException, Exception { if (errDispatcher == null) { this.errDispatcher = new ErrorDispatcher(jspcMode); } try { String[] smap = generateJava(); File javaFile = new File(ctxt.getServletJavaFileName()); Long jspLastModified = ctxt.getLastModified(ctxt.getJspFile()); javaFile.setLastModified(jspLastModified.longValue()); if (compileClass) { generateClass(smap); // Fix for bugzilla 41606 // Set JspServletWrapper.servletClassLastModifiedTime after successful compile String targetFileName = ctxt.getClassFileName(); if (targetFileName != null) { File targetFile = new File(targetFileName); if (targetFile.exists()) { targetFile.setLastModified(jspLastModified.longValue()); if (jsw != null) { jsw.setServletClassLastModifiedTime( jspLastModified.longValue()); } } } } } finally { if (tfp != null && ctxt.isPrototypeMode()) { tfp.removeProtoTypeFiles(null); } // Make sure these object which are only used during the // generation and compilation of the JSP page get // dereferenced so that they can be GC'd and reduce the // memory footprint. tfp = null; errDispatcher = null; pageInfo = null; // Only get rid of the pageNodes if in production. // In development mode, they are used for detailed // error messages. // http://issues.apache.org/bugzilla/show_bug.cgi?id=37062 if (!this.options.getDevelopment()) { pageNodes = null; } if (ctxt.getWriter() != null) { ctxt.getWriter().close(); ctxt.setWriter(null); } } }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parse(String inFileName) throws FileNotFoundException, JasperException, IOException { // If we're parsing a packaged tag file or a resource included by it // (using an include directive), ctxt.getTagFileJar() returns the // JAR file from which to read the tag file or included resource, // respectively. isTagFile = ctxt.isTagFile(); directiveOnly = false; return doParse(inFileName, null, ctxt.getTagFileJarResource()); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parseDirectives(String inFileName) throws FileNotFoundException, JasperException, IOException { // If we're parsing a packaged tag file or a resource included by it // (using an include directive), ctxt.getTagFileJar() returns the // JAR file from which to read the tag file or included resource, // respectively. isTagFile = ctxt.isTagFile(); directiveOnly = true; return doParse(inFileName, null, ctxt.getTagFileJarResource()); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parse(String inFileName, Node parent, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { // For files that are statically included, isTagfile and directiveOnly // remain unchanged. return doParse(inFileName, parent, jarResource); }
// in java/org/apache/jasper/compiler/ParserController.java
public Node.Nodes parseTagFileDirectives(String inFileName, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { boolean isTagFileSave = isTagFile; boolean directiveOnlySave = directiveOnly; isTagFile = true; directiveOnly = true; Node.Nodes page = doParse(inFileName, null, jarResource); directiveOnly = directiveOnlySave; isTagFile = isTagFileSave; return page; }
// in java/org/apache/jasper/compiler/ParserController.java
private Node.Nodes doParse(String inFileName, Node parent, JarResource jarResource) throws FileNotFoundException, JasperException, IOException { Node.Nodes parsedPage = null; isEncodingSpecifiedInProlog = false; isBomPresent = false; isDefaultPageEncoding = false; JarFile jarFile = (jarResource == null) ? null : jarResource.getJarFile(); String absFileName = resolveFileName(inFileName); String jspConfigPageEnc = getJspConfigPageEncoding(absFileName); // Figure out what type of JSP document and encoding type we are // dealing with determineSyntaxAndEncoding(absFileName, jarFile, jspConfigPageEnc); if (parent != null) { // Included resource, add to dependent list if (jarFile == null) { compiler.getPageInfo().addDependant(absFileName, ctxt.getLastModified(absFileName)); } else { String entry = absFileName.substring(1); compiler.getPageInfo().addDependant( jarResource.getEntry(entry).toString(), Long.valueOf(jarFile.getEntry(entry).getTime())); } } if ((isXml && isEncodingSpecifiedInProlog) || isBomPresent) { /* * Make sure the encoding explicitly specified in the XML * prolog (if any) matches that in the JSP config element * (if any), treating "UTF-16", "UTF-16BE", and "UTF-16LE" as * identical. */ if (jspConfigPageEnc != null && !jspConfigPageEnc.equals(sourceEnc) && (!jspConfigPageEnc.startsWith("UTF-16") || !sourceEnc.startsWith("UTF-16"))) { err.jspError("jsp.error.prolog_config_encoding_mismatch", sourceEnc, jspConfigPageEnc); } } // Dispatch to the appropriate parser if (isXml) { // JSP document (XML syntax) // InputStream for jspx page is created and properly closed in // JspDocumentParser. parsedPage = JspDocumentParser.parse(this, absFileName, jarFile, parent, isTagFile, directiveOnly, sourceEnc, jspConfigPageEnc, isEncodingSpecifiedInProlog, isBomPresent); } else { // Standard syntax InputStreamReader inStreamReader = null; try { inStreamReader = JspUtil.getReader(absFileName, sourceEnc, jarFile, ctxt, err, skip); JspReader jspReader = new JspReader(ctxt, absFileName, sourceEnc, inStreamReader, err); parsedPage = Parser.parse(this, jspReader, parent, isTagFile, directiveOnly, jarResource, sourceEnc, jspConfigPageEnc, isDefaultPageEncoding, isBomPresent); } finally { if (inStreamReader != null) { try { inStreamReader.close(); } catch (Exception any) { } } } } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } baseDirStack.pop(); return parsedPage; }
// in java/org/apache/jasper/compiler/ParserController.java
private String getJspConfigPageEncoding(String absFileName) throws JasperException { JspConfig jspConfig = ctxt.getOptions().getJspConfig(); JspConfig.JspProperty jspProperty = jspConfig.findJspProperty(absFileName); return jspProperty.getPageEncoding(); }
// in java/org/apache/jasper/compiler/ParserController.java
private void determineSyntaxAndEncoding(String absFileName, JarFile jarFile, String jspConfigPageEnc) throws JasperException, IOException { isXml = false; /* * 'true' if the syntax (XML or standard) of the file is given * from external information: either via a JSP configuration element, * the ".jspx" suffix, or the enclosing file (for included resources) */ boolean isExternal = false; /* * Indicates whether we need to revert from temporary usage of * "ISO-8859-1" back to "UTF-8" */ boolean revert = false; JspConfig jspConfig = ctxt.getOptions().getJspConfig(); JspConfig.JspProperty jspProperty = jspConfig.findJspProperty( absFileName); if (jspProperty.isXml() != null) { // If <is-xml> is specified in a <jsp-property-group>, it is used. isXml = JspUtil.booleanValue(jspProperty.isXml()); isExternal = true; } else if (absFileName.endsWith(".jspx") || absFileName.endsWith(".tagx")) { isXml = true; isExternal = true; } if (isExternal && !isXml) { // JSP (standard) syntax. Use encoding specified in jsp-config // if provided. sourceEnc = jspConfigPageEnc; if (sourceEnc != null) { return; } // We don't know the encoding, so use BOM to determine it sourceEnc = "ISO-8859-1"; } else { // XML syntax or unknown, (auto)detect encoding ... Object[] ret = XMLEncodingDetector.getEncoding(absFileName, jarFile, ctxt, err); sourceEnc = (String) ret[0]; if (((Boolean) ret[1]).booleanValue()) { isEncodingSpecifiedInProlog = true; } if (((Boolean) ret[2]).booleanValue()) { isBomPresent = true; } skip = ((Integer) ret[3]).intValue(); if (!isXml && sourceEnc.equals("UTF-8")) { /* * We don't know if we're dealing with XML or standard syntax. * Therefore, we need to check to see if the page contains * a <jsp:root> element. * * We need to be careful, because the page may be encoded in * ISO-8859-1 (or something entirely different), and may * contain byte sequences that will cause a UTF-8 converter to * throw exceptions. * * It is safe to use a source encoding of ISO-8859-1 in this * case, as there are no invalid byte sequences in ISO-8859-1, * and the byte/character sequences we're looking for (i.e., * <jsp:root>) are identical in either encoding (both UTF-8 * and ISO-8859-1 are extensions of ASCII). */ sourceEnc = "ISO-8859-1"; revert = true; } } if (isXml) { // (This implies 'isExternal' is TRUE.) // We know we're dealing with a JSP document (via JSP config or // ".jspx" suffix), so we're done. return; } /* * At this point, 'isExternal' or 'isXml' is FALSE. * Search for jsp:root action, in order to determine if we're dealing * with XML or standard syntax (unless we already know what we're * dealing with, i.e., when 'isExternal' is TRUE and 'isXml' is FALSE). * No check for XML prolog, since nothing prevents a page from * outputting XML and still using JSP syntax (in this case, the * XML prolog is treated as template text). */ JspReader jspReader = null; try { jspReader = new JspReader(ctxt, absFileName, sourceEnc, jarFile, err); } catch (FileNotFoundException ex) { throw new JasperException(ex); } jspReader.setSingleFile(true); Mark startMark = jspReader.mark(); if (!isExternal) { jspReader.reset(startMark); if (hasJspRoot(jspReader)) { if (revert) { sourceEnc = "UTF-8"; } isXml = true; return; } else { if (revert && isBomPresent) { sourceEnc = "UTF-8"; } isXml = false; } } /* * At this point, we know we're dealing with JSP syntax. * If an XML prolog is provided, it's treated as template text. * Determine the page encoding from the page directive, unless it's * specified via JSP config. */ if (!isBomPresent) { sourceEnc = jspConfigPageEnc; if (sourceEnc == null) { sourceEnc = getPageEncodingForJspSyntax(jspReader, startMark); if (sourceEnc == null) { // Default to "ISO-8859-1" per JSP spec sourceEnc = "ISO-8859-1"; isDefaultPageEncoding = true; } } } }
// in java/org/apache/jasper/compiler/ParserController.java
private String getPageEncodingForJspSyntax(JspReader jspReader, Mark startMark) throws JasperException { String encoding = null; String saveEncoding = null; jspReader.reset(startMark); /* * Determine page encoding from directive of the form <%@ page %>, * <%@ tag %>, <jsp:directive.page > or <jsp:directive.tag >. */ while (true) { if (jspReader.skipUntil("<") == null) { break; } // If this is a comment, skip until its end if (jspReader.matches("%--")) { if (jspReader.skipUntil("--%>") == null) { // error will be caught in Parser break; } continue; } boolean isDirective = jspReader.matches("%@"); if (isDirective) { jspReader.skipSpaces(); } else { isDirective = jspReader.matches("jsp:directive."); } if (!isDirective) { continue; } // compare for "tag ", so we don't match "taglib" if (jspReader.matches("tag ") || jspReader.matches("page")) { jspReader.skipSpaces(); Attributes attrs = Parser.parseAttributes(this, jspReader); encoding = getPageEncodingFromDirective(attrs, "pageEncoding"); if (encoding != null) { break; } encoding = getPageEncodingFromDirective(attrs, "contentType"); if (encoding != null) { saveEncoding = encoding; } } } if (encoding == null) { encoding = saveEncoding; } return encoding; }
// in java/org/apache/jasper/compiler/ParserController.java
private boolean hasJspRoot(JspReader reader) throws JasperException { // <prefix>:root must be the first element Mark start = null; while ((start = reader.skipUntil("<")) != null) { int c = reader.nextChar(); if (c != '!' && c != '?') break; } if (start == null) { return false; } Mark stop = reader.skipUntil(":root"); if (stop == null) { return false; } // call substring to get rid of leading '<' String prefix = reader.getText(start, stop).substring(1); start = stop; stop = reader.skipUntil(">"); if (stop == null) { return false; } // Determine namespace associated with <root> element's prefix String root = reader.getText(start, stop); String xmlnsDecl = "xmlns:" + prefix; int index = root.indexOf(xmlnsDecl); if (index == -1) { return false; } index += xmlnsDecl.length(); while (index < root.length() && Character.isWhitespace(root.charAt(index))) { index++; } if (index < root.length() && root.charAt(index) == '=') { index++; while (index < root.length() && Character.isWhitespace(root.charAt(index))) { index++; } if (index < root.length() && (root.charAt(index) == '"' || root.charAt(index) == '\'')) { index++; if (root.regionMatches(index, JSP_URI, 0, JSP_URI.length())) { return true; } } } return false; }
// in java/org/apache/jasper/compiler/ELNode.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/ELNode.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/ELNode.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/ELNode.java
Override public void accept(Visitor v) throws JasperException { v.visit(this); }
// in java/org/apache/jasper/compiler/ELNode.java
public void visit(Visitor v) throws JasperException { Iterator<ELNode> iter = list.iterator(); while (iter.hasNext()) { ELNode n = iter.next(); n.accept(v); } }
// in java/org/apache/jasper/compiler/ELNode.java
public void visit(Root n) throws JasperException { n.getExpression().visit(this); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
private void parseTLD(String uri, InputStream in, JarResource jarResource) throws JasperException { Vector<TagInfo> tagVector = new Vector<TagInfo>(); Vector<TagFileInfo> tagFileVector = new Vector<TagFileInfo>(); Hashtable<String, FunctionInfo> functionTable = new Hashtable<String, FunctionInfo>(); // Create an iterator over the child elements of our <taglib> element ParserUtils pu = new ParserUtils(); TreeNode tld = pu.parseXMLDocument(uri, in); // Check to see if the <taglib> root element contains a 'version' // attribute, which was added in JSP 2.0 to replace the <jsp-version> // subelement this.jspversion = tld.findAttribute("version"); // Process each child element of our <taglib> element Iterator<TreeNode> list = tld.findChildren(); while (list.hasNext()) { TreeNode element = list.next(); String tname = element.getName(); if ("tlibversion".equals(tname) // JSP 1.1 || "tlib-version".equals(tname)) { // JSP 1.2 this.tlibversion = element.getBody(); } else if ("jspversion".equals(tname) || "jsp-version".equals(tname)) { this.jspversion = element.getBody(); } else if ("shortname".equals(tname) || "short-name".equals(tname)) this.shortname = element.getBody(); else if ("uri".equals(tname)) this.urn = element.getBody(); else if ("info".equals(tname) || "description".equals(tname)) this.info = element.getBody(); else if ("validator".equals(tname)) this.tagLibraryValidator = createValidator(element); else if ("tag".equals(tname)) tagVector.addElement(createTagInfo(element, jspversion)); else if ("tag-file".equals(tname)) { TagFileInfo tagFileInfo = createTagFileInfo(element, jarResource); tagFileVector.addElement(tagFileInfo); } else if ("function".equals(tname)) { // JSP2.0 FunctionInfo funcInfo = createFunctionInfo(element); String funcName = funcInfo.getName(); if (functionTable.containsKey(funcName)) { err.jspError("jsp.error.tld.fn.duplicate.name", funcName, uri); } functionTable.put(funcName, funcInfo); } else if ("display-name".equals(tname) || "small-icon".equals(tname) || "large-icon".equals(tname) || "listener".equals(tname)) { // Ignored elements } else if ("taglib-extension".equals(tname)) { // Recognized but ignored } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage( "jsp.warning.unknown.element.in.taglib", tname)); } } } if (tlibversion == null) { err.jspError("jsp.error.tld.mandatory.element.missing", "tlib-version", uri); } if (jspversion == null) { err.jspError("jsp.error.tld.mandatory.element.missing", "jsp-version", uri); } this.tags = new TagInfo[tagVector.size()]; tagVector.copyInto(this.tags); this.tagFiles = new TagFileInfo[tagFileVector.size()]; tagFileVector.copyInto(this.tagFiles); this.functions = new FunctionInfo[functionTable.size()]; int i = 0; Enumeration<FunctionInfo> enumeration = functionTable.elements(); while (enumeration.hasMoreElements()) { this.functions[i++] = enumeration.nextElement(); } }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
private TldLocation generateTLDLocation(String uri, JspCompilationContext ctxt) throws JasperException { int uriType = TldLocationsCache.uriType(uri); if (uriType == TldLocationsCache.ABS_URI) { err.jspError("jsp.error.taglibDirective.absUriCannotBeResolved", uri); } else if (uriType == TldLocationsCache.NOROOT_REL_URI) { uri = ctxt.resolveRelativeUri(uri); } if (uri.endsWith(".jar")) { URL url = null; try { url = ctxt.getResource(uri); } catch (Exception ex) { err.jspError("jsp.error.tld.unable_to_get_jar", uri, ex .toString()); } if (url == null) { err.jspError("jsp.error.tld.missing_jar", uri); } return new TldLocation("META-INF/taglib.tld", url.toString()); } else { return new TldLocation(uri); } }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
private TagInfo createTagInfo(TreeNode elem, String jspVersion) throws JasperException { String tagName = null; String tagClassName = null; String teiClassName = null; /* * Default body content for JSP 1.2 tag handlers (<body-content> has * become mandatory in JSP 2.0, because the default would be invalid for * simple tag handlers) */ String bodycontent = "JSP"; String info = null; String displayName = null; String smallIcon = null; String largeIcon = null; boolean dynamicAttributes = false; Vector<TagAttributeInfo> attributeVector = new Vector<TagAttributeInfo>(); Vector<TagVariableInfo> variableVector = new Vector<TagVariableInfo>(); Iterator<TreeNode> list = elem.findChildren(); while (list.hasNext()) { TreeNode element = list.next(); String tname = element.getName(); if ("name".equals(tname)) { tagName = element.getBody(); } else if ("tagclass".equals(tname) || "tag-class".equals(tname)) { tagClassName = element.getBody(); } else if ("teiclass".equals(tname) || "tei-class".equals(tname)) { teiClassName = element.getBody(); } else if ("bodycontent".equals(tname) || "body-content".equals(tname)) { bodycontent = element.getBody(); } else if ("display-name".equals(tname)) { displayName = element.getBody(); } else if ("small-icon".equals(tname)) { smallIcon = element.getBody(); } else if ("large-icon".equals(tname)) { largeIcon = element.getBody(); } else if ("icon".equals(tname)) { TreeNode icon = element.findChild("small-icon"); if (icon != null) { smallIcon = icon.getBody(); } icon = element.findChild("large-icon"); if (icon != null) { largeIcon = icon.getBody(); } } else if ("info".equals(tname) || "description".equals(tname)) { info = element.getBody(); } else if ("variable".equals(tname)) { variableVector.addElement(createVariable(element)); } else if ("attribute".equals(tname)) { attributeVector .addElement(createAttribute(element, jspVersion)); } else if ("dynamic-attributes".equals(tname)) { dynamicAttributes = JspUtil.booleanValue(element.getBody()); } else if ("example".equals(tname)) { // Ignored elements } else if ("tag-extension".equals(tname)) { // Ignored } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage( "jsp.warning.unknown.element.in.tag", tname)); } } } TagExtraInfo tei = null; if (teiClassName != null && !teiClassName.equals("")) { try { Class<?> teiClass = ctxt.getClassLoader().loadClass(teiClassName); tei = (TagExtraInfo) teiClass.newInstance(); } catch (Exception e) { err.jspError("jsp.error.teiclass.instantiation", teiClassName, e); } } TagAttributeInfo[] tagAttributeInfo = new TagAttributeInfo[attributeVector .size()]; attributeVector.copyInto(tagAttributeInfo); TagVariableInfo[] tagVariableInfos = new TagVariableInfo[variableVector .size()]; variableVector.copyInto(tagVariableInfos); TagInfo taginfo = new TagInfo(tagName, tagClassName, bodycontent, info, this, tei, tagAttributeInfo, displayName, smallIcon, largeIcon, tagVariableInfos, dynamicAttributes); return taginfo; }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
private TagFileInfo createTagFileInfo(TreeNode elem, JarResource jarResource) throws JasperException { String name = null; String path = null; Iterator<TreeNode> list = elem.findChildren(); while (list.hasNext()) { TreeNode child = list.next(); String tname = child.getName(); if ("name".equals(tname)) { name = child.getBody(); } else if ("path".equals(tname)) { path = child.getBody(); } else if ("example".equals(tname)) { // Ignore <example> element: Bugzilla 33538 } else if ("tag-extension".equals(tname)) { // Ignore <tag-extension> element: Bugzilla 33538 } else if ("icon".equals(tname) || "display-name".equals(tname) || "description".equals(tname)) { // Ignore these elements: Bugzilla 38015 } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage( "jsp.warning.unknown.element.in.tagfile", tname)); } } } if (path.startsWith("/META-INF/tags")) { // Tag file packaged in JAR // See https://issues.apache.org/bugzilla/show_bug.cgi?id=46471 // This needs to be removed once all the broken code that depends on // it has been removed ctxt.setTagFileJarResource(path, jarResource); } else if (!path.startsWith("/WEB-INF/tags")) { err.jspError("jsp.error.tagfile.illegalPath", path); } TagInfo tagInfo = TagFileProcessor.parseTagFileDirectives( parserController, name, path, jarResource, this); return new TagFileInfo(name, path, tagInfo); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
private TagLibraryValidator createValidator(TreeNode elem) throws JasperException { String validatorClass = null; Map<String,Object> initParams = new Hashtable<String,Object>(); Iterator<TreeNode> list = elem.findChildren(); while (list.hasNext()) { TreeNode element = list.next(); String tname = element.getName(); if ("validator-class".equals(tname)) validatorClass = element.getBody(); else if ("init-param".equals(tname)) { String[] initParam = createInitParam(element); initParams.put(initParam[0], initParam[1]); } else if ("description".equals(tname) || // Ignored elements false) { } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage( "jsp.warning.unknown.element.in.validator", tname)); } } } TagLibraryValidator tlv = null; if (validatorClass != null && !validatorClass.equals("")) { try { Class<?> tlvClass = ctxt.getClassLoader() .loadClass(validatorClass); tlv = (TagLibraryValidator) tlvClass.newInstance(); } catch (Exception e) { err.jspError("jsp.error.tlvclass.instantiation", validatorClass, e); } } if (tlv != null) { tlv.setInitParameters(initParams); } return tlv; }
// in java/org/apache/jasper/compiler/Parser.java
public static Node.Nodes parse(ParserController pc, JspReader reader, Node parent, boolean isTagFile, boolean directivesOnly, JarResource jarResource, String pageEnc, String jspConfigPageEnc, boolean isDefaultPageEncoding, boolean isBomPresent) throws JasperException { Parser parser = new Parser(pc, reader, isTagFile, directivesOnly, jarResource); Node.Root root = new Node.Root(reader.mark(), parent, false); root.setPageEncoding(pageEnc); root.setJspConfigPageEncoding(jspConfigPageEnc); root.setIsDefaultPageEncoding(isDefaultPageEncoding); root.setIsBomPresent(isBomPresent); // For the Top level page, add include-prelude and include-coda PageInfo pageInfo = pc.getCompiler().getPageInfo(); if (parent == null && !isTagFile) { parser.addInclude(root, pageInfo.getIncludePrelude()); } if (directivesOnly) { parser.parseFileDirectives(root); } else { while (reader.hasMoreInput()) { parser.parseElements(root); } } if (parent == null && !isTagFile) { parser.addInclude(root, pageInfo.getIncludeCoda()); } Node.Nodes page = new Node.Nodes(root); return page; }
// in java/org/apache/jasper/compiler/Parser.java
Attributes parseAttributes() throws JasperException { return parseAttributes(false); }
// in java/org/apache/jasper/compiler/Parser.java
Attributes parseAttributes(boolean pageDirective) throws JasperException { UniqueAttributesImpl attrs = new UniqueAttributesImpl(pageDirective); reader.skipSpaces(); int ws = 1; try { while (parseAttribute(attrs)) { if (ws == 0 && STRICT_WHITESPACE) { err.jspError(reader.mark(), "jsp.error.attribute.nowhitespace"); } ws = reader.skipSpaces(); } } catch (IllegalArgumentException iae) { // Duplicate attribute err.jspError(reader.mark(), "jsp.error.attribute.duplicate"); } return attrs; }
// in java/org/apache/jasper/compiler/Parser.java
public static Attributes parseAttributes(ParserController pc, JspReader reader) throws JasperException { Parser tmpParser = new Parser(pc, reader, false, false, null); return tmpParser.parseAttributes(true); }
// in java/org/apache/jasper/compiler/Parser.java
private boolean parseAttribute(AttributesImpl attrs) throws JasperException { // Get the qualified name String qName = parseName(); if (qName == null) return false; // Determine prefix and local name components String localName = qName; String uri = ""; int index = qName.indexOf(':'); if (index != -1) { String prefix = qName.substring(0, index); uri = pageInfo.getURI(prefix); if (uri == null) { err.jspError(reader.mark(), "jsp.error.attribute.invalidPrefix", prefix); } localName = qName.substring(index + 1); } reader.skipSpaces(); if (!reader.matches("=")) err.jspError(reader.mark(), "jsp.error.attribute.noequal"); reader.skipSpaces(); char quote = (char) reader.nextChar(); if (quote != '\'' && quote != '"') err.jspError(reader.mark(), "jsp.error.attribute.noquote"); String watchString = ""; if (reader.matches("<%=")) watchString = "%>"; watchString = watchString + quote; String attrValue = parseAttributeValue(watchString); attrs.addAttribute(uri, localName, qName, "CDATA", attrValue); return true; }
// in java/org/apache/jasper/compiler/Parser.java
private String parseName() throws JasperException { char ch = (char) reader.peekChar(); if (Character.isLetter(ch) || ch == '_' || ch == ':') { StringBuilder buf = new StringBuilder(); buf.append(ch); reader.nextChar(); ch = (char) reader.peekChar(); while (Character.isLetter(ch) || Character.isDigit(ch) || ch == '.' || ch == '_' || ch == '-' || ch == ':') { buf.append(ch); reader.nextChar(); ch = (char) reader.peekChar(); } return buf.toString(); } return null; }
// in java/org/apache/jasper/compiler/Parser.java
private String parseAttributeValue(String watch) throws JasperException { Mark start = reader.mark(); Mark stop = reader.skipUntilIgnoreEsc(watch); if (stop == null) { err.jspError(start, "jsp.error.attribute.unterminated", watch); } String ret = null; try { char quote = watch.charAt(watch.length() - 1); // If watch is longer than 1 character this is a scripting // expression and EL is always ignored boolean isElIgnored = pageInfo.isELIgnored() || watch.length() > 1; ret = AttributeParser.getUnquoted(reader.getText(start, stop), quote, isElIgnored, pageInfo.isDeferredSyntaxAllowedAsLiteral()); } catch (IllegalArgumentException iae) { err.jspError(start, iae.getMessage()); } if (watch.length() == 1) // quote return ret; // Put back delimiter '<%=' and '%>', since they are needed if the // attribute does not allow RTexpression. return "<%=" + ret + "%>"; }
// in java/org/apache/jasper/compiler/Parser.java
private void processIncludeDirective(String file, Node parent) throws JasperException { if (file == null) { return; } try { parserController.parse(file, parent, jarResource); } catch (FileNotFoundException ex) { err.jspError(start, "jsp.error.file.not.found", file); } catch (Exception ex) { err.jspError(start, ex.getMessage()); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parsePageDirective(Node parent) throws JasperException { Attributes attrs = parseAttributes(true); Node.PageDirective n = new Node.PageDirective(attrs, start, parent); /* * A page directive may contain multiple 'import' attributes, each of * which consists of a comma-separated list of package names. Store each * list with the node, where it is parsed. */ for (int i = 0; i < attrs.getLength(); i++) { if ("import".equals(attrs.getQName(i))) { n.addImport(attrs.getValue(i)); } } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseIncludeDirective(Node parent) throws JasperException { Attributes attrs = parseAttributes(); // Included file expanded here Node includeNode = new Node.IncludeDirective(attrs, start, parent); processIncludeDirective(attrs.getValue("file"), includeNode); }
// in java/org/apache/jasper/compiler/Parser.java
private void addInclude(Node parent, List<String> files) throws JasperException { if (files != null) { Iterator<String> iter = files.iterator(); while (iter.hasNext()) { String file = iter.next(); AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute("", "file", "file", "CDATA", file); // Create a dummy Include directive node Node includeNode = new Node.IncludeDirective(attrs, reader .mark(), parent); processIncludeDirective(file, includeNode); } } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseTaglibDirective(Node parent) throws JasperException { Attributes attrs = parseAttributes(); String uri = attrs.getValue("uri"); String prefix = attrs.getValue("prefix"); if (prefix != null) { Mark prevMark = pageInfo.getNonCustomTagPrefix(prefix); if (prevMark != null) { err.jspError(reader.mark(), "jsp.error.prefix.use_before_dcl", prefix, prevMark.getFile(), "" + prevMark.getLineNumber()); } if (uri != null) { String uriPrev = pageInfo.getURI(prefix); if (uriPrev != null && !uriPrev.equals(uri)) { err.jspError(reader.mark(), "jsp.error.prefix.refined", prefix, uri, uriPrev); } if (pageInfo.getTaglib(uri) == null) { TagLibraryInfoImpl impl = null; if (ctxt.getOptions().isCaching()) { impl = (TagLibraryInfoImpl) ctxt.getOptions() .getCache().get(uri); } if (impl == null) { TldLocation location = ctxt.getTldLocation(uri); impl = new TagLibraryInfoImpl(ctxt, parserController, pageInfo, prefix, uri, location, err, reader.mark()); if (ctxt.getOptions().isCaching()) { ctxt.getOptions().getCache().put(uri, impl); } } else { // Current compilation context needs location of cached // tag files for (TagFileInfo info : impl.getTagFiles()) { ctxt.setTagFileJarResource(info.getPath(), ctxt.getTagFileJarResource()); } } pageInfo.addTaglib(uri, impl); } pageInfo.addPrefixMapping(prefix, uri); } else { String tagdir = attrs.getValue("tagdir"); if (tagdir != null) { String urnTagdir = URN_JSPTAGDIR + tagdir; if (pageInfo.getTaglib(urnTagdir) == null) { pageInfo.addTaglib(urnTagdir, new ImplicitTagLibraryInfo(ctxt, parserController, pageInfo, prefix, tagdir, err)); } pageInfo.addPrefixMapping(prefix, urnTagdir); } } } new Node.TaglibDirective(attrs, start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseDirective(Node parent) throws JasperException { reader.skipSpaces(); String directive = null; if (reader.matches("page")) { directive = "&lt;%@ page"; if (isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.istagfile", directive); } parsePageDirective(parent); } else if (reader.matches("include")) { directive = "&lt;%@ include"; parseIncludeDirective(parent); } else if (reader.matches("taglib")) { if (directivesOnly) { // No need to get the tagLibInfo objects. This alos suppresses // parsing of any tag files used in this tag file. return; } directive = "&lt;%@ taglib"; parseTaglibDirective(parent); } else if (reader.matches("tag")) { directive = "&lt;%@ tag"; if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.isnottagfile", directive); } parseTagDirective(parent); } else if (reader.matches("attribute")) { directive = "&lt;%@ attribute"; if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.isnottagfile", directive); } parseAttributeDirective(parent); } else if (reader.matches("variable")) { directive = "&lt;%@ variable"; if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.isnottagfile", directive); } parseVariableDirective(parent); } else { err.jspError(reader.mark(), "jsp.error.invalid.directive"); } reader.skipSpaces(); if (!reader.matches("%>")) { err.jspError(start, "jsp.error.unterminated", directive); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseXMLDirective(Node parent) throws JasperException { reader.skipSpaces(); String eTag = null; if (reader.matches("page")) { eTag = "jsp:directive.page"; if (isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.istagfile", "&lt;" + eTag); } parsePageDirective(parent); } else if (reader.matches("include")) { eTag = "jsp:directive.include"; parseIncludeDirective(parent); } else if (reader.matches("tag")) { eTag = "jsp:directive.tag"; if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.isnottagfile", "&lt;" + eTag); } parseTagDirective(parent); } else if (reader.matches("attribute")) { eTag = "jsp:directive.attribute"; if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.isnottagfile", "&lt;" + eTag); } parseAttributeDirective(parent); } else if (reader.matches("variable")) { eTag = "jsp:directive.variable"; if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.directive.isnottagfile", "&lt;" + eTag); } parseVariableDirective(parent); } else { err.jspError(reader.mark(), "jsp.error.invalid.directive"); } reader.skipSpaces(); if (reader.matches(">")) { reader.skipSpaces(); if (!reader.matchesETag(eTag)) { err.jspError(start, "jsp.error.unterminated", "&lt;" + eTag); } } else if (!reader.matches("/>")) { err.jspError(start, "jsp.error.unterminated", "&lt;" + eTag); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseTagDirective(Node parent) throws JasperException { Attributes attrs = parseAttributes(true); Node.TagDirective n = new Node.TagDirective(attrs, start, parent); /* * A page directive may contain multiple 'import' attributes, each of * which consists of a comma-separated list of package names. Store each * list with the node, where it is parsed. */ for (int i = 0; i < attrs.getLength(); i++) { if ("import".equals(attrs.getQName(i))) { n.addImport(attrs.getValue(i)); } } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseAttributeDirective(Node parent) throws JasperException { Attributes attrs = parseAttributes(); new Node.AttributeDirective(attrs, start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseVariableDirective(Node parent) throws JasperException { Attributes attrs = parseAttributes(); new Node.VariableDirective(attrs, start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseComment(Node parent) throws JasperException { start = reader.mark(); Mark stop = reader.skipUntil("--%>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "&lt;%--"); } new Node.Comment(reader.getText(start, stop), start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseDeclaration(Node parent) throws JasperException { start = reader.mark(); Mark stop = reader.skipUntil("%>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "&lt;%!"); } new Node.Declaration(parseScriptText(reader.getText(start, stop)), start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseXMLDeclaration(Node parent) throws JasperException { reader.skipSpaces(); if (!reader.matches("/>")) { if (!reader.matches(">")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:declaration&gt;"); } Mark stop; String text; while (true) { start = reader.mark(); stop = reader.skipUntil("<"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:declaration&gt;"); } text = parseScriptText(reader.getText(start, stop)); new Node.Declaration(text, start, parent); if (reader.matches("![CDATA[")) { start = reader.mark(); stop = reader.skipUntil("]]>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "CDATA"); } text = parseScriptText(reader.getText(start, stop)); new Node.Declaration(text, start, parent); } else { break; } } if (!reader.matchesETagWithoutLessThan("jsp:declaration")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:declaration&gt;"); } } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseExpression(Node parent) throws JasperException { start = reader.mark(); Mark stop = reader.skipUntil("%>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "&lt;%="); } new Node.Expression(parseScriptText(reader.getText(start, stop)), start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseXMLExpression(Node parent) throws JasperException { reader.skipSpaces(); if (!reader.matches("/>")) { if (!reader.matches(">")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:expression&gt;"); } Mark stop; String text; while (true) { start = reader.mark(); stop = reader.skipUntil("<"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:expression&gt;"); } text = parseScriptText(reader.getText(start, stop)); new Node.Expression(text, start, parent); if (reader.matches("![CDATA[")) { start = reader.mark(); stop = reader.skipUntil("]]>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "CDATA"); } text = parseScriptText(reader.getText(start, stop)); new Node.Expression(text, start, parent); } else { break; } } if (!reader.matchesETagWithoutLessThan("jsp:expression")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:expression&gt;"); } } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseELExpression(Node parent, char type) throws JasperException { start = reader.mark(); Mark last = null; boolean singleQuoted = false, doubleQuoted = false; int currentChar; do { // XXX could move this logic to JspReader last = reader.mark(); // XXX somewhat wasteful currentChar = reader.nextChar(); if (currentChar == '\\' && (singleQuoted || doubleQuoted)) { // skip character following '\' within quotes reader.nextChar(); currentChar = reader.nextChar(); } if (currentChar == -1) err.jspError(start, "jsp.error.unterminated", type + "{"); if (currentChar == '"' && !singleQuoted) doubleQuoted = !doubleQuoted; if (currentChar == '\'' && !doubleQuoted) singleQuoted = !singleQuoted; } while (currentChar != '}' || (singleQuoted || doubleQuoted)); new Node.ELExpression(type, reader.getText(start, last), start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseScriptlet(Node parent) throws JasperException { start = reader.mark(); Mark stop = reader.skipUntil("%>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "&lt;%"); } new Node.Scriptlet(parseScriptText(reader.getText(start, stop)), start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseXMLScriptlet(Node parent) throws JasperException { reader.skipSpaces(); if (!reader.matches("/>")) { if (!reader.matches(">")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:scriptlet&gt;"); } Mark stop; String text; while (true) { start = reader.mark(); stop = reader.skipUntil("<"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:scriptlet&gt;"); } text = parseScriptText(reader.getText(start, stop)); new Node.Scriptlet(text, start, parent); if (reader.matches("![CDATA[")) { start = reader.mark(); stop = reader.skipUntil("]]>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "CDATA"); } text = parseScriptText(reader.getText(start, stop)); new Node.Scriptlet(text, start, parent); } else { break; } } if (!reader.matchesETagWithoutLessThan("jsp:scriptlet")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:scriptlet&gt;"); } } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseParam(Node parent) throws JasperException { if (!reader.matches("<jsp:param")) { err.jspError(reader.mark(), "jsp.error.paramexpected"); } Attributes attrs = parseAttributes(); reader.skipSpaces(); Node paramActionNode = new Node.ParamAction(attrs, start, parent); parseEmptyBody(paramActionNode, "jsp:param"); reader.skipSpaces(); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseInclude(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node includeNode = new Node.IncludeAction(attrs, start, parent); parseOptionalBody(includeNode, "jsp:include", JAVAX_BODY_CONTENT_PARAM); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseForward(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node forwardNode = new Node.ForwardAction(attrs, start, parent); parseOptionalBody(forwardNode, "jsp:forward", JAVAX_BODY_CONTENT_PARAM); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseInvoke(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node invokeNode = new Node.InvokeAction(attrs, start, parent); parseEmptyBody(invokeNode, "jsp:invoke"); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseDoBody(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node doBodyNode = new Node.DoBodyAction(attrs, start, parent); parseEmptyBody(doBodyNode, "jsp:doBody"); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseElement(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node elementNode = new Node.JspElement(attrs, start, parent); parseOptionalBody(elementNode, "jsp:element", TagInfo.BODY_CONTENT_JSP); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseGetProperty(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node getPropertyNode = new Node.GetProperty(attrs, start, parent); parseOptionalBody(getPropertyNode, "jsp:getProperty", TagInfo.BODY_CONTENT_EMPTY); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseSetProperty(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node setPropertyNode = new Node.SetProperty(attrs, start, parent); parseOptionalBody(setPropertyNode, "jsp:setProperty", TagInfo.BODY_CONTENT_EMPTY); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseEmptyBody(Node parent, String tag) throws JasperException { if (reader.matches("/>")) { // Done } else if (reader.matches(">")) { if (reader.matchesETag(tag)) { // Done } else if (reader.matchesOptionalSpacesFollowedBy("<jsp:attribute")) { // Parse the one or more named attribute nodes parseNamedAttributes(parent); if (!reader.matchesETag(tag)) { // Body not allowed err.jspError(reader.mark(), "jsp.error.jspbody.emptybody.only", "&lt;" + tag); } } else { err.jspError(reader.mark(), "jsp.error.jspbody.emptybody.only", "&lt;" + tag); } } else { err.jspError(reader.mark(), "jsp.error.unterminated", "&lt;" + tag); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseUseBean(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node useBeanNode = new Node.UseBean(attrs, start, parent); parseOptionalBody(useBeanNode, "jsp:useBean", TagInfo.BODY_CONTENT_JSP); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseOptionalBody(Node parent, String tag, String bodyType) throws JasperException { if (reader.matches("/>")) { // EmptyBody return; } if (!reader.matches(">")) { err.jspError(reader.mark(), "jsp.error.unterminated", "&lt;" + tag); } if (reader.matchesETag(tag)) { // EmptyBody return; } if (!parseJspAttributeAndBody(parent, tag, bodyType)) { // Must be ( '>' # Body ETag ) parseBody(parent, tag, bodyType); } }
// in java/org/apache/jasper/compiler/Parser.java
private boolean parseJspAttributeAndBody(Node parent, String tag, String bodyType) throws JasperException { boolean result = false; if (reader.matchesOptionalSpacesFollowedBy("<jsp:attribute")) { // May be an EmptyBody, depending on whether // There's a "<jsp:body" before the ETag // First, parse <jsp:attribute> elements: parseNamedAttributes(parent); result = true; } if (reader.matchesOptionalSpacesFollowedBy("<jsp:body")) { // ActionBody parseJspBody(parent, bodyType); reader.skipSpaces(); if (!reader.matchesETag(tag)) { err.jspError(reader.mark(), "jsp.error.unterminated", "&lt;" + tag); } result = true; } else if (result && !reader.matchesETag(tag)) { // If we have <jsp:attribute> but something other than // <jsp:body> or the end tag, translation error. err.jspError(reader.mark(), "jsp.error.jspbody.required", "&lt;" + tag); } return result; }
// in java/org/apache/jasper/compiler/Parser.java
private void parseJspParams(Node parent) throws JasperException { Node jspParamsNode = new Node.ParamsAction(start, parent); parseOptionalBody(jspParamsNode, "jsp:params", JAVAX_BODY_CONTENT_PARAM); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseFallBack(Node parent) throws JasperException { Node fallBackNode = new Node.FallBackAction(start, parent); parseOptionalBody(fallBackNode, "jsp:fallback", JAVAX_BODY_CONTENT_TEMPLATE_TEXT); }
// in java/org/apache/jasper/compiler/Parser.java
private void parsePlugin(Node parent) throws JasperException { Attributes attrs = parseAttributes(); reader.skipSpaces(); Node pluginNode = new Node.PlugIn(attrs, start, parent); parseOptionalBody(pluginNode, "jsp:plugin", JAVAX_BODY_CONTENT_PLUGIN); }
// in java/org/apache/jasper/compiler/Parser.java
private void parsePluginTags(Node parent) throws JasperException { reader.skipSpaces(); if (reader.matches("<jsp:params")) { parseJspParams(parent); reader.skipSpaces(); } if (reader.matches("<jsp:fallback")) { parseFallBack(parent); reader.skipSpaces(); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseStandardAction(Node parent) throws JasperException { Mark start = reader.mark(); if (reader.matches(INCLUDE_ACTION)) { parseInclude(parent); } else if (reader.matches(FORWARD_ACTION)) { parseForward(parent); } else if (reader.matches(INVOKE_ACTION)) { if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.action.isnottagfile", "&lt;jsp:invoke"); } parseInvoke(parent); } else if (reader.matches(DOBODY_ACTION)) { if (!isTagFile) { err.jspError(reader.mark(), "jsp.error.action.isnottagfile", "&lt;jsp:doBody"); } parseDoBody(parent); } else if (reader.matches(GET_PROPERTY_ACTION)) { parseGetProperty(parent); } else if (reader.matches(SET_PROPERTY_ACTION)) { parseSetProperty(parent); } else if (reader.matches(USE_BEAN_ACTION)) { parseUseBean(parent); } else if (reader.matches(PLUGIN_ACTION)) { parsePlugin(parent); } else if (reader.matches(ELEMENT_ACTION)) { parseElement(parent); } else if (reader.matches(ATTRIBUTE_ACTION)) { err.jspError(start, "jsp.error.namedAttribute.invalidUse"); } else if (reader.matches(BODY_ACTION)) { err.jspError(start, "jsp.error.jspbody.invalidUse"); } else if (reader.matches(FALLBACK_ACTION)) { err.jspError(start, "jsp.error.fallback.invalidUse"); } else if (reader.matches(PARAMS_ACTION)) { err.jspError(start, "jsp.error.params.invalidUse"); } else if (reader.matches(PARAM_ACTION)) { err.jspError(start, "jsp.error.param.invalidUse"); } else if (reader.matches(OUTPUT_ACTION)) { err.jspError(start, "jsp.error.jspoutput.invalidUse"); } else { err.jspError(start, "jsp.error.badStandardAction"); } }
// in java/org/apache/jasper/compiler/Parser.java
private boolean parseCustomTag(Node parent) throws JasperException { if (reader.peekChar() != '<') { return false; } // Parse 'CustomAction' production (tag prefix and custom action name) reader.nextChar(); // skip '<' String tagName = reader.parseToken(false); int i = tagName.indexOf(':'); if (i == -1) { reader.reset(start); return false; } String prefix = tagName.substring(0, i); String shortTagName = tagName.substring(i + 1); // Check if this is a user-defined tag. String uri = pageInfo.getURI(prefix); if (uri == null) { if (pageInfo.isErrorOnUndeclaredNamespace()) { err.jspError(start, "jsp.error.undeclared_namespace", prefix); } else { reader.reset(start); // Remember the prefix for later error checking pageInfo.putNonCustomTagPrefix(prefix, reader.mark()); return false; } } TagLibraryInfo tagLibInfo = pageInfo.getTaglib(uri); TagInfo tagInfo = tagLibInfo.getTag(shortTagName); TagFileInfo tagFileInfo = tagLibInfo.getTagFile(shortTagName); if (tagInfo == null && tagFileInfo == null) { err.jspError(start, "jsp.error.bad_tag", shortTagName, prefix); } Class<?> tagHandlerClass = null; if (tagInfo != null) { // Must be a classic tag, load it here. // tag files will be loaded later, in TagFileProcessor String handlerClassName = tagInfo.getTagClassName(); try { tagHandlerClass = ctxt.getClassLoader().loadClass( handlerClassName); } catch (Exception e) { err.jspError(start, "jsp.error.loadclass.taghandler", handlerClassName, tagName); } } // Parse 'CustomActionBody' production: // At this point we are committed - if anything fails, we produce // a translation error. // Parse 'Attributes' production: Attributes attrs = parseAttributes(); reader.skipSpaces(); // Parse 'CustomActionEnd' production: if (reader.matches("/>")) { if (tagInfo != null) { new Node.CustomTag(tagName, prefix, shortTagName, uri, attrs, start, parent, tagInfo, tagHandlerClass); } else { new Node.CustomTag(tagName, prefix, shortTagName, uri, attrs, start, parent, tagFileInfo); } return true; } // Now we parse one of 'CustomActionTagDependent', // 'CustomActionJSPContent', or 'CustomActionScriptlessContent'. // depending on body-content in TLD. // Looking for a body, it still can be empty; but if there is a // a tag body, its syntax would be dependent on the type of // body content declared in the TLD. String bc; if (tagInfo != null) { bc = tagInfo.getBodyContent(); } else { bc = tagFileInfo.getTagInfo().getBodyContent(); } Node tagNode = null; if (tagInfo != null) { tagNode = new Node.CustomTag(tagName, prefix, shortTagName, uri, attrs, start, parent, tagInfo, tagHandlerClass); } else { tagNode = new Node.CustomTag(tagName, prefix, shortTagName, uri, attrs, start, parent, tagFileInfo); } parseOptionalBody(tagNode, tagName, bc); return true; }
// in java/org/apache/jasper/compiler/Parser.java
private void parseTemplateText(Node parent) throws JasperException { if (!reader.hasMoreInput()) return; CharArrayWriter ttext = new CharArrayWriter(); // Output the first character int ch = reader.nextChar(); if (ch == '\\') { reader.pushChar(); } else { ttext.write(ch); } while (reader.hasMoreInput()) { int prev = ch; ch = reader.nextChar(); if (ch == '<') { reader.pushChar(); break; } else if ((ch == '$' || ch == '#') && !pageInfo.isELIgnored()) { if (!reader.hasMoreInput()) { ttext.write(ch); break; } if (reader.nextChar() == '{') { reader.pushChar(); reader.pushChar(); break; } ttext.write(ch); reader.pushChar(); continue; } else if (ch == '\\') { if (!reader.hasMoreInput()) { ttext.write('\\'); break; } char next = (char) reader.peekChar(); // Looking for \% or \$ or \# if ((prev == '<' && next == '%') || ((next == '$' || next == '#') && !pageInfo.isELIgnored())) { ch = reader.nextChar(); } } ttext.write(ch); } new Node.TemplateText(ttext.toString(), start, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseXMLTemplateText(Node parent) throws JasperException { reader.skipSpaces(); if (!reader.matches("/>")) { if (!reader.matches(">")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:text&gt;"); } CharArrayWriter ttext = new CharArrayWriter(); while (reader.hasMoreInput()) { int ch = reader.nextChar(); if (ch == '<') { // Check for <![CDATA[ if (!reader.matches("![CDATA[")) { break; } start = reader.mark(); Mark stop = reader.skipUntil("]]>"); if (stop == null) { err.jspError(start, "jsp.error.unterminated", "CDATA"); } String text = reader.getText(start, stop); ttext.write(text, 0, text.length()); } else if (ch == '\\') { if (!reader.hasMoreInput()) { ttext.write('\\'); break; } ch = reader.nextChar(); if (ch != '$' && ch != '#') { ttext.write('\\'); } ttext.write(ch); } else if (ch == '$' || ch == '#') { if (!reader.hasMoreInput()) { ttext.write(ch); break; } if (reader.nextChar() != '{') { ttext.write(ch); reader.pushChar(); continue; } // Create a template text node new Node.TemplateText(ttext.toString(), start, parent); // Mark and parse the EL expression and create its node: start = reader.mark(); parseELExpression(parent, (char) ch); start = reader.mark(); ttext = new CharArrayWriter(); } else { ttext.write(ch); } } new Node.TemplateText(ttext.toString(), start, parent); if (!reader.hasMoreInput()) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:text&gt;"); } else if (!reader.matchesETagWithoutLessThan("jsp:text")) { err.jspError(start, "jsp.error.jsptext.badcontent"); } } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseElements(Node parent) throws JasperException { if (scriptlessCount > 0) { // vc: ScriptlessBody // We must follow the ScriptlessBody production if one of // our parents is ScriptlessBody. parseElementsScriptless(parent); return; } start = reader.mark(); if (reader.matches("<%--")) { parseComment(parent); } else if (reader.matches("<%@")) { parseDirective(parent); } else if (reader.matches("<jsp:directive.")) { parseXMLDirective(parent); } else if (reader.matches("<%!")) { parseDeclaration(parent); } else if (reader.matches("<jsp:declaration")) { parseXMLDeclaration(parent); } else if (reader.matches("<%=")) { parseExpression(parent); } else if (reader.matches("<jsp:expression")) { parseXMLExpression(parent); } else if (reader.matches("<%")) { parseScriptlet(parent); } else if (reader.matches("<jsp:scriptlet")) { parseXMLScriptlet(parent); } else if (reader.matches("<jsp:text")) { parseXMLTemplateText(parent); } else if (!pageInfo.isELIgnored() && reader.matches("${")) { parseELExpression(parent, '$'); } else if (!pageInfo.isELIgnored() && !pageInfo.isDeferredSyntaxAllowedAsLiteral() && reader.matches("#{")) { parseELExpression(parent, '#'); } else if (reader.matches("<jsp:")) { parseStandardAction(parent); } else if (!parseCustomTag(parent)) { checkUnbalancedEndTag(); parseTemplateText(parent); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseElementsScriptless(Node parent) throws JasperException { // Keep track of how many scriptless nodes we've encountered // so we know whether our child nodes are forced scriptless scriptlessCount++; start = reader.mark(); if (reader.matches("<%--")) { parseComment(parent); } else if (reader.matches("<%@")) { parseDirective(parent); } else if (reader.matches("<jsp:directive.")) { parseXMLDirective(parent); } else if (reader.matches("<%!")) { err.jspError(reader.mark(), "jsp.error.no.scriptlets"); } else if (reader.matches("<jsp:declaration")) { err.jspError(reader.mark(), "jsp.error.no.scriptlets"); } else if (reader.matches("<%=")) { err.jspError(reader.mark(), "jsp.error.no.scriptlets"); } else if (reader.matches("<jsp:expression")) { err.jspError(reader.mark(), "jsp.error.no.scriptlets"); } else if (reader.matches("<%")) { err.jspError(reader.mark(), "jsp.error.no.scriptlets"); } else if (reader.matches("<jsp:scriptlet")) { err.jspError(reader.mark(), "jsp.error.no.scriptlets"); } else if (reader.matches("<jsp:text")) { parseXMLTemplateText(parent); } else if (!pageInfo.isELIgnored() && reader.matches("${")) { parseELExpression(parent, '$'); } else if (!pageInfo.isELIgnored() && !pageInfo.isDeferredSyntaxAllowedAsLiteral() && reader.matches("#{")) { parseELExpression(parent, '#'); } else if (reader.matches("<jsp:")) { parseStandardAction(parent); } else if (!parseCustomTag(parent)) { checkUnbalancedEndTag(); parseTemplateText(parent); } scriptlessCount--; }
// in java/org/apache/jasper/compiler/Parser.java
private void parseElementsTemplateText(Node parent) throws JasperException { start = reader.mark(); if (reader.matches("<%--")) { parseComment(parent); } else if (reader.matches("<%@")) { parseDirective(parent); } else if (reader.matches("<jsp:directive.")) { parseXMLDirective(parent); } else if (reader.matches("<%!")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Declarations"); } else if (reader.matches("<jsp:declaration")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Declarations"); } else if (reader.matches("<%=")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Expressions"); } else if (reader.matches("<jsp:expression")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Expressions"); } else if (reader.matches("<%")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Scriptlets"); } else if (reader.matches("<jsp:scriptlet")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Scriptlets"); } else if (reader.matches("<jsp:text")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "&lt;jsp:text"); } else if (!pageInfo.isELIgnored() && reader.matches("${")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Expression language"); } else if (!pageInfo.isELIgnored() && !pageInfo.isDeferredSyntaxAllowedAsLiteral() && reader.matches("#{")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Expression language"); } else if (reader.matches("<jsp:")) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Standard actions"); } else if (parseCustomTag(parent)) { err.jspError(reader.mark(), "jsp.error.not.in.template", "Custom actions"); } else { checkUnbalancedEndTag(); parseTemplateText(parent); } }
// in java/org/apache/jasper/compiler/Parser.java
private void checkUnbalancedEndTag() throws JasperException { if (!reader.matches("</")) { return; } // Check for unbalanced standard actions if (reader.matches("jsp:")) { err.jspError(start, "jsp.error.unbalanced.endtag", "jsp:"); } // Check for unbalanced custom actions String tagName = reader.parseToken(false); int i = tagName.indexOf(':'); if (i == -1 || pageInfo.getURI(tagName.substring(0, i)) == null) { reader.reset(start); return; } err.jspError(start, "jsp.error.unbalanced.endtag", tagName); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseTagDependentBody(Node parent, String tag) throws JasperException { Mark bodyStart = reader.mark(); Mark bodyEnd = reader.skipUntilETag(tag); if (bodyEnd == null) { err.jspError(start, "jsp.error.unterminated", "&lt;" + tag); } new Node.TemplateText(reader.getText(bodyStart, bodyEnd), bodyStart, parent); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseJspBody(Node parent, String bodyType) throws JasperException { Mark start = reader.mark(); Node bodyNode = new Node.JspBody(start, parent); reader.skipSpaces(); if (!reader.matches("/>")) { if (!reader.matches(">")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:body"); } parseBody(bodyNode, "jsp:body", bodyType); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseBody(Node parent, String tag, String bodyType) throws JasperException { if (bodyType.equalsIgnoreCase(TagInfo.BODY_CONTENT_TAG_DEPENDENT)) { parseTagDependentBody(parent, tag); } else if (bodyType.equalsIgnoreCase(TagInfo.BODY_CONTENT_EMPTY)) { if (!reader.matchesETag(tag)) { err.jspError(start, "jasper.error.emptybodycontent.nonempty", tag); } } else if (bodyType == JAVAX_BODY_CONTENT_PLUGIN) { // (note the == since we won't recognize JAVAX_* // from outside this module). parsePluginTags(parent); if (!reader.matchesETag(tag)) { err.jspError(reader.mark(), "jsp.error.unterminated", "&lt;" + tag); } } else if (bodyType.equalsIgnoreCase(TagInfo.BODY_CONTENT_JSP) || bodyType.equalsIgnoreCase(TagInfo.BODY_CONTENT_SCRIPTLESS) || (bodyType == JAVAX_BODY_CONTENT_PARAM) || (bodyType == JAVAX_BODY_CONTENT_TEMPLATE_TEXT)) { while (reader.hasMoreInput()) { if (reader.matchesETag(tag)) { return; } // Check for nested jsp:body or jsp:attribute if (tag.equals("jsp:body") || tag.equals("jsp:attribute")) { if (reader.matches("<jsp:attribute")) { err.jspError(reader.mark(), "jsp.error.nested.jspattribute"); } else if (reader.matches("<jsp:body")) { err.jspError(reader.mark(), "jsp.error.nested.jspbody"); } } if (bodyType.equalsIgnoreCase(TagInfo.BODY_CONTENT_JSP)) { parseElements(parent); } else if (bodyType .equalsIgnoreCase(TagInfo.BODY_CONTENT_SCRIPTLESS)) { parseElementsScriptless(parent); } else if (bodyType == JAVAX_BODY_CONTENT_PARAM) { // (note the == since we won't recognize JAVAX_* // from outside this module). reader.skipSpaces(); parseParam(parent); } else if (bodyType == JAVAX_BODY_CONTENT_TEMPLATE_TEXT) { parseElementsTemplateText(parent); } } err.jspError(start, "jsp.error.unterminated", "&lt;" + tag); } else { err.jspError(start, "jasper.error.bad.bodycontent.type"); } }
// in java/org/apache/jasper/compiler/Parser.java
private void parseNamedAttributes(Node parent) throws JasperException { do { Mark start = reader.mark(); Attributes attrs = parseAttributes(); Node.NamedAttribute namedAttributeNode = new Node.NamedAttribute( attrs, start, parent); reader.skipSpaces(); if (!reader.matches("/>")) { if (!reader.matches(">")) { err.jspError(start, "jsp.error.unterminated", "&lt;jsp:attribute"); } if (namedAttributeNode.isTrim()) { reader.skipSpaces(); } parseBody(namedAttributeNode, "jsp:attribute", getAttributeBodyType(parent, attrs.getValue("name"))); if (namedAttributeNode.isTrim()) { Node.Nodes subElems = namedAttributeNode.getBody(); if (subElems != null) { Node lastNode = subElems.getNode(subElems.size() - 1); if (lastNode instanceof Node.TemplateText) { ((Node.TemplateText) lastNode).rtrim(); } } } } reader.skipSpaces(); } while (reader.matches("<jsp:attribute")); }
// in java/org/apache/jasper/compiler/Parser.java
private void parseFileDirectives(Node parent) throws JasperException { reader.setSingleFile(true); reader.skipUntil("<"); while (reader.hasMoreInput()) { start = reader.mark(); if (reader.matches("%--")) { // Comment reader.skipUntil("--%>"); } else if (reader.matches("%@")) { parseDirective(parent); } else if (reader.matches("jsp:directive.")) { parseXMLDirective(parent); } else if (reader.matches("%!")) { // Declaration reader.skipUntil("%>"); } else if (reader.matches("%=")) { // Expression reader.skipUntil("%>"); } else if (reader.matches("%")) { // Scriptlet reader.skipUntil("%>"); } reader.skipUntil("<"); } }
// in java/org/apache/jasper/compiler/BeanRepository.java
public void addBean(Node.UseBean n, String s, String type, String scope) throws JasperException { if (!(scope == null || scope.equals("page") || scope.equals("request") || scope.equals("session") || scope.equals("application"))) { errDispatcher.jspError(n, "jsp.error.usebean.badScope"); } beanTypes.put(s, type); }
// in java/org/apache/jasper/compiler/BeanRepository.java
public Class<?> getBeanType(String bean) throws JasperException { Class<?> clazz = null; try { clazz = loader.loadClass(beanTypes.get(bean)); } catch (ClassNotFoundException ex) { throw new JasperException (ex); } return clazz; }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
Override public void visit(Node.TagDirective n) throws JasperException { JspUtil.checkAttributes("Tag directive", n, tagDirectiveAttrs, err); bodycontent = checkConflict(n, bodycontent, "body-content"); if (bodycontent != null && !bodycontent .equalsIgnoreCase(TagInfo.BODY_CONTENT_EMPTY) && !bodycontent .equalsIgnoreCase(TagInfo.BODY_CONTENT_TAG_DEPENDENT) && !bodycontent .equalsIgnoreCase(TagInfo.BODY_CONTENT_SCRIPTLESS)) { err.jspError(n, "jsp.error.tagdirective.badbodycontent", bodycontent); } dynamicAttrsMapName = checkConflict(n, dynamicAttrsMapName, "dynamic-attributes"); if (dynamicAttrsMapName != null) { checkUniqueName(dynamicAttrsMapName, TAG_DYNAMIC, n); } smallIcon = checkConflict(n, smallIcon, "small-icon"); largeIcon = checkConflict(n, largeIcon, "large-icon"); description = checkConflict(n, description, "description"); displayName = checkConflict(n, displayName, "display-name"); example = checkConflict(n, example, "example"); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
private String checkConflict(Node n, String oldAttrValue, String attr) throws JasperException { String result = oldAttrValue; String attrValue = n.getAttributeValue(attr); if (attrValue != null) { if (oldAttrValue != null && !oldAttrValue.equals(attrValue)) { err.jspError(n, "jsp.error.tag.conflict.attr", attr, oldAttrValue, attrValue); } result = attrValue; } return result; }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
Override public void visit(Node.AttributeDirective n) throws JasperException { JspUtil.checkAttributes("Attribute directive", n, attributeDirectiveAttrs, err); // JSP 2.1 Table JSP.8-3 // handle deferredValue and deferredValueType boolean deferredValue = false; boolean deferredValueSpecified = false; String deferredValueString = n.getAttributeValue("deferredValue"); if (deferredValueString != null) { deferredValueSpecified = true; deferredValue = JspUtil.booleanValue(deferredValueString); } String deferredValueType = n.getAttributeValue("deferredValueType"); if (deferredValueType != null) { if (deferredValueSpecified && !deferredValue) { err.jspError(n, "jsp.error.deferredvaluetypewithoutdeferredvalue"); } else { deferredValue = true; } } else if (deferredValue) { deferredValueType = "java.lang.Object"; } else { deferredValueType = "java.lang.String"; } // JSP 2.1 Table JSP.8-3 // handle deferredMethod and deferredMethodSignature boolean deferredMethod = false; boolean deferredMethodSpecified = false; String deferredMethodString = n.getAttributeValue("deferredMethod"); if (deferredMethodString != null) { deferredMethodSpecified = true; deferredMethod = JspUtil.booleanValue(deferredMethodString); } String deferredMethodSignature = n .getAttributeValue("deferredMethodSignature"); if (deferredMethodSignature != null) { if (deferredMethodSpecified && !deferredMethod) { err.jspError(n, "jsp.error.deferredmethodsignaturewithoutdeferredmethod"); } else { deferredMethod = true; } } else if (deferredMethod) { deferredMethodSignature = "void methodname()"; } if (deferredMethod && deferredValue) { err.jspError(n, "jsp.error.deferredmethodandvalue"); } String attrName = n.getAttributeValue("name"); boolean required = JspUtil.booleanValue(n .getAttributeValue("required")); boolean rtexprvalue = true; String rtexprvalueString = n.getAttributeValue("rtexprvalue"); if (rtexprvalueString != null) { rtexprvalue = JspUtil.booleanValue(rtexprvalueString); } boolean fragment = JspUtil.booleanValue(n .getAttributeValue("fragment")); String type = n.getAttributeValue("type"); if (fragment) { // type is fixed to "JspFragment" and a translation error // must occur if specified. if (type != null) { err.jspError(n, "jsp.error.fragmentwithtype"); } // rtexprvalue is fixed to "true" and a translation error // must occur if specified. rtexprvalue = true; if (rtexprvalueString != null) { err.jspError(n, "jsp.error.frgmentwithrtexprvalue"); } } else { if (type == null) type = "java.lang.String"; if (deferredValue) { type = ValueExpression.class.getName(); } else if (deferredMethod) { type = MethodExpression.class.getName(); } } if (("2.0".equals(tagLibInfo.getRequiredVersion()) || ("1.2".equals(tagLibInfo.getRequiredVersion()))) && (deferredMethodSpecified || deferredMethod || deferredValueSpecified || deferredValue)) { err.jspError("jsp.error.invalid.version", path); } TagAttributeInfo tagAttributeInfo = new TagAttributeInfo(attrName, required, type, rtexprvalue, fragment, null, deferredValue, deferredMethod, deferredValueType, deferredMethodSignature); attributeVector.addElement(tagAttributeInfo); checkUniqueName(attrName, ATTR_NAME, n, tagAttributeInfo); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
Override public void visit(Node.VariableDirective n) throws JasperException { JspUtil.checkAttributes("Variable directive", n, variableDirectiveAttrs, err); String nameGiven = n.getAttributeValue("name-given"); String nameFromAttribute = n .getAttributeValue("name-from-attribute"); if (nameGiven == null && nameFromAttribute == null) { err.jspError("jsp.error.variable.either.name"); } if (nameGiven != null && nameFromAttribute != null) { err.jspError("jsp.error.variable.both.name"); } String alias = n.getAttributeValue("alias"); if (nameFromAttribute != null && alias == null || nameFromAttribute == null && alias != null) { err.jspError("jsp.error.variable.alias"); } String className = n.getAttributeValue("variable-class"); if (className == null) className = "java.lang.String"; String declareStr = n.getAttributeValue("declare"); boolean declare = true; if (declareStr != null) declare = JspUtil.booleanValue(declareStr); int scope = VariableInfo.NESTED; String scopeStr = n.getAttributeValue("scope"); if (scopeStr != null) { if ("NESTED".equals(scopeStr)) { // Already the default } else if ("AT_BEGIN".equals(scopeStr)) { scope = VariableInfo.AT_BEGIN; } else if ("AT_END".equals(scopeStr)) { scope = VariableInfo.AT_END; } } if (nameFromAttribute != null) { /* * An alias has been specified. We use 'nameGiven' to hold the * value of the alias, and 'nameFromAttribute' to hold the name * of the attribute whose value (at invocation-time) denotes the * name of the variable that is being aliased */ nameGiven = alias; checkUniqueName(nameFromAttribute, VAR_NAME_FROM, n); checkUniqueName(alias, VAR_ALIAS, n); } else { // name-given specified checkUniqueName(nameGiven, VAR_NAME_GIVEN, n); } variableVector.addElement(new TagVariableInfo(nameGiven, nameFromAttribute, className, declare, scope)); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
public TagInfo getTagInfo() throws JasperException { if (name == null) { // XXX Get it from tag file name } if (bodycontent == null) { bodycontent = TagInfo.BODY_CONTENT_SCRIPTLESS; } String tagClassName = JspUtil.getTagHandlerClassName( path, tagLibInfo.getReliableURN(), err); TagVariableInfo[] tagVariableInfos = new TagVariableInfo[variableVector .size()]; variableVector.copyInto(tagVariableInfos); TagAttributeInfo[] tagAttributeInfo = new TagAttributeInfo[attributeVector .size()]; attributeVector.copyInto(tagAttributeInfo); return new JasperTagInfo(name, tagClassName, bodycontent, description, tagLibInfo, tei, tagAttributeInfo, displayName, smallIcon, largeIcon, tagVariableInfos, dynamicAttrsMapName); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
private void checkUniqueName(String name, String type, Node n) throws JasperException { checkUniqueName(name, type, n, null); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
private void checkUniqueName(String name, String type, Node n, TagAttributeInfo attr) throws JasperException { HashMap<String, NameEntry> table = (type == VAR_NAME_FROM) ? nameFromTable : nameTable; NameEntry nameEntry = table.get(name); if (nameEntry != null) { if (!TAG_DYNAMIC.equals(type) || !TAG_DYNAMIC.equals(nameEntry.getType())) { int line = nameEntry.getNode().getStart().getLineNumber(); err.jspError(n, "jsp.error.tagfile.nameNotUnique", type, nameEntry.getType(), Integer.toString(line)); } } else { table.put(name, new NameEntry(type, n, attr)); } }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
void postCheck() throws JasperException { // Check that var.name-from-attributes has valid values. Iterator<String> iter = nameFromTable.keySet().iterator(); while (iter.hasNext()) { String nameFrom = iter.next(); NameEntry nameEntry = nameTable.get(nameFrom); NameEntry nameFromEntry = nameFromTable.get(nameFrom); Node nameFromNode = nameFromEntry.getNode(); if (nameEntry == null) { err.jspError(nameFromNode, "jsp.error.tagfile.nameFrom.noAttribute", nameFrom); } else { Node node = nameEntry.getNode(); TagAttributeInfo tagAttr = nameEntry.getTagAttributeInfo(); if (!"java.lang.String".equals(tagAttr.getTypeName()) || !tagAttr.isRequired() || tagAttr.canBeRequestTime()) { err.jspError(nameFromNode, "jsp.error.tagfile.nameFrom.badAttribute", nameFrom, Integer.toString(node.getStart() .getLineNumber())); } } } }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
public static TagInfo parseTagFileDirectives(ParserController pc, String name, String path, JarResource jarResource, TagLibraryInfo tagLibInfo) throws JasperException { ErrorDispatcher err = pc.getCompiler().getErrorDispatcher(); Node.Nodes page = null; try { page = pc.parseTagFileDirectives(path, jarResource); } catch (FileNotFoundException e) { err.jspError("jsp.error.file.not.found", path); } catch (IOException e) { err.jspError("jsp.error.file.not.found", path); } TagFileDirectiveVisitor tagFileVisitor = new TagFileDirectiveVisitor(pc .getCompiler(), tagLibInfo, name, path); page.visit(tagFileVisitor); tagFileVisitor.postCheck(); return tagFileVisitor.getTagInfo(); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
private Class<?> loadTagFile(Compiler compiler, String tagFilePath, TagInfo tagInfo, PageInfo parentPageInfo) throws JasperException { JarResource tagJarResouce = null; if (tagFilePath.startsWith("/META-INF/")) { tagJarResouce = compiler.getCompilationContext().getTldLocation( tagInfo.getTagLibrary().getURI()).getJarResource(); } String wrapperUri; if (tagJarResouce == null) { wrapperUri = tagFilePath; } else { wrapperUri = tagJarResouce.getEntry(tagFilePath).toString(); } JspCompilationContext ctxt = compiler.getCompilationContext(); JspRuntimeContext rctxt = ctxt.getRuntimeContext(); JspServletWrapper wrapper = rctxt.getWrapper(wrapperUri); synchronized (rctxt) { if (wrapper == null) { wrapper = new JspServletWrapper(ctxt.getServletContext(), ctxt .getOptions(), tagFilePath, tagInfo, ctxt .getRuntimeContext(), tagJarResouce); rctxt.addWrapper(wrapperUri, wrapper); // Use same classloader and classpath for compiling tag files wrapper.getJspEngineContext().setClassLoader( ctxt.getClassLoader()); wrapper.getJspEngineContext().setClassPath(ctxt.getClassPath()); } else { // Make sure that JspCompilationContext gets the latest TagInfo // for the tag file. TagInfo instance was created the last // time the tag file was scanned for directives, and the tag // file may have been modified since then. wrapper.getJspEngineContext().setTagInfo(tagInfo); } Class<?> tagClazz; int tripCount = wrapper.incTripCount(); try { if (tripCount > 0) { // When tripCount is greater than zero, a circular // dependency exists. The circularly dependent tag // file is compiled in prototype mode, to avoid infinite // recursion. JspServletWrapper tempWrapper = new JspServletWrapper(ctxt .getServletContext(), ctxt.getOptions(), tagFilePath, tagInfo, ctxt.getRuntimeContext(), ctxt.getTagFileJarResource(tagFilePath)); // Use same classloader and classpath for compiling tag files tempWrapper.getJspEngineContext().setClassLoader( ctxt.getClassLoader()); tempWrapper.getJspEngineContext().setClassPath(ctxt.getClassPath()); tagClazz = tempWrapper.loadTagFilePrototype(); tempVector.add(tempWrapper.getJspEngineContext() .getCompiler()); } else { tagClazz = wrapper.loadTagFile(); } } finally { wrapper.decTripCount(); } // Add the dependents for this tag file to its parent's // Dependent list. The only reliable dependency information // can only be obtained from the tag instance. try { Object tagIns = tagClazz.newInstance(); if (tagIns instanceof JspSourceDependent) { Iterator<Entry<String,Long>> iter = ((JspSourceDependent) tagIns).getDependants().entrySet().iterator(); while (iter.hasNext()) { Entry<String,Long> entry = iter.next(); parentPageInfo.addDependant(entry.getKey(), entry.getValue()); } } } catch (Exception e) { // ignore errors } return tagClazz; } }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
Override public void visit(Node.CustomTag n) throws JasperException { TagFileInfo tagFileInfo = n.getTagFileInfo(); if (tagFileInfo != null) { String tagFilePath = tagFileInfo.getPath(); if (tagFilePath.startsWith("/META-INF/")) { // For tags in JARs, add the TLD and the tag as a dependency TldLocation location = compiler.getCompilationContext().getTldLocation( tagFileInfo.getTagInfo().getTagLibrary().getURI()); JarResource jarResource = location.getJarResource(); if (jarResource != null) { try { // Add TLD pageInfo.addDependant(jarResource.getEntry(location.getName()).toString(), Long.valueOf(jarResource.getJarFile().getEntry(location.getName()).getTime())); // Add Tag pageInfo.addDependant(jarResource.getEntry(tagFilePath.substring(1)).toString(), Long.valueOf(jarResource.getJarFile().getEntry(tagFilePath.substring(1)).getTime())); } catch (IOException ioe) { throw new JasperException(ioe); } } else { pageInfo.addDependant(tagFilePath, compiler.getCompilationContext().getLastModified( tagFilePath)); } } else { pageInfo.addDependant(tagFilePath, compiler.getCompilationContext().getLastModified( tagFilePath)); } Class<?> c = loadTagFile(compiler, tagFilePath, n.getTagInfo(), pageInfo); n.setTagHandlerClass(c); } visitBody(n); }
// in java/org/apache/jasper/compiler/TagFileProcessor.java
public void loadTagFiles(Compiler compiler, Node.Nodes page) throws JasperException { tempVector = new Vector<Compiler>(); page.visit(new TagFileLoaderVisitor(compiler)); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
public TldLocation getLocation(String uri) throws JasperException { if (!initialized) { init(); } return mappings.get(uri); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
private synchronized void init() throws JasperException { if (initialized) return; try { tldScanWebXml(); tldScanResourcePaths(WEB_INF); JarScanner jarScanner = JarScannerFactory.getJarScanner(ctxt); if (jarScanner != null) { jarScanner.scan(ctxt, Thread.currentThread().getContextClassLoader(), new TldJarScannerCallback(), noTldJars); } initialized = true; } catch (Exception ex) { throw new JasperException(Localizer.getMessage( "jsp.error.internal.tldinit", ex.getMessage()), ex); } }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
public static void map(Node.Nodes page) throws JasperException { ELFunctionMapper map = new ELFunctionMapper(); map.ds = new StringBuilder(); map.ss = new StringBuilder(); page.visit(map.new ELFunctionVisitor()); // Append the declarations to the root node String ds = map.ds.toString(); if (ds.length() > 0) { Node root = page.getRoot(); new Node.Declaration(map.ss.toString(), null, root); new Node.Declaration("static {\n" + ds + "}\n", null, root); } }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.ParamAction n) throws JasperException { doMap(n.getValue()); visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.IncludeAction n) throws JasperException { doMap(n.getPage()); visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.ForwardAction n) throws JasperException { doMap(n.getPage()); visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.SetProperty n) throws JasperException { doMap(n.getValue()); visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.UseBean n) throws JasperException { doMap(n.getBeanName()); visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.PlugIn n) throws JasperException { doMap(n.getHeight()); doMap(n.getWidth()); visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.JspElement n) throws JasperException { Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { doMap(attrs[i]); } doMap(n.getNameAttribute()); visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.UninterpretedTag n) throws JasperException { Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { doMap(attrs[i]); } visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.CustomTag n) throws JasperException { Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { doMap(attrs[i]); } visitBody(n); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(Node.ELExpression n) throws JasperException { doMap(n.getEL()); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
private void doMap(Node.JspAttribute attr) throws JasperException { if (attr != null) { doMap(attr.getEL()); } }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
private void doMap(ELNode.Nodes el) throws JasperException { // Only care about functions in ELNode's class Fvisitor extends ELNode.Visitor { ArrayList<ELNode.Function> funcs = new ArrayList<ELNode.Function>(); HashMap<String, String> keyMap = new HashMap<String, String>(); @Override public void visit(ELNode.Function n) throws JasperException { String key = n.getPrefix() + ":" + n.getName(); if (! keyMap.containsKey(key)) { keyMap.put(key,""); funcs.add(n); } } } if (el == null) { return; } // First locate all unique functions in this EL Fvisitor fv = new Fvisitor(); el.visit(fv); ArrayList<ELNode.Function> functions = fv.funcs; if (functions.size() == 0) { return; } // Reuse a previous map if possible String decName = matchMap(functions); if (decName != null) { el.setMapName(decName); return; } // Generate declaration for the map statically decName = getMapName(); ss.append("private static org.apache.jasper.runtime.ProtectedFunctionMapper " + decName + ";\n"); ds.append(" " + decName + "= "); ds.append("org.apache.jasper.runtime.ProtectedFunctionMapper"); // Special case if there is only one function in the map String funcMethod = null; if (functions.size() == 1) { funcMethod = ".getMapForFunction"; } else { ds.append(".getInstance();\n"); funcMethod = " " + decName + ".mapFunction"; } // Setup arguments for either getMapForFunction or mapFunction for (int i = 0; i < functions.size(); i++) { ELNode.Function f = functions.get(i); FunctionInfo funcInfo = f.getFunctionInfo(); String key = f.getPrefix()+ ":" + f.getName(); ds.append(funcMethod + "(\"" + key + "\", " + getCanonicalName(funcInfo.getFunctionClass()) + ".class, " + '\"' + f.getMethodName() + "\", " + "new Class[] {"); String params[] = f.getParameters(); for (int k = 0; k < params.length; k++) { if (k != 0) { ds.append(", "); } int iArray = params[k].indexOf('['); if (iArray < 0) { ds.append(params[k] + ".class"); } else { String baseType = params[k].substring(0, iArray); ds.append("java.lang.reflect.Array.newInstance("); ds.append(baseType); ds.append(".class,"); // Count the number of array dimension int aCount = 0; for (int jj = iArray; jj < params[k].length(); jj++ ) { if (params[k].charAt(jj) == '[') { aCount++; } } if (aCount == 1) { ds.append("0).getClass()"); } else { ds.append("new int[" + aCount + "]).getClass()"); } } } ds.append("});\n"); // Put the current name in the global function map gMap.put(f.getPrefix() + ':' + f.getName() + ':' + f.getUri(), decName); } el.setMapName(decName); }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
Override public void visit(ELNode.Function n) throws JasperException { String key = n.getPrefix() + ":" + n.getName(); if (! keyMap.containsKey(key)) { keyMap.put(key,""); funcs.add(n); } }
// in java/org/apache/jasper/compiler/ELFunctionMapper.java
private String getCanonicalName(String className) throws JasperException { Class<?> clazz; ClassLoader tccl; if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<ClassLoader> pa = new PrivilegedGetTccl(); tccl = AccessController.doPrivileged(pa); } else { tccl = Thread.currentThread().getContextClassLoader(); } try { clazz = Class.forName(className, false, tccl); } catch (ClassNotFoundException e) { throw new JasperException(e); } return clazz.getCanonicalName(); }
// in java/org/apache/jasper/compiler/JDTCompiler.java
Override protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception { long t1 = 0; if (log.isDebugEnabled()) { t1 = System.currentTimeMillis(); } final String sourceFile = ctxt.getServletJavaFileName(); final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath(); String packageName = ctxt.getServletPackageName(); final String targetClassName = ((packageName.length() != 0) ? (packageName + ".") : "") + ctxt.getServletClassName(); final ClassLoader classLoader = ctxt.getJspLoader(); String[] fileNames = new String[] {sourceFile}; String[] classNames = new String[] {targetClassName}; final ArrayList<JavacErrorDetail> problemList = new ArrayList<JavacErrorDetail>(); class CompilationUnit implements ICompilationUnit { private final String className; private final String sourceFile; CompilationUnit(String sourceFile, String className) { this.className = className; this.sourceFile = sourceFile; } @Override public char[] getFileName() { return sourceFile.toCharArray(); } @Override public char[] getContents() { char[] result = null; FileInputStream is = null; InputStreamReader isr = null; Reader reader = null; try { is = new FileInputStream(sourceFile); isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding()); reader = new BufferedReader(isr); char[] chars = new char[8192]; StringBuilder buf = new StringBuilder(); int count; while ((count = reader.read(chars, 0, chars.length)) > 0) { buf.append(chars, 0, count); } result = new char[buf.length()]; buf.getChars(0, result.length, result, 0); } catch (IOException e) { log.error("Compilation error", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) {/*Ignore*/} } if (isr != null) { try { isr.close(); } catch (IOException ioe) {/*Ignore*/} } if (is != null) { try { is.close(); } catch (IOException exc) {/*Ignore*/} } } return result; } @Override public char[] getMainTypeName() { int dot = className.lastIndexOf('.'); if (dot > 0) { return className.substring(dot + 1).toCharArray(); } return className.toCharArray(); } @Override public char[][] getPackageName() { StringTokenizer izer = new StringTokenizer(className, "."); char[][] result = new char[izer.countTokens()-1][]; for (int i = 0; i < result.length; i++) { String tok = izer.nextToken(); result[i] = tok.toCharArray(); } return result; } @SuppressWarnings("unused") // New method added to interface in // later JDT versions public boolean ignoreOptionalProblems() { return false; } }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void doVisit(Node n) throws JasperException { collectText(); }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void visit(Node.PageDirective n) throws JasperException { }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void visit(Node.TagDirective n) throws JasperException { }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void visit(Node.TaglibDirective n) throws JasperException { }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void visit(Node.AttributeDirective n) throws JasperException { }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void visit(Node.VariableDirective n) throws JasperException { }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void visitBody(Node n) throws JasperException { super.visitBody(n); collectText(); }
// in java/org/apache/jasper/compiler/TextOptimizer.java
Override public void visit(Node.TemplateText n) throws JasperException { if ((options.getTrimSpaces() || pageInfo.isTrimDirectiveWhitespaces()) && n.isAllSpace()) { n.setText(EMPTY_TEXT); return; } if (textNodeCount++ == 0) { firstTextNode = n; textBuffer = new StringBuilder(n.getText()); } else { // Append text to text buffer textBuffer.append(n.getText()); n.setText(EMPTY_TEXT); } }
// in java/org/apache/jasper/compiler/TextOptimizer.java
public static void concatenate(Compiler compiler, Node.Nodes page) throws JasperException { TextCatVisitor v = new TextCatVisitor(compiler); page.visit(v); // Cleanup, in case the page ends with a template text v.collectText(); }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setLanguage(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if (!"java".equalsIgnoreCase(value)) { if (pagedir) err.jspError(n, "jsp.error.page.language.nonjava"); else err.jspError(n, "jsp.error.tag.language.nonjava"); } language = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setBufferValue(String value, Node n, ErrorDispatcher err) throws JasperException { if ("none".equalsIgnoreCase(value)) buffer = 0; else { if (value == null || !value.endsWith("kb")) { if (n == null) { err.jspError("jsp.error.page.invalid.buffer"); } else { err.jspError(n, "jsp.error.page.invalid.buffer"); } } try { Integer k = new Integer(value.substring(0, value.length()-2)); buffer = k.intValue() * 1024; } catch (NumberFormatException e) { if (n == null) { err.jspError("jsp.error.page.invalid.buffer"); } else { err.jspError(n, "jsp.error.page.invalid.buffer"); } } } bufferValue = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setSession(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) isSession = true; else if ("false".equalsIgnoreCase(value)) isSession = false; else err.jspError(n, "jsp.error.page.invalid.session"); session = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setAutoFlush(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) isAutoFlush = true; else if ("false".equalsIgnoreCase(value)) isAutoFlush = false; else err.jspError(n, "jsp.error.autoFlush.invalid"); autoFlush = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setIsThreadSafe(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) isThreadSafe = true; else if ("false".equalsIgnoreCase(value)) isThreadSafe = false; else err.jspError(n, "jsp.error.page.invalid.isthreadsafe"); isThreadSafeValue = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setIsErrorPage(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) isErrorPage = true; else if ("false".equalsIgnoreCase(value)) isErrorPage = false; else err.jspError(n, "jsp.error.page.invalid.iserrorpage"); isErrorPageValue = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setIsELIgnored(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) isELIgnored = true; else if ("false".equalsIgnoreCase(value)) isELIgnored = false; else { if (pagedir) err.jspError(n, "jsp.error.page.invalid.iselignored"); else err.jspError(n, "jsp.error.tag.invalid.iselignored"); } isELIgnoredValue = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setDeferredSyntaxAllowedAsLiteral(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) deferredSyntaxAllowedAsLiteral = true; else if ("false".equalsIgnoreCase(value)) deferredSyntaxAllowedAsLiteral = false; else { if (pagedir) err.jspError(n, "jsp.error.page.invalid.deferredsyntaxallowedasliteral"); else err.jspError(n, "jsp.error.tag.invalid.deferredsyntaxallowedasliteral"); } deferredSyntaxAllowedAsLiteralValue = value; }
// in java/org/apache/jasper/compiler/PageInfo.java
public void setTrimDirectiveWhitespaces(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) trimDirectiveWhitespaces = true; else if ("false".equalsIgnoreCase(value)) trimDirectiveWhitespaces = false; else { if (pagedir) err.jspError(n, "jsp.error.page.invalid.trimdirectivewhitespaces"); else err.jspError(n, "jsp.error.tag.invalid.trimdirectivewhitespaces"); } trimDirectiveWhitespacesValue = value; }
// in java/org/apache/jasper/compiler/JspReader.java
boolean hasMoreInput() throws JasperException { if (current.cursor >= current.stream.length) { if (singleFile) return false; while (popFile()) { if (current.cursor < current.stream.length) return true; } return false; } return true; }
// in java/org/apache/jasper/compiler/JspReader.java
int nextChar() throws JasperException { if (!hasMoreInput()) return -1; int ch = current.stream[current.cursor]; current.cursor++; if (ch == '\n') { current.line++; current.col = 0; } else { current.col++; } return ch; }
// in java/org/apache/jasper/compiler/JspReader.java
String getText(Mark start, Mark stop) throws JasperException { Mark oldstart = mark(); reset(start); CharArrayWriter caw = new CharArrayWriter(); while (!stop.equals(mark())) caw.write(nextChar()); caw.close(); reset(oldstart); return caw.toString(); }
// in java/org/apache/jasper/compiler/JspReader.java
int peekChar() throws JasperException { if (!hasMoreInput()) return -1; return current.stream[current.cursor]; }
// in java/org/apache/jasper/compiler/JspReader.java
boolean matches(String string) throws JasperException { Mark mark = mark(); int ch = 0; int i = 0; do { ch = nextChar(); if (((char) ch) != string.charAt(i++)) { reset(mark); return false; } } while (i < string.length()); return true; }
// in java/org/apache/jasper/compiler/JspReader.java
boolean matchesETag(String tagName) throws JasperException { Mark mark = mark(); if (!matches("</" + tagName)) return false; skipSpaces(); if (nextChar() == '>') return true; reset(mark); return false; }
// in java/org/apache/jasper/compiler/JspReader.java
boolean matchesETagWithoutLessThan(String tagName) throws JasperException { Mark mark = mark(); if (!matches("/" + tagName)) return false; skipSpaces(); if (nextChar() == '>') return true; reset(mark); return false; }
// in java/org/apache/jasper/compiler/JspReader.java
boolean matchesOptionalSpacesFollowedBy( String s ) throws JasperException { Mark mark = mark(); skipSpaces(); boolean result = matches( s ); if( !result ) { reset( mark ); } return result; }
// in java/org/apache/jasper/compiler/JspReader.java
int skipSpaces() throws JasperException { int i = 0; while (hasMoreInput() && isSpace()) { i++; nextChar(); } return i; }
// in java/org/apache/jasper/compiler/JspReader.java
Mark skipUntil(String limit) throws JasperException { Mark ret = null; int limlen = limit.length(); int ch; skip: for (ret = mark(), ch = nextChar() ; ch != -1 ; ret = mark(), ch = nextChar()) { if (ch == limit.charAt(0)) { Mark restart = mark(); for (int i = 1 ; i < limlen ; i++) { if (peekChar() == limit.charAt(i)) nextChar(); else { reset(restart); continue skip; } } return ret; } } return null; }
// in java/org/apache/jasper/compiler/JspReader.java
Mark skipUntilIgnoreEsc(String limit) throws JasperException { Mark ret = null; int limlen = limit.length(); int ch; int prev = 'x'; // Doesn't matter skip: for (ret = mark(), ch = nextChar() ; ch != -1 ; ret = mark(), prev = ch, ch = nextChar()) { if (ch == '\\' && prev == '\\') { ch = 0; // Double \ is not an escape char anymore } else if (ch == limit.charAt(0) && prev != '\\') { for (int i = 1 ; i < limlen ; i++) { if (peekChar() == limit.charAt(i)) nextChar(); else continue skip; } return ret; } } return null; }
// in java/org/apache/jasper/compiler/JspReader.java
Mark skipUntilETag(String tag) throws JasperException { Mark ret = skipUntil("</" + tag); if (ret != null) { skipSpaces(); if (nextChar() != '>') ret = null; } return ret; }
// in java/org/apache/jasper/compiler/JspReader.java
final boolean isSpace() throws JasperException { // Note: If this logic changes, also update Node.TemplateText.rtrim() return peekChar() <= ' '; }
// in java/org/apache/jasper/compiler/JspReader.java
String parseToken(boolean quoted) throws JasperException { StringBuilder StringBuilder = new StringBuilder(); skipSpaces(); StringBuilder.setLength(0); if (!hasMoreInput()) { return ""; } int ch = peekChar(); if (quoted) { if (ch == '"' || ch == '\'') { char endQuote = ch == '"' ? '"' : '\''; // Consume the open quote: ch = nextChar(); for (ch = nextChar(); ch != -1 && ch != endQuote; ch = nextChar()) { if (ch == '\\') ch = nextChar(); StringBuilder.append((char) ch); } // Check end of quote, skip closing quote: if (ch == -1) { err.jspError(mark(), "jsp.error.quotes.unterminated"); } } else { err.jspError(mark(), "jsp.error.attr.quoted"); } } else { if (!isDelimiter()) { // Read value until delimiter is found: do { ch = nextChar(); // Take care of the quoting here. if (ch == '\\') { if (peekChar() == '"' || peekChar() == '\'' || peekChar() == '>' || peekChar() == '%') ch = nextChar(); } StringBuilder.append((char) ch); } while (!isDelimiter()); } } return StringBuilder.toString(); }
// in java/org/apache/jasper/compiler/JspReader.java
private boolean isDelimiter() throws JasperException { if (! isSpace()) { int ch = peekChar(); // Look for a single-char work delimiter: if (ch == '=' || ch == '>' || ch == '"' || ch == '\'' || ch == '/') { return true; } // Look for an end-of-comment or end-of-tag: if (ch == '-') { Mark mark = mark(); if (((ch = nextChar()) == '>') || ((ch == '-') && (nextChar() == '>'))) { reset(mark); return true; } else { reset(mark); return false; } } return false; } else { return true; } }
// in java/org/apache/jasper/compiler/JspReader.java
private void pushFile(String file, String encoding, InputStreamReader reader) throws JasperException { // Register the file String longName = file; int fileid = registerSourceFile(longName); if (fileid == -1) { // Bugzilla 37407: http://issues.apache.org/bugzilla/show_bug.cgi?id=37407 if(reader != null) { try { reader.close(); } catch (Exception any) { if(log.isDebugEnabled()) { log.debug("Exception closing reader: ", any); } } } err.jspError("jsp.error.file.already.registered", file); } currFileId = fileid; try { CharArrayWriter caw = new CharArrayWriter(); char buf[] = new char[1024]; for (int i = 0 ; (i = reader.read(buf)) != -1 ;) caw.write(buf, 0, i); caw.close(); if (current == null) { current = new Mark(this, caw.toCharArray(), fileid, getFile(fileid), master, encoding); } else { current.pushStream(caw.toCharArray(), fileid, getFile(fileid), longName, encoding); } }
// in java/org/apache/jasper/compiler/JspReader.java
private boolean popFile() throws JasperException { // Is stack created ? (will happen if the Jsp file we're looking at is // missing. if (current == null || currFileId < 0) { return false; } // Restore parser state: String fName = getFile(currFileId); currFileId = unregisterSourceFile(fName); if (currFileId < -1) { err.jspError("jsp.error.file.not.registered", fName); } Mark previous = current.popStream(); if (previous != null) { master = current.baseDir; current = previous; return true; } // Note that although the current file is undefined here, "current" // is not set to null just for convenience, for it maybe used to // set the current (undefined) position. return false; }
// in java/org/apache/jasper/compiler/Generator.java
private void generateDeclarations(Node.Nodes page) throws JasperException { class DeclarationVisitor extends Node.Visitor { private boolean getServletInfoGenerated = false; /* * Generates getServletInfo() method that returns the value of the * page directive's 'info' attribute, if present. * * The Validator has already ensured that if the translation unit * contains more than one page directive with an 'info' attribute, * their values match. */ @Override public void visit(Node.PageDirective n) throws JasperException { if (getServletInfoGenerated) { return; } String info = n.getAttributeValue("info"); if (info == null) return; getServletInfoGenerated = true; out.printil("public java.lang.String getServletInfo() {"); out.pushIndent(); out.printin("return "); out.print(quote(info)); out.println(";"); out.popIndent(); out.printil("}"); out.println(); } @Override public void visit(Node.Declaration n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printMultiLn(n.getText()); out.println(); n.setEndJavaLine(out.getJavaLine()); } // Custom Tags may contain declarations from tag plugins. @Override public void visit(Node.CustomTag n) throws JasperException { if (n.useTagPlugin()) { if (n.getAtSTag() != null) { n.getAtSTag().visit(this); } visitBody(n); if (n.getAtETag() != null) { n.getAtETag().visit(this); } } else { visitBody(n); } } } out.println(); page.visit(new DeclarationVisitor()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.PageDirective n) throws JasperException { if (getServletInfoGenerated) { return; } String info = n.getAttributeValue("info"); if (info == null) return; getServletInfoGenerated = true; out.printil("public java.lang.String getServletInfo() {"); out.pushIndent(); out.printin("return "); out.print(quote(info)); out.println(";"); out.popIndent(); out.printil("}"); out.println(); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.Declaration n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printMultiLn(n.getText()); out.println(); n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.CustomTag n) throws JasperException { if (n.useTagPlugin()) { if (n.getAtSTag() != null) { n.getAtSTag().visit(this); } visitBody(n); if (n.getAtETag() != null) { n.getAtETag().visit(this); } } else { visitBody(n); } }
// in java/org/apache/jasper/compiler/Generator.java
private void compileTagHandlerPoolList(Node.Nodes page) throws JasperException { class TagHandlerPoolVisitor extends Node.Visitor { private final Vector<String> names; /* * Constructor * * @param v Vector of tag handler pool names to populate */ TagHandlerPoolVisitor(Vector<String> v) { names = v; } /* * Gets the name of the tag handler pool for the given custom tag * and adds it to the list of tag handler pool names unless it is * already contained in it. */ @Override public void visit(Node.CustomTag n) throws JasperException { if (!n.implementsSimpleTag()) { String name = createTagHandlerPoolName(n.getPrefix(), n .getLocalName(), n.getAttributes(), n.getNamedAttributeNodes(), n.hasEmptyBody()); n.setTagHandlerPoolName(name); if (!names.contains(name)) { names.add(name); } } visitBody(n); } /* * Creates the name of the tag handler pool whose tag handlers may * be (re)used to service this action. * * @return The name of the tag handler pool */ private String createTagHandlerPoolName(String prefix, String shortName, Attributes attrs, Node.Nodes namedAttrs, boolean hasEmptyBody) { StringBuilder poolName = new StringBuilder(64); poolName.append("_jspx_tagPool_").append(prefix).append('_') .append(shortName); if (attrs != null) { String[] attrNames = new String[attrs.getLength() + namedAttrs.size()]; for (int i = 0; i < attrNames.length; i++) { attrNames[i] = attrs.getQName(i); } for (int i = 0; i < namedAttrs.size(); i++) { attrNames[attrs.getLength() + i] = ((NamedAttribute) namedAttrs.getNode(i)).getQName(); } Arrays.sort(attrNames, Collections.reverseOrder()); if (attrNames.length > 0) { poolName.append('&'); } for (int i = 0; i < attrNames.length; i++) { poolName.append('_'); poolName.append(attrNames[i]); } } if (hasEmptyBody) { poolName.append("_nobody"); } return JspUtil.makeJavaIdentifier(poolName.toString()); } } page.visit(new TagHandlerPoolVisitor(tagHandlerPoolNames)); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.CustomTag n) throws JasperException { if (!n.implementsSimpleTag()) { String name = createTagHandlerPoolName(n.getPrefix(), n .getLocalName(), n.getAttributes(), n.getNamedAttributeNodes(), n.hasEmptyBody()); n.setTagHandlerPoolName(name); if (!names.contains(name)) { names.add(name); } } visitBody(n); }
// in java/org/apache/jasper/compiler/Generator.java
private void declareTemporaryScriptingVars(Node.Nodes page) throws JasperException { class ScriptingVarVisitor extends Node.Visitor { private final Vector<String> vars; ScriptingVarVisitor() { vars = new Vector<String>(); } @Override public void visit(Node.CustomTag n) throws JasperException { // XXX - Actually there is no need to declare those // "_jspx_" + varName + "_" + nestingLevel variables when we are // inside a JspFragment. if (n.getCustomNestingLevel() > 0) { TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { String varName = varInfos[i].getVarName(); String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); if (!vars.contains(tmpVarName)) { vars.add(tmpVarName); out.printin(varInfos[i].getClassName()); out.print(" "); out.print(tmpVarName); out.print(" = "); out.print(null); out.println(";"); } } } else { for (int i = 0; i < tagVarInfos.length; i++) { String varName = tagVarInfos[i].getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); if (!vars.contains(tmpVarName)) { vars.add(tmpVarName); out.printin(tagVarInfos[i].getClassName()); out.print(" "); out.print(tmpVarName); out.print(" = "); out.print(null); out.println(";"); } } } } visitBody(n); } } page.visit(new ScriptingVarVisitor()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.CustomTag n) throws JasperException { // XXX - Actually there is no need to declare those // "_jspx_" + varName + "_" + nestingLevel variables when we are // inside a JspFragment. if (n.getCustomNestingLevel() > 0) { TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { String varName = varInfos[i].getVarName(); String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); if (!vars.contains(tmpVarName)) { vars.add(tmpVarName); out.printin(varInfos[i].getClassName()); out.print(" "); out.print(tmpVarName); out.print(" = "); out.print(null); out.println(";"); } } } else { for (int i = 0; i < tagVarInfos.length; i++) { String varName = tagVarInfos[i].getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); if (!vars.contains(tmpVarName)) { vars.add(tmpVarName); out.printin(tagVarInfos[i].getClassName()); out.print(" "); out.print(tmpVarName); out.print(" = "); out.print(null); out.println(";"); } } } } visitBody(n); }
// in java/org/apache/jasper/compiler/Generator.java
private void generatePreamble(Node.Nodes page) throws JasperException { String servletPackageName = ctxt.getServletPackageName(); String servletClassName = ctxt.getServletClassName(); String serviceMethodName = Constants.SERVICE_METHOD_NAME; // First the package name: genPreamblePackage(servletPackageName); // Generate imports genPreambleImports(); // Generate class declaration out.printin("public final class "); out.print(servletClassName); out.print(" extends "); out.println(pageInfo.getExtends()); out.printin(" implements org.apache.jasper.runtime.JspSourceDependent"); if (!pageInfo.isThreadSafe()) { out.println(","); out.printin(" javax.servlet.SingleThreadModel"); } out.println(" {"); out.pushIndent(); // Class body begins here generateDeclarations(page); // Static initializations here genPreambleStaticInitializers(); // Class variable declarations genPreambleClassVariableDeclarations(); // Methods here genPreambleMethods(); // Now the service method out.printin("public void "); out.print(serviceMethodName); out.println("(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)"); out.println(" throws java.io.IOException, javax.servlet.ServletException {"); out.pushIndent(); out.println(); // Local variable declarations out.printil("final javax.servlet.jsp.PageContext pageContext;"); if (pageInfo.isSession()) out.printil("javax.servlet.http.HttpSession session = null;"); if (pageInfo.isErrorPage()) { out.printil("java.lang.Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request);"); out.printil("if (exception != null) {"); out.pushIndent(); out.printil("response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);"); out.popIndent(); out.printil("}"); } out.printil("final javax.servlet.ServletContext application;"); out.printil("final javax.servlet.ServletConfig config;"); out.printil("javax.servlet.jsp.JspWriter out = null;"); out.printil("final java.lang.Object page = this;"); out.printil("javax.servlet.jsp.JspWriter _jspx_out = null;"); out.printil("javax.servlet.jsp.PageContext _jspx_page_context = null;"); out.println(); declareTemporaryScriptingVars(page); out.println(); out.printil("try {"); out.pushIndent(); out.printin("response.setContentType("); out.print(quote(pageInfo.getContentType())); out.println(");"); if (ctxt.getOptions().isXpoweredBy()) { out.printil("response.addHeader(\"X-Powered-By\", \"JSP/2.1\");"); } out.printil("pageContext = _jspxFactory.getPageContext(this, request, response,"); out.printin("\t\t\t"); out.print(quote(pageInfo.getErrorPage())); out.print(", " + pageInfo.isSession()); out.print(", " + pageInfo.getBuffer()); out.print(", " + pageInfo.isAutoFlush()); out.println(");"); out.printil("_jspx_page_context = pageContext;"); out.printil("application = pageContext.getServletContext();"); out.printil("config = pageContext.getServletConfig();"); if (pageInfo.isSession()) out.printil("session = pageContext.getSession();"); out.printil("out = pageContext.getOut();"); out.printil("_jspx_out = out;"); out.println(); }
// in java/org/apache/jasper/compiler/Generator.java
private void printParams(Node n, String pageParam, boolean literal) throws JasperException { class ParamVisitor extends Node.Visitor { String separator; ParamVisitor(String separator) { this.separator = separator; } @Override public void visit(Node.ParamAction n) throws JasperException { out.print(" + "); out.print(separator); out.print(" + "); out.print("org.apache.jasper.runtime.JspRuntimeLibrary." + "URLEncode(" + quote(n.getTextAttribute("name")) + ", request.getCharacterEncoding())"); out.print("+ \"=\" + "); out.print(attributeValue(n.getValue(), true, String.class)); // The separator is '&' after the second use separator = "\"&\""; } } String sep; if (literal) { sep = pageParam.indexOf('?') > 0 ? "\"&\"" : "\"?\""; } else { sep = "((" + pageParam + ").indexOf('?')>0? '&': '?')"; } if (n.getBody() != null) { n.getBody().visit(new ParamVisitor(sep)); } }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.ParamAction n) throws JasperException { out.print(" + "); out.print(separator); out.print(" + "); out.print("org.apache.jasper.runtime.JspRuntimeLibrary." + "URLEncode(" + quote(n.getTextAttribute("name")) + ", request.getCharacterEncoding())"); out.print("+ \"=\" + "); out.print(attributeValue(n.getValue(), true, String.class)); // The separator is '&' after the second use separator = "\"&\""; }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.Expression n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printin("out.print("); out.printMultiLn(n.getText()); out.println(");"); n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.Scriptlet n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printMultiLn(n.getText()); out.println(); n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.ELExpression n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); if (!pageInfo.isELIgnored() && (n.getEL() != null)) { out.printil("out.write(" + JspUtil.interpreterCall(this.isTagFile, n.getType() + "{" + n.getText() + "}", String.class, n.getEL().getMapName(), false) + ");"); } else { out.printil("out.write(" + quote(n.getType() + "{" + n.getText() + "}") + ");"); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.IncludeAction n) throws JasperException { String flush = n.getTextAttribute("flush"); Node.JspAttribute page = n.getPage(); boolean isFlush = false; // default to false; if ("true".equals(flush)) isFlush = true; n.setBeginJavaLine(out.getJavaLine()); String pageParam; if (page.isNamedAttribute()) { // If the page for jsp:include was specified via // jsp:attribute, first generate code to evaluate // that body. pageParam = generateNamedAttributeValue(page .getNamedAttributeNode()); } else { pageParam = attributeValue(page, false, String.class); } // If any of the params have their values specified by // jsp:attribute, prepare those values first. Node jspBody = findJspBody(n); if (jspBody != null) { prepareParams(jspBody); } else { prepareParams(n); } out.printin("org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, " + pageParam); printParams(n, pageParam, page.isLiteral()); out.println(", out, " + isFlush + ");"); n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
private void prepareParams(Node parent) throws JasperException { if (parent == null) return; Node.Nodes subelements = parent.getBody(); if (subelements != null) { for (int i = 0; i < subelements.size(); i++) { Node n = subelements.getNode(i); if (n instanceof Node.ParamAction) { Node.Nodes paramSubElements = n.getBody(); for (int j = 0; (paramSubElements != null) && (j < paramSubElements.size()); j++) { Node m = paramSubElements.getNode(j); if (m instanceof Node.NamedAttribute) { generateNamedAttributeValue((Node.NamedAttribute) m); } } } } }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.ForwardAction n) throws JasperException { Node.JspAttribute page = n.getPage(); n.setBeginJavaLine(out.getJavaLine()); out.printil("if (true) {"); // So that javac won't complain about out.pushIndent(); // codes after "return" String pageParam; if (page.isNamedAttribute()) { // If the page for jsp:forward was specified via // jsp:attribute, first generate code to evaluate // that body. pageParam = generateNamedAttributeValue(page .getNamedAttributeNode()); } else { pageParam = attributeValue(page, false, String.class); } // If any of the params have their values specified by // jsp:attribute, prepare those values first. Node jspBody = findJspBody(n); if (jspBody != null) { prepareParams(jspBody); } else { prepareParams(n); } out.printin("_jspx_page_context.forward("); out.print(pageParam); printParams(n, pageParam, page.isLiteral()); out.println(");"); if (isTagFile || isFragment) { out.printil("throw new javax.servlet.jsp.SkipPageException();"); } else { out.printil((methodNesting > 0) ? "return true;" : "return;"); } out.popIndent(); out.printil("}"); n.setEndJavaLine(out.getJavaLine()); // XXX Not sure if we can eliminate dead codes after this. }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.GetProperty n) throws JasperException { String name = n.getTextAttribute("name"); String property = n.getTextAttribute("property"); n.setBeginJavaLine(out.getJavaLine()); if (beanInfo.checkVariable(name)) { // Bean is defined using useBean, introspect at compile time Class<?> bean = beanInfo.getBeanType(name); String beanName = bean.getCanonicalName(); java.lang.reflect.Method meth = JspRuntimeLibrary .getReadMethod(bean, property); String methodName = meth.getName(); out.printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString(" + "(((" + beanName + ")_jspx_page_context.findAttribute(" + "\"" + name + "\"))." + methodName + "())));"); } else if (!STRICT_GET_PROPERTY || varInfoNames.contains(name)) { // The object is a custom action with an associated // VariableInfo entry for this name. // Get the class name and then introspect at runtime. out.printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString" + "(org.apache.jasper.runtime.JspRuntimeLibrary.handleGetProperty" + "(_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\")));"); } else { StringBuilder msg = new StringBuilder(); msg.append("file:"); msg.append(n.getStart()); msg.append(" jsp:getProperty for bean with name '"); msg.append(name); msg.append( "'. Name was not previously introduced as per JSP.5.3"); throw new JasperException(msg.toString()); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.SetProperty n) throws JasperException { String name = n.getTextAttribute("name"); String property = n.getTextAttribute("property"); String param = n.getTextAttribute("param"); Node.JspAttribute value = n.getValue(); n.setBeginJavaLine(out.getJavaLine()); if ("*".equals(property)) { out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspect(" + "_jspx_page_context.findAttribute(" + "\"" + name + "\"), request);"); } else if (value == null) { if (param == null) param = property; // default to same as property out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", request.getParameter(\"" + param + "\"), " + "request, \"" + param + "\", false);"); } else if (value.isExpression()) { out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.handleSetProperty(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\","); out.print(attributeValue(value, false, null)); out.println(");"); } else if (value.isELInterpreterInput()) { // We've got to resolve the very call to the interpreter // at runtime since we don't know what type to expect // in the general case; we thus can't hard-wire the call // into the generated code. (XXX We could, however, // optimize the case where the bean is exposed with // <jsp:useBean>, much as the code here does for // getProperty.) // The following holds true for the arguments passed to // JspRuntimeLibrary.handleSetPropertyExpression(): // - 'pageContext' is a VariableResolver. // - 'this' (either the generated Servlet or the generated tag // handler for Tag files) is a FunctionMapper. out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.handleSetPropertyExpression(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", " + quote(value.getValue()) + ", " + "_jspx_page_context, " + value.getEL().getMapName() + ");"); } else if (value.isNamedAttribute()) { // If the value for setProperty was specified via // jsp:attribute, first generate code to evaluate // that body. String valueVarName = generateNamedAttributeValue(value .getNamedAttributeNode()); out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", " + valueVarName + ", null, null, false);"); } else { out.printin("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", "); out.print(attributeValue(value, false, null)); out.println(", null, null, false);"); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.UseBean n) throws JasperException { String name = n.getTextAttribute("id"); String scope = n.getTextAttribute("scope"); String klass = n.getTextAttribute("class"); String type = n.getTextAttribute("type"); Node.JspAttribute beanName = n.getBeanName(); // If "class" is specified, try an instantiation at compile time boolean generateNew = false; String canonicalName = null; // Canonical name for klass if (klass != null) { try { Class<?> bean = ctxt.getClassLoader().loadClass(klass); if (klass.indexOf('$') >= 0) { // Obtain the canonical type name canonicalName = bean.getCanonicalName(); } else { canonicalName = klass; } int modifiers = bean.getModifiers(); if (!Modifier.isPublic(modifiers) || Modifier.isInterface(modifiers) || Modifier.isAbstract(modifiers)) { throw new Exception("Invalid bean class modifier"); } // Check that there is a 0 arg constructor bean.getConstructor(new Class[] {}); // At compile time, we have determined that the bean class // exists, with a public zero constructor, new() can be // used for bean instantiation. generateNew = true; } catch (Exception e) { // Cannot instantiate the specified class, either a // compilation error or a runtime error will be raised, // depending on a compiler flag. if (ctxt.getOptions() .getErrorOnUseBeanInvalidClassAttribute()) { err.jspError(n, "jsp.error.invalid.bean", klass); } if (canonicalName == null) { // Doing our best here to get a canonical name // from the binary name, should work 99.99% of time. canonicalName = klass.replace('$', '.'); } } if (type == null) { // if type is unspecified, use "class" as type of bean type = canonicalName; } } // JSP.5.1, Sematics, para 1 - lock not required for request or // page scope String scopename = "javax.servlet.jsp.PageContext.PAGE_SCOPE"; // Default to page String lock = null; if ("request".equals(scope)) { scopename = "javax.servlet.jsp.PageContext.REQUEST_SCOPE"; } else if ("session".equals(scope)) { scopename = "javax.servlet.jsp.PageContext.SESSION_SCOPE"; lock = "session"; } else if ("application".equals(scope)) { scopename = "javax.servlet.jsp.PageContext.APPLICATION_SCOPE"; lock = "application"; } n.setBeginJavaLine(out.getJavaLine()); // Declare bean out.printin(type); out.print(' '); out.print(name); out.println(" = null;"); // Lock (if required) while getting or creating bean if (lock != null) { out.printin("synchronized ("); out.print(lock); out.println(") {"); out.pushIndent(); } // Locate bean from context out.printin(name); out.print(" = ("); out.print(type); out.print(") _jspx_page_context.getAttribute("); out.print(quote(name)); out.print(", "); out.print(scopename); out.println(");"); // Create bean /* * Check if bean is already there */ out.printin("if ("); out.print(name); out.println(" == null){"); out.pushIndent(); if (klass == null && beanName == null) { /* * If both class name and beanName is not specified, the bean * must be found locally, otherwise it's an error */ out.printin("throw new java.lang.InstantiationException(\"bean "); out.print(name); out.println(" not found within scope\");"); } else { /* * Instantiate the bean if it is not in the specified scope. */ if (!generateNew) { String binaryName; if (beanName != null) { if (beanName.isNamedAttribute()) { // If the value for beanName was specified via // jsp:attribute, first generate code to evaluate // that body. binaryName = generateNamedAttributeValue(beanName .getNamedAttributeNode()); } else { binaryName = attributeValue(beanName, false, String.class); } } else { // Implies klass is not null binaryName = quote(klass); } out.printil("try {"); out.pushIndent(); out.printin(name); out.print(" = ("); out.print(type); out.print(") java.beans.Beans.instantiate("); out.print("this.getClass().getClassLoader(), "); out.print(binaryName); out.println(");"); out.popIndent(); /* * Note: Beans.instantiate throws ClassNotFoundException if * the bean class is abstract. */ out.printil("} catch (java.lang.ClassNotFoundException exc) {"); out.pushIndent(); out.printil("throw new InstantiationException(exc.getMessage());"); out.popIndent(); out.printil("} catch (java.lang.Exception exc) {"); out.pushIndent(); out.printin("throw new javax.servlet.ServletException("); out.print("\"Cannot create bean of class \" + "); out.print(binaryName); out.println(", exc);"); out.popIndent(); out.printil("}"); // close of try } else { // Implies klass is not null // Generate codes to instantiate the bean class out.printin(name); out.print(" = new "); out.print(canonicalName); out.println("();"); } /* * Set attribute for bean in the specified scope */ out.printin("_jspx_page_context.setAttribute("); out.print(quote(name)); out.print(", "); out.print(name); out.print(", "); out.print(scopename); out.println(");"); // Only visit the body when bean is instantiated visitBody(n); } out.popIndent(); out.printil("}"); // End of lock block if (lock != null) { out.popIndent(); out.printil("}"); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.PlugIn n) throws JasperException { /** * A visitor to handle &lt;jsp:param&gt; in a plugin */ class ParamVisitor extends Node.Visitor { private final boolean ie; ParamVisitor(boolean ie) { this.ie = ie; } @Override public void visit(Node.ParamAction n) throws JasperException { String name = n.getTextAttribute("name"); if (name.equalsIgnoreCase("object")) name = "java_object"; else if (name.equalsIgnoreCase("type")) name = "java_type"; n.setBeginJavaLine(out.getJavaLine()); // XXX - Fixed a bug here - value used to be output // inline, which is only okay if value is not an EL // expression. Also, key/value pairs for the // embed tag were not being generated correctly. // Double check that this is now the correct behavior. if (ie) { // We want something of the form // out.println( "<param name=\"blah\" // value=\"" + ... + "\">" ); out.printil("out.write( \"<param name=\\\"" + escape(name) + "\\\" value=\\\"\" + " + attributeValue(n.getValue(), false, String.class) + " + \"\\\">\" );"); out.printil("out.write(\"\\n\");"); } else { // We want something of the form // out.print( " blah=\"" + ... + "\"" ); out.printil("out.write( \" " + escape(name) + "=\\\"\" + " + attributeValue(n.getValue(), false, String.class) + " + \"\\\"\" );"); } n.setEndJavaLine(out.getJavaLine()); } } String type = n.getTextAttribute("type"); String code = n.getTextAttribute("code"); String name = n.getTextAttribute("name"); Node.JspAttribute height = n.getHeight(); Node.JspAttribute width = n.getWidth(); String hspace = n.getTextAttribute("hspace"); String vspace = n.getTextAttribute("vspace"); String align = n.getTextAttribute("align"); String iepluginurl = n.getTextAttribute("iepluginurl"); String nspluginurl = n.getTextAttribute("nspluginurl"); String codebase = n.getTextAttribute("codebase"); String archive = n.getTextAttribute("archive"); String jreversion = n.getTextAttribute("jreversion"); String widthStr = null; if (width != null) { if (width.isNamedAttribute()) { widthStr = generateNamedAttributeValue(width .getNamedAttributeNode()); } else { widthStr = attributeValue(width, false, String.class); } } String heightStr = null; if (height != null) { if (height.isNamedAttribute()) { heightStr = generateNamedAttributeValue(height .getNamedAttributeNode()); } else { heightStr = attributeValue(height, false, String.class); } } if (iepluginurl == null) iepluginurl = Constants.IE_PLUGIN_URL; if (nspluginurl == null) nspluginurl = Constants.NS_PLUGIN_URL; n.setBeginJavaLine(out.getJavaLine()); // If any of the params have their values specified by // jsp:attribute, prepare those values first. // Look for a params node and prepare its param subelements: Node.JspBody jspBody = findJspBody(n); if (jspBody != null) { Node.Nodes subelements = jspBody.getBody(); if (subelements != null) { for (int i = 0; i < subelements.size(); i++) { Node m = subelements.getNode(i); if (m instanceof Node.ParamsAction) { prepareParams(m); break; } } } } // XXX - Fixed a bug here - width and height can be set // dynamically. Double-check if this generation is correct. // IE style plugin // <object ...> // First compose the runtime output string String s0 = "<object" + makeAttr("classid", ctxt.getOptions().getIeClassId()) + makeAttr("name", name); String s1 = ""; if (width != null) { s1 = " + \" width=\\\"\" + " + widthStr + " + \"\\\"\""; } String s2 = ""; if (height != null) { s2 = " + \" height=\\\"\" + " + heightStr + " + \"\\\"\""; } String s3 = makeAttr("hspace", hspace) + makeAttr("vspace", vspace) + makeAttr("align", align) + makeAttr("codebase", iepluginurl) + '>'; // Then print the output string to the java file out.printil("out.write(" + quote(s0) + s1 + s2 + " + " + quote(s3) + ");"); out.printil("out.write(\"\\n\");"); // <param > for java_code s0 = "<param name=\"java_code\"" + makeAttr("value", code) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); // <param > for java_codebase if (codebase != null) { s0 = "<param name=\"java_codebase\"" + makeAttr("value", codebase) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); } // <param > for java_archive if (archive != null) { s0 = "<param name=\"java_archive\"" + makeAttr("value", archive) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); } // <param > for type s0 = "<param name=\"type\"" + makeAttr("value", "application/x-java-" + type + ((jreversion == null) ? "" : ";version=" + jreversion)) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); /* * generate a <param> for each <jsp:param> in the plugin body */ if (n.getBody() != null) n.getBody().visit(new ParamVisitor(true)); /* * Netscape style plugin part */ out.printil("out.write(" + quote("<comment>") + ");"); out.printil("out.write(\"\\n\");"); s0 = "<EMBED" + makeAttr("type", "application/x-java-" + type + ((jreversion == null) ? "" : ";version=" + jreversion)) + makeAttr("name", name); // s1 and s2 are the same as before. s3 = makeAttr("hspace", hspace) + makeAttr("vspace", vspace) + makeAttr("align", align) + makeAttr("pluginspage", nspluginurl) + makeAttr("java_code", code) + makeAttr("java_codebase", codebase) + makeAttr("java_archive", archive); out.printil("out.write(" + quote(s0) + s1 + s2 + " + " + quote(s3) + ");"); /* * Generate a 'attr = "value"' for each <jsp:param> in plugin body */ if (n.getBody() != null) n.getBody().visit(new ParamVisitor(false)); out.printil("out.write(" + quote("/>") + ");"); out.printil("out.write(\"\\n\");"); out.printil("out.write(" + quote("<noembed>") + ");"); out.printil("out.write(\"\\n\");"); /* * Fallback */ if (n.getBody() != null) { visitBody(n); out.printil("out.write(\"\\n\");"); } out.printil("out.write(" + quote("</noembed>") + ");"); out.printil("out.write(\"\\n\");"); out.printil("out.write(" + quote("</comment>") + ");"); out.printil("out.write(\"\\n\");"); out.printil("out.write(" + quote("</object>") + ");"); out.printil("out.write(\"\\n\");"); n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.ParamAction n) throws JasperException { String name = n.getTextAttribute("name"); if (name.equalsIgnoreCase("object")) name = "java_object"; else if (name.equalsIgnoreCase("type")) name = "java_type"; n.setBeginJavaLine(out.getJavaLine()); // XXX - Fixed a bug here - value used to be output // inline, which is only okay if value is not an EL // expression. Also, key/value pairs for the // embed tag were not being generated correctly. // Double check that this is now the correct behavior. if (ie) { // We want something of the form // out.println( "<param name=\"blah\" // value=\"" + ... + "\">" ); out.printil("out.write( \"<param name=\\\"" + escape(name) + "\\\" value=\\\"\" + " + attributeValue(n.getValue(), false, String.class) + " + \"\\\">\" );"); out.printil("out.write(\"\\n\");"); } else { // We want something of the form // out.print( " blah=\"" + ... + "\"" ); out.printil("out.write( \" " + escape(name) + "=\\\"\" + " + attributeValue(n.getValue(), false, String.class) + " + \"\\\"\" );"); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.NamedAttribute n) throws JasperException { // Don't visit body of this tag - we already did earlier. }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.CustomTag n) throws JasperException { // Use plugin to generate more efficient code if there is one. if (n.useTagPlugin()) { generateTagPlugin(n); return; } TagHandlerInfo handlerInfo = getTagHandlerInfo(n); // Create variable names String baseVar = createTagVarName(n.getQName(), n.getPrefix(), n .getLocalName()); String tagEvalVar = "_jspx_eval_" + baseVar; String tagHandlerVar = "_jspx_th_" + baseVar; String tagPushBodyCountVar = "_jspx_push_body_count_" + baseVar; // If the tag contains no scripting element, generate its codes // to a method. ServletWriter outSave = null; Node.ChildInfo ci = n.getChildInfo(); if (ci.isScriptless() && !ci.hasScriptingVars()) { // The tag handler and its body code can reside in a separate // method if it is scriptless and does not have any scripting // variable defined. String tagMethod = "_jspx_meth_" + baseVar; // Generate a call to this method out.printin("if ("); out.print(tagMethod); out.print("("); if (parent != null) { out.print(parent); out.print(", "); } out.print("_jspx_page_context"); if (pushBodyCountVar != null) { out.print(", "); out.print(pushBodyCountVar); } out.println("))"); out.pushIndent(); out.printil((methodNesting > 0) ? "return true;" : "return;"); out.popIndent(); // Set up new buffer for the method outSave = out; /* * For fragments, their bodies will be generated in fragment * helper classes, and the Java line adjustments will be done * there, hence they are set to null here to avoid double * adjustments. */ GenBuffer genBuffer = new GenBuffer(n, n.implementsSimpleTag() ? null : n.getBody()); methodsBuffered.add(genBuffer); out = genBuffer.getOut(); methodNesting++; // Generate code for method declaration out.println(); out.pushIndent(); out.printin("private boolean "); out.print(tagMethod); out.print("("); if (parent != null) { out.print("javax.servlet.jsp.tagext.JspTag "); out.print(parent); out.print(", "); } out.print("javax.servlet.jsp.PageContext _jspx_page_context"); if (pushBodyCountVar != null) { out.print(", int[] "); out.print(pushBodyCountVar); } out.println(")"); out.printil(" throws java.lang.Throwable {"); out.pushIndent(); // Initialize local variables used in this method. if (!isTagFile) { out.printil("javax.servlet.jsp.PageContext pageContext = _jspx_page_context;"); } out.printil("javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();"); generateLocalVariables(out, n); } // Add the named objects to the list of 'introduced' names to enable // a later test as per JSP.5.3 VariableInfo[] infos = n.getVariableInfos(); if (infos != null && infos.length > 0) { for (int i = 0; i < infos.length; i++) { VariableInfo info = infos[i]; if (info != null && info.getVarName() != null) pageInfo.getVarInfoNames().add(info.getVarName()); } } TagVariableInfo[] tagInfos = n.getTagVariableInfos(); if (tagInfos != null && tagInfos.length > 0) { for (int i = 0; i < tagInfos.length; i++) { TagVariableInfo tagInfo = tagInfos[i]; if (tagInfo != null) { String name = tagInfo.getNameGiven(); if (name == null) { String nameFromAttribute = tagInfo.getNameFromAttribute(); name = n.getAttributeValue(nameFromAttribute); } pageInfo.getVarInfoNames().add(name); } } } if (n.implementsSimpleTag()) { generateCustomDoTag(n, handlerInfo, tagHandlerVar); } else { /* * Classic tag handler: Generate code for start element, body, * and end element */ generateCustomStart(n, handlerInfo, tagHandlerVar, tagEvalVar, tagPushBodyCountVar); // visit body String tmpParent = parent; parent = tagHandlerVar; boolean isSimpleTagParentSave = isSimpleTagParent; isSimpleTagParent = false; String tmpPushBodyCountVar = null; if (n.implementsTryCatchFinally()) { tmpPushBodyCountVar = pushBodyCountVar; pushBodyCountVar = tagPushBodyCountVar; } boolean tmpIsSimpleTagHandler = isSimpleTagHandler; isSimpleTagHandler = false; visitBody(n); parent = tmpParent; isSimpleTagParent = isSimpleTagParentSave; if (n.implementsTryCatchFinally()) { pushBodyCountVar = tmpPushBodyCountVar; } isSimpleTagHandler = tmpIsSimpleTagHandler; generateCustomEnd(n, tagHandlerVar, tagEvalVar, tagPushBodyCountVar); } if (ci.isScriptless() && !ci.hasScriptingVars()) { // Generate end of method if (methodNesting > 0) { out.printil("return false;"); } out.popIndent(); out.printil("}"); out.popIndent(); methodNesting--; // restore previous writer out = outSave; } }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.UninterpretedTag n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); /* * Write begin tag */ out.printin("out.write(\"<"); out.print(n.getQName()); Attributes attrs = n.getNonTaglibXmlnsAttributes(); if (attrs != null) { for (int i = 0; i < attrs.getLength(); i++) { out.print(" "); out.print(attrs.getQName(i)); out.print("="); out.print(DOUBLE_QUOTE); out.print(attrs.getValue(i).replace("\"", "&quot;")); out.print(DOUBLE_QUOTE); } } attrs = n.getAttributes(); if (attrs != null) { Node.JspAttribute[] jspAttrs = n.getJspAttributes(); for (int i = 0; i < attrs.getLength(); i++) { out.print(" "); out.print(attrs.getQName(i)); out.print("="); if (jspAttrs[i].isELInterpreterInput()) { out.print("\\\"\" + "); out.print(attributeValue(jspAttrs[i], false, String.class)); out.print(" + \"\\\""); } else { out.print(DOUBLE_QUOTE); out.print(attrs.getValue(i).replace("\"", "&quot;")); out.print(DOUBLE_QUOTE); } } } if (n.getBody() != null) { out.println(">\");"); // Visit tag body visitBody(n); /* * Write end tag */ out.printin("out.write(\"</"); out.print(n.getQName()); out.println(">\");"); } else { out.println("/>\");"); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.JspElement n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); // Compute attribute value string for XML-style and named // attributes Hashtable<String,String> map = new Hashtable<String,String>(); Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { String value = null; String nvp = null; if (attrs[i].isNamedAttribute()) { NamedAttribute attr = attrs[i].getNamedAttributeNode(); Node.JspAttribute omitAttr = attr.getOmit(); String omit; if (omitAttr == null) { omit = "false"; } else { omit = attributeValue(omitAttr, false, boolean.class); if ("true".equals(omit)) { continue; } } value = generateNamedAttributeValue( attrs[i].getNamedAttributeNode()); if ("false".equals(omit)) { nvp = " + \" " + attrs[i].getName() + "=\\\"\" + " + value + " + \"\\\"\""; } else { nvp = " + (java.lang.Boolean.valueOf(" + omit + ")?\"\":\" " + attrs[i].getName() + "=\\\"\" + " + value + " + \"\\\"\")"; } } else { value = attributeValue(attrs[i], false, Object.class); nvp = " + \" " + attrs[i].getName() + "=\\\"\" + " + value + " + \"\\\"\""; } map.put(attrs[i].getName(), nvp); } // Write begin tag, using XML-style 'name' attribute as the // element name String elemName = attributeValue(n.getNameAttribute(), false, String.class); out.printin("out.write(\"<\""); out.print(" + " + elemName); // Write remaining attributes Enumeration<String> enumeration = map.keys(); while (enumeration.hasMoreElements()) { String attrName = enumeration.nextElement(); out.print(map.get(attrName)); } // Does the <jsp:element> have nested tags other than // <jsp:attribute> boolean hasBody = false; Node.Nodes subelements = n.getBody(); if (subelements != null) { for (int i = 0; i < subelements.size(); i++) { Node subelem = subelements.getNode(i); if (!(subelem instanceof Node.NamedAttribute)) { hasBody = true; break; } } } if (hasBody) { out.println(" + \">\");"); // Smap should not include the body n.setEndJavaLine(out.getJavaLine()); // Visit tag body visitBody(n); // Write end tag out.printin("out.write(\"</\""); out.print(" + " + elemName); out.println(" + \">\");"); } else { out.println(" + \"/>\");"); n.setEndJavaLine(out.getJavaLine()); } }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.TemplateText n) throws JasperException { String text = n.getText(); int textSize = text.length(); if (textSize == 0) { return; } if (textSize <= 3) { // Special case small text strings n.setBeginJavaLine(out.getJavaLine()); int lineInc = 0; for (int i = 0; i < textSize; i++) { char ch = text.charAt(i); out.printil("out.write(" + quote(ch) + ");"); if (i > 0) { n.addSmap(lineInc); } if (ch == '\n') { lineInc++; } } n.setEndJavaLine(out.getJavaLine()); return; } if (ctxt.getOptions().genStringAsCharArray()) { // Generate Strings as char arrays, for performance ServletWriter caOut; if (charArrayBuffer == null) { charArrayBuffer = new GenBuffer(); caOut = charArrayBuffer.getOut(); caOut.pushIndent(); textMap = new HashMap<String,String>(); } else { caOut = charArrayBuffer.getOut(); } // UTF-8 is up to 4 bytes per character // String constants are limited to 64k bytes // Limit string constants here to 16k characters int textIndex = 0; int textLength = text.length(); while (textIndex < textLength) { int len = 0; if (textLength - textIndex > 16384) { len = 16384; } else { len = textLength - textIndex; } String output = text.substring(textIndex, textIndex + len); String charArrayName = textMap.get(output); if (charArrayName == null) { charArrayName = "_jspx_char_array_" + charArrayCount++; textMap.put(output, charArrayName); caOut.printin("static char[] "); caOut.print(charArrayName); caOut.print(" = "); caOut.print(quote(output)); caOut.println(".toCharArray();"); } n.setBeginJavaLine(out.getJavaLine()); out.printil("out.write(" + charArrayName + ");"); n.setEndJavaLine(out.getJavaLine()); textIndex = textIndex + len; } return; } n.setBeginJavaLine(out.getJavaLine()); out.printin(); StringBuilder sb = new StringBuilder("out.write(\""); int initLength = sb.length(); int count = JspUtil.CHUNKSIZE; int srcLine = 0; // relative to starting source line for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); --count; switch (ch) { case '"': sb.append('\\').append('\"'); break; case '\\': sb.append('\\').append('\\'); break; case '\r': sb.append('\\').append('r'); break; case '\n': sb.append('\\').append('n'); srcLine++; if (breakAtLF || count < 0) { // Generate an out.write() when see a '\n' in template sb.append("\");"); out.println(sb.toString()); if (i < text.length() - 1) { out.printin(); } sb.setLength(initLength); count = JspUtil.CHUNKSIZE; } // add a Smap for this line n.addSmap(srcLine); break; case '\t': // Not sure we need this sb.append('\\').append('t'); break; default: sb.append(ch); } } if (sb.length() > initLength) { sb.append("\");"); out.println(sb.toString()); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.JspBody n) throws JasperException { if (n.getBody() != null) { if (isSimpleTagHandler) { out.printin(simpleTagHandlerVar); out.print(".setJspBody("); generateJspFragment(n, simpleTagHandlerVar); out.println(");"); } else { visitBody(n); } } }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.InvokeAction n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); // Copy virtual page scope of tag file to page scope of invoking // page out.printil("((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke();"); String varReaderAttr = n.getTextAttribute("varReader"); String varAttr = n.getTextAttribute("var"); if (varReaderAttr != null || varAttr != null) { out.printil("_jspx_sout = new java.io.StringWriter();"); } else { out.printil("_jspx_sout = null;"); } // Invoke fragment, unless fragment is null out.printin("if ("); out.print(toGetterMethod(n.getTextAttribute("fragment"))); out.println(" != null) {"); out.pushIndent(); out.printin(toGetterMethod(n.getTextAttribute("fragment"))); out.println(".invoke(_jspx_sout);"); out.popIndent(); out.printil("}"); // Store varReader in appropriate scope if (varReaderAttr != null || varAttr != null) { String scopeName = n.getTextAttribute("scope"); out.printin("_jspx_page_context.setAttribute("); if (varReaderAttr != null) { out.print(quote(varReaderAttr)); out.print(", new java.io.StringReader(_jspx_sout.toString())"); } else { out.print(quote(varAttr)); out.print(", _jspx_sout.toString()"); } if (scopeName != null) { out.print(", "); out.print(getScopeConstant(scopeName)); } out.println(");"); } n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.DoBodyAction n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); // Copy virtual page scope of tag file to page scope of invoking // page out.printil("((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke();"); // Invoke body String varReaderAttr = n.getTextAttribute("varReader"); String varAttr = n.getTextAttribute("var"); if (varReaderAttr != null || varAttr != null) { out.printil("_jspx_sout = new java.io.StringWriter();"); } else { out.printil("_jspx_sout = null;"); } out.printil("if (getJspBody() != null)"); out.pushIndent(); out.printil("getJspBody().invoke(_jspx_sout);"); out.popIndent(); // Store varReader in appropriate scope if (varReaderAttr != null || varAttr != null) { String scopeName = n.getTextAttribute("scope"); out.printin("_jspx_page_context.setAttribute("); if (varReaderAttr != null) { out.print(quote(varReaderAttr)); out.print(", new java.io.StringReader(_jspx_sout.toString())"); } else { out.print(quote(varAttr)); out.print(", _jspx_sout.toString()"); } if (scopeName != null) { out.print(", "); out.print(getScopeConstant(scopeName)); } out.println(");"); } // Restore EL context out.printil("jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,getJspContext());"); n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.AttributeGenerator n) throws JasperException { Node.CustomTag tag = n.getTag(); Node.JspAttribute[] attrs = tag.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { if (attrs[i].getName().equals(n.getName())) { out.print(evaluateAttribute(getTagHandlerInfo(tag), attrs[i], tag, null)); break; } } }
// in java/org/apache/jasper/compiler/Generator.java
private TagHandlerInfo getTagHandlerInfo(Node.CustomTag n) throws JasperException { Hashtable<String,TagHandlerInfo> handlerInfosByShortName = handlerInfos.get(n.getPrefix()); if (handlerInfosByShortName == null) { handlerInfosByShortName = new Hashtable<String,TagHandlerInfo>(); handlerInfos.put(n.getPrefix(), handlerInfosByShortName); } TagHandlerInfo handlerInfo = handlerInfosByShortName.get(n.getLocalName()); if (handlerInfo == null) { handlerInfo = new TagHandlerInfo(n, n.getTagHandlerClass(), err); handlerInfosByShortName.put(n.getLocalName(), handlerInfo); } return handlerInfo; }
// in java/org/apache/jasper/compiler/Generator.java
private void generateTagPlugin(Node.CustomTag n) throws JasperException { if (n.getAtSTag() != null) { n.getAtSTag().visit(this); } visitBody(n); if (n.getAtETag() != null) { n.getAtETag().visit(this); } }
// in java/org/apache/jasper/compiler/Generator.java
private void generateCustomStart(Node.CustomTag n, TagHandlerInfo handlerInfo, String tagHandlerVar, String tagEvalVar, String tagPushBodyCountVar) throws JasperException { Class<?> tagHandlerClass = handlerInfo.getTagHandlerClass(); out.printin("// "); out.println(n.getQName()); n.setBeginJavaLine(out.getJavaLine()); // Declare AT_BEGIN scripting variables declareScriptingVars(n, VariableInfo.AT_BEGIN); saveScriptingVars(n, VariableInfo.AT_BEGIN); String tagHandlerClassName = tagHandlerClass.getCanonicalName(); if (isPoolingEnabled && !(n.implementsJspIdConsumer())) { out.printin(tagHandlerClassName); out.print(" "); out.print(tagHandlerVar); out.print(" = "); out.print("("); out.print(tagHandlerClassName); out.print(") "); out.print(n.getTagHandlerPoolName()); out.print(".get("); out.print(tagHandlerClassName); out.println(".class);"); } else { writeNewInstance(tagHandlerVar, tagHandlerClassName); } // includes setting the context generateSetters(n, tagHandlerVar, handlerInfo, false); // JspIdConsumer (after context has been set) if (n.implementsJspIdConsumer()) { out.printin(tagHandlerVar); out.print(".setJspId(\""); out.print(createJspId()); out.println("\");"); } if (n.implementsTryCatchFinally()) { out.printin("int[] "); out.print(tagPushBodyCountVar); out.println(" = new int[] { 0 };"); out.printil("try {"); out.pushIndent(); } out.printin("int "); out.print(tagEvalVar); out.print(" = "); out.print(tagHandlerVar); out.println(".doStartTag();"); if (!n.implementsBodyTag()) { // Synchronize AT_BEGIN scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); } if (!n.hasEmptyBody()) { out.printin("if ("); out.print(tagEvalVar); out.println(" != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {"); out.pushIndent(); // Declare NESTED scripting variables declareScriptingVars(n, VariableInfo.NESTED); saveScriptingVars(n, VariableInfo.NESTED); if (n.implementsBodyTag()) { out.printin("if ("); out.print(tagEvalVar); out.println(" != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {"); // Assume EVAL_BODY_BUFFERED out.pushIndent(); out.printil("out = _jspx_page_context.pushBody();"); if (n.implementsTryCatchFinally()) { out.printin(tagPushBodyCountVar); out.println("[0]++;"); } else if (pushBodyCountVar != null) { out.printin(pushBodyCountVar); out.println("[0]++;"); } out.printin(tagHandlerVar); out.println(".setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);"); out.printin(tagHandlerVar); out.println(".doInitBody();"); out.popIndent(); out.printil("}"); // Synchronize AT_BEGIN and NESTED scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); syncScriptingVars(n, VariableInfo.NESTED); } else { // Synchronize NESTED scripting variables syncScriptingVars(n, VariableInfo.NESTED); } if (n.implementsIterationTag()) { out.printil("do {"); out.pushIndent(); } } // Map the Java lines that handles start of custom tags to the // JSP line for this tag n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
private void generateCustomDoTag(Node.CustomTag n, TagHandlerInfo handlerInfo, String tagHandlerVar) throws JasperException { Class<?> tagHandlerClass = handlerInfo.getTagHandlerClass(); n.setBeginJavaLine(out.getJavaLine()); out.printin("// "); out.println(n.getQName()); // Declare AT_BEGIN scripting variables declareScriptingVars(n, VariableInfo.AT_BEGIN); saveScriptingVars(n, VariableInfo.AT_BEGIN); String tagHandlerClassName = tagHandlerClass.getCanonicalName(); writeNewInstance(tagHandlerVar, tagHandlerClassName); generateSetters(n, tagHandlerVar, handlerInfo, true); // JspIdConsumer (after context has been set) if (n.implementsJspIdConsumer()) { out.printin(tagHandlerVar); out.print(".setJspId(\""); out.print(createJspId()); out.println("\");"); } // Set the body if (findJspBody(n) == null) { /* * Encapsulate body of custom tag invocation in JspFragment and * pass it to tag handler's setJspBody(), unless tag body is * empty */ if (!n.hasEmptyBody()) { out.printin(tagHandlerVar); out.print(".setJspBody("); generateJspFragment(n, tagHandlerVar); out.println(");"); } } else { /* * Body of tag is the body of the <jsp:body> element. The visit * method for that element is going to encapsulate that * element's body in a JspFragment and pass it to the tag * handler's setJspBody() */ String tmpTagHandlerVar = simpleTagHandlerVar; simpleTagHandlerVar = tagHandlerVar; boolean tmpIsSimpleTagHandler = isSimpleTagHandler; isSimpleTagHandler = true; visitBody(n); simpleTagHandlerVar = tmpTagHandlerVar; isSimpleTagHandler = tmpIsSimpleTagHandler; } out.printin(tagHandlerVar); out.println(".doTag();"); restoreScriptingVars(n, VariableInfo.AT_BEGIN); // Synchronize AT_BEGIN scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); // Declare and synchronize AT_END scripting variables declareScriptingVars(n, VariableInfo.AT_END); syncScriptingVars(n, VariableInfo.AT_END); // Resource injection writeDestroyInstance(tagHandlerVar); n.setEndJavaLine(out.getJavaLine()); }
// in java/org/apache/jasper/compiler/Generator.java
private void generateSetters(Node.CustomTag n, String tagHandlerVar, TagHandlerInfo handlerInfo, boolean simpleTag) throws JasperException { // Set context if (simpleTag) { // Generate alias map String aliasMapVar = null; if (n.isTagFile()) { aliasMapVar = generateAliasMap(n, tagHandlerVar); } out.printin(tagHandlerVar); if (aliasMapVar == null) { out.println(".setJspContext(_jspx_page_context);"); } else { out.print(".setJspContext(_jspx_page_context, "); out.print(aliasMapVar); out.println(");"); } } else { out.printin(tagHandlerVar); out.println(".setPageContext(_jspx_page_context);"); } // Set parent if (isTagFile && parent == null) { out.printin(tagHandlerVar); out.print(".setParent("); out.print("new javax.servlet.jsp.tagext.TagAdapter("); out.print("(javax.servlet.jsp.tagext.SimpleTag) this ));"); } else if (!simpleTag) { out.printin(tagHandlerVar); out.print(".setParent("); if (parent != null) { if (isSimpleTagParent) { out.print("new javax.servlet.jsp.tagext.TagAdapter("); out.print("(javax.servlet.jsp.tagext.SimpleTag) "); out.print(parent); out.println("));"); } else { out.print("(javax.servlet.jsp.tagext.Tag) "); out.print(parent); out.println(");"); } } else { out.println("null);"); } } else { // The setParent() method need not be called if the value being // passed is null, since SimpleTag instances are not reused if (parent != null) { out.printin(tagHandlerVar); out.print(".setParent("); out.print(parent); out.println(");"); } } // need to handle deferred values and methods Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { String attrValue = evaluateAttribute(handlerInfo, attrs[i], n, tagHandlerVar); Mark m = n.getStart(); out.printil("// "+m.getFile()+"("+m.getLineNumber()+","+m.getColumnNumber()+") "+ attrs[i].getTagAttributeInfo()); if (attrs[i].isDynamic()) { out.printin(tagHandlerVar); out.print("."); out.print("setDynamicAttribute("); String uri = attrs[i].getURI(); if ("".equals(uri) || (uri == null)) { out.print("null"); } else { out.print("\"" + attrs[i].getURI() + "\""); } out.print(", \""); out.print(attrs[i].getLocalName()); out.print("\", "); out.print(attrValue); out.println(");"); } else { out.printin(tagHandlerVar); out.print("."); out.print(handlerInfo.getSetterMethod( attrs[i].getLocalName()).getName()); out.print("("); out.print(attrValue); out.println(");"); } } }
// in java/org/apache/jasper/compiler/Generator.java
private void generateJspFragment(Node n, String tagHandlerVar) throws JasperException { // XXX - A possible optimization here would be to check to see // if the only child of the parent node is TemplateText. If so, // we know there won't be any parameters, etc, so we can // generate a low-overhead JspFragment that just echoes its // body. The implementation of this fragment can come from // the org.apache.jasper.runtime package as a support class. FragmentHelperClass.Fragment fragment = fragmentHelperClass .openFragment(n, methodNesting); ServletWriter outSave = out; out = fragment.getGenBuffer().getOut(); String tmpParent = parent; parent = "_jspx_parent"; boolean isSimpleTagParentSave = isSimpleTagParent; isSimpleTagParent = true; boolean tmpIsFragment = isFragment; isFragment = true; String pushBodyCountVarSave = pushBodyCountVar; if (pushBodyCountVar != null) { // Use a fixed name for push body count, to simplify code gen pushBodyCountVar = "_jspx_push_body_count"; } visitBody(n); out = outSave; parent = tmpParent; isSimpleTagParent = isSimpleTagParentSave; isFragment = tmpIsFragment; pushBodyCountVar = pushBodyCountVarSave; fragmentHelperClass.closeFragment(fragment, methodNesting); // XXX - Need to change pageContext to jspContext if // we're not in a place where pageContext is defined (e.g. // in a fragment or in a tag file. out.print("new " + fragmentHelperClass.getClassName() + "( " + fragment.getId() + ", _jspx_page_context, " + tagHandlerVar + ", " + pushBodyCountVar + ")"); }
// in java/org/apache/jasper/compiler/Generator.java
public String generateNamedAttributeValue(Node.NamedAttribute n) throws JasperException { String varName = n.getTemporaryVariableName(); // If the only body element for this named attribute node is // template text, we need not generate an extra call to // pushBody and popBody. Maybe we can further optimize // here by getting rid of the temporary variable, but in // reality it looks like javac does this for us. Node.Nodes body = n.getBody(); if (body != null) { boolean templateTextOptimization = false; if (body.size() == 1) { Node bodyElement = body.getNode(0); if (bodyElement instanceof Node.TemplateText) { templateTextOptimization = true; out.printil("java.lang.String " + varName + " = " + quote(((Node.TemplateText) bodyElement) .getText()) + ";"); } } // XXX - Another possible optimization would be for // lone EL expressions (no need to pushBody here either). if (!templateTextOptimization) { out.printil("out = _jspx_page_context.pushBody();"); visitBody(n); out.printil("java.lang.String " + varName + " = " + "((javax.servlet.jsp.tagext.BodyContent)" + "out).getString();"); out.printil("out = _jspx_page_context.popBody();"); } } else { // Empty body must be treated as "" out.printil("java.lang.String " + varName + " = \"\";"); } return varName; }
// in java/org/apache/jasper/compiler/Generator.java
public String generateNamedAttributeJspFragment(Node.NamedAttribute n, String tagHandlerVar) throws JasperException { String varName = n.getTemporaryVariableName(); out.printin("javax.servlet.jsp.tagext.JspFragment " + varName + " = "); generateJspFragment(n, tagHandlerVar); out.println(";"); return varName; }
// in java/org/apache/jasper/compiler/Generator.java
private static void generateLocalVariables(ServletWriter out, Node n) throws JasperException { Node.ChildInfo ci; if (n instanceof Node.CustomTag) { ci = ((Node.CustomTag) n).getChildInfo(); } else if (n instanceof Node.JspBody) { ci = ((Node.JspBody) n).getChildInfo(); } else if (n instanceof Node.NamedAttribute) { ci = ((Node.NamedAttribute) n).getChildInfo(); } else { // Cannot access err since this method is static, but at // least flag an error. throw new JasperException("Unexpected Node Type"); // err.getString( // "jsp.error.internal.unexpected_node_type" ) ); } if (ci.hasUseBean()) { out.printil("javax.servlet.http.HttpSession session = _jspx_page_context.getSession();"); out.printil("javax.servlet.ServletContext application = _jspx_page_context.getServletContext();"); } if (ci.hasUseBean() || ci.hasIncludeAction() || ci.hasSetProperty() || ci.hasParamAction()) { out.printil("javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest)_jspx_page_context.getRequest();"); } if (ci.hasIncludeAction()) { out.printil("javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse)_jspx_page_context.getResponse();"); } }
// in java/org/apache/jasper/compiler/Generator.java
public static void generate(ServletWriter out, Compiler compiler, Node.Nodes page) throws JasperException { Generator gen = new Generator(out, compiler); if (gen.isPoolingEnabled) { gen.compileTagHandlerPoolList(page); } gen.generateCommentHeader(); if (gen.ctxt.isTagFile()) { JasperTagInfo tagInfo = (JasperTagInfo) gen.ctxt.getTagInfo(); gen.generateTagHandlerPreamble(tagInfo, page); if (gen.ctxt.isPrototypeMode()) { return; } gen.generateXmlProlog(page); gen.fragmentHelperClass.generatePreamble(); page.visit(gen.new GenerateVisitor(gen.ctxt.isTagFile(), out, gen.methodsBuffered, gen.fragmentHelperClass)); gen.generateTagHandlerPostamble(tagInfo); } else { gen.generatePreamble(page); gen.generateXmlProlog(page); gen.fragmentHelperClass.generatePreamble(); page.visit(gen.new GenerateVisitor(gen.ctxt.isTagFile(), out, gen.methodsBuffered, gen.fragmentHelperClass)); gen.generatePostamble(); } }
// in java/org/apache/jasper/compiler/Generator.java
private void generateTagHandlerPreamble(JasperTagInfo tagInfo, Node.Nodes tag) throws JasperException { // Generate package declaration String className = tagInfo.getTagClassName(); int lastIndex = className.lastIndexOf('.'); if (lastIndex != -1) { String pkgName = className.substring(0, lastIndex); genPreamblePackage(pkgName); className = className.substring(lastIndex + 1); } // Generate imports genPreambleImports(); // Generate class declaration out.printin("public final class "); out.println(className); out.printil(" extends javax.servlet.jsp.tagext.SimpleTagSupport"); out.printin(" implements org.apache.jasper.runtime.JspSourceDependent"); if (tagInfo.hasDynamicAttributes()) { out.println(","); out.printin(" javax.servlet.jsp.tagext.DynamicAttributes"); } out.println(" {"); out.println(); out.pushIndent(); /* * Class body begins here */ generateDeclarations(tag); // Static initializations here genPreambleStaticInitializers(); out.printil("private javax.servlet.jsp.JspContext jspContext;"); // Declare writer used for storing result of fragment/body invocation // if 'varReader' or 'var' attribute is specified out.printil("private java.io.Writer _jspx_sout;"); // Class variable declarations genPreambleClassVariableDeclarations(); generateSetJspContext(tagInfo); // Tag-handler specific declarations generateTagHandlerAttributes(tagInfo); if (tagInfo.hasDynamicAttributes()) generateSetDynamicAttribute(); // Methods here genPreambleMethods(); // Now the doTag() method out.printil("public void doTag() throws javax.servlet.jsp.JspException, java.io.IOException {"); if (ctxt.isPrototypeMode()) { out.printil("}"); out.popIndent(); out.printil("}"); return; } out.pushIndent(); /* * According to the spec, 'pageContext' must not be made available as an * implicit object in tag files. Declare _jspx_page_context, so we can * share the code generator with JSPs. */ out.printil("javax.servlet.jsp.PageContext _jspx_page_context = (javax.servlet.jsp.PageContext)jspContext;"); // Declare implicit objects. out.printil("javax.servlet.http.HttpServletRequest request = " + "(javax.servlet.http.HttpServletRequest) _jspx_page_context.getRequest();"); out.printil("javax.servlet.http.HttpServletResponse response = " + "(javax.servlet.http.HttpServletResponse) _jspx_page_context.getResponse();"); out.printil("javax.servlet.http.HttpSession session = _jspx_page_context.getSession();"); out.printil("javax.servlet.ServletContext application = _jspx_page_context.getServletContext();"); out.printil("javax.servlet.ServletConfig config = _jspx_page_context.getServletConfig();"); out.printil("javax.servlet.jsp.JspWriter out = jspContext.getOut();"); out.printil("_jspInit(config);"); // set current JspContext on ELContext out.printil("jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,jspContext);"); generatePageScopedVariables(tagInfo); declareTemporaryScriptingVars(tag); out.println(); out.printil("try {"); out.pushIndent(); }
// in java/org/apache/jasper/compiler/Generator.java
public void adjustJavaLines(final int offset) { if (node != null) { adjustJavaLine(node, offset); } if (body != null) { try { body.visit(new Node.Visitor() { @Override public void doVisit(Node n) { adjustJavaLine(n, offset); } @Override public void visit(Node.CustomTag n) throws JasperException { Node.Nodes b = n.getBody(); if (b != null && !b.isGeneratedInBuffer()) { // Don't adjust lines for the nested tags that // are also generated in buffers, because the // adjustments will be done elsewhere. b.visit(this); } } }); } catch (JasperException ex) { // Ignore } }
// in java/org/apache/jasper/compiler/Generator.java
Override public void visit(Node.CustomTag n) throws JasperException { Node.Nodes b = n.getBody(); if (b != null && !b.isGeneratedInBuffer()) { // Don't adjust lines for the nested tags that // are also generated in buffers, because the // adjustments will be done elsewhere. b.visit(this); } }
// in java/org/apache/jasper/compiler/Generator.java
public Fragment openFragment(Node parent, int methodNesting) throws JasperException { Fragment result = new Fragment(fragments.size(), parent); fragments.add(result); this.used = true; parent.setInnerClassName(className); ServletWriter out = result.getGenBuffer().getOut(); out.pushIndent(); out.pushIndent(); // XXX - Returns boolean because if a tag is invoked from // within this fragment, the Generator sometimes might // generate code like "return true". This is ignored for now, // meaning only the fragment is skipped. The JSR-152 // expert group is currently discussing what to do in this case. // See comment in closeFragment() if (methodNesting > 0) { out.printin("public boolean invoke"); } else { out.printin("public void invoke"); } out.println(result.getId() + "( " + "javax.servlet.jsp.JspWriter out ) "); out.pushIndent(); // Note: Throwable required because methods like _jspx_meth_* // throw Throwable. out.printil("throws java.lang.Throwable"); out.popIndent(); out.printil("{"); out.pushIndent(); generateLocalVariables(out, parent); return result; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
public static Node.Nodes parse( ParserController pc, String path, JarFile jarFile, Node parent, boolean isTagFile, boolean directivesOnly, String pageEnc, String jspConfigPageEnc, boolean isEncodingSpecifiedInProlog, boolean isBomPresent) throws JasperException { JspDocumentParser jspDocParser = new JspDocumentParser(pc, path, isTagFile, directivesOnly); Node.Nodes pageNodes = null; try { // Create dummy root and initialize it with given page encodings Node.Root dummyRoot = new Node.Root(null, parent, true); dummyRoot.setPageEncoding(pageEnc); dummyRoot.setJspConfigPageEncoding(jspConfigPageEnc); dummyRoot.setIsEncodingSpecifiedInProlog( isEncodingSpecifiedInProlog); dummyRoot.setIsBomPresent(isBomPresent); jspDocParser.current = dummyRoot; if (parent == null) { jspDocParser.addInclude( dummyRoot, jspDocParser.pageInfo.getIncludePrelude()); } else { jspDocParser.isTop = false; } // Parse the input SAXParser saxParser = getSAXParser(false, jspDocParser); InputStream inStream = null; try { inStream = JspUtil.getInputStream(path, jarFile, jspDocParser.ctxt); saxParser.parse(new InputSource(inStream), jspDocParser); } catch (EnableDTDValidationException e) { saxParser = getSAXParser(true, jspDocParser); jspDocParser.isValidating = true; if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } inStream = JspUtil.getInputStream(path, jarFile, jspDocParser.ctxt); saxParser.parse(new InputSource(inStream), jspDocParser); } finally { if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } } if (parent == null) { jspDocParser.addInclude( dummyRoot, jspDocParser.pageInfo.getIncludeCoda()); } // Create Node.Nodes from dummy root pageNodes = new Node.Nodes(dummyRoot); } catch (IOException ioe) { jspDocParser.err.jspError("jsp.error.data.file.read", path, ioe); } catch (SAXParseException e) { jspDocParser.err.jspError (new Mark(jspDocParser.ctxt, path, e.getLineNumber(), e.getColumnNumber()), e.getMessage()); } catch (Exception e) { jspDocParser.err.jspError(e); } return pageNodes; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private TagLibraryInfo getTaglibInfo(String prefix, String uri) throws JasperException { TagLibraryInfo result = null; if (uri.startsWith(URN_JSPTAGDIR)) { // uri (of the form "urn:jsptagdir:path") references tag file dir String tagdir = uri.substring(URN_JSPTAGDIR.length()); result = new ImplicitTagLibraryInfo( ctxt, parserController, pageInfo, prefix, tagdir, err); } else { // uri references TLD file boolean isPlainUri = false; if (uri.startsWith(URN_JSPTLD)) { // uri is of the form "urn:jsptld:path" uri = uri.substring(URN_JSPTLD.length()); } else { isPlainUri = true; } TldLocation location = ctxt.getTldLocation(uri); if (location != null || !isPlainUri) { if (ctxt.getOptions().isCaching()) { result = ctxt.getOptions().getCache().get(uri); } if (result == null) { /* * If the uri value is a plain uri, a translation error must * not be generated if the uri is not found in the taglib map. * Instead, any actions in the namespace defined by the uri * value must be treated as uninterpreted. */ result = new TagLibraryInfoImpl( ctxt, parserController, pageInfo, prefix, uri, location, err, null); if (ctxt.getOptions().isCaching()) { ctxt.getOptions().getCache().put(uri, result); } } } } return result; }
// in java/org/apache/jasper/compiler/TagPluginManager.java
public void apply(Node.Nodes page, ErrorDispatcher err, PageInfo pageInfo) throws JasperException { init(err); if (tagPlugins == null || tagPlugins.size() == 0) { return; } this.pageInfo = pageInfo; page.visit(new Node.Visitor() { @Override public void visit(Node.CustomTag n) throws JasperException { invokePlugin(n); visitBody(n); } }); }
// in java/org/apache/jasper/compiler/TagPluginManager.java
Override public void visit(Node.CustomTag n) throws JasperException { invokePlugin(n); visitBody(n); }
// in java/org/apache/jasper/compiler/TagPluginManager.java
private void init(ErrorDispatcher err) throws JasperException { if (initialized) return; InputStream is = ctxt.getResourceAsStream(TAG_PLUGINS_XML); if (is == null) return; TreeNode root = (new ParserUtils()).parseXMLDocument(TAG_PLUGINS_XML, is); if (root == null) { return; } if (!TAG_PLUGINS_ROOT_ELEM.equals(root.getName())) { err.jspError("jsp.error.plugin.wrongRootElement", TAG_PLUGINS_XML, TAG_PLUGINS_ROOT_ELEM); } tagPlugins = new HashMap<String, TagPlugin>(); Iterator<TreeNode> pluginList = root.findChildren("tag-plugin"); while (pluginList.hasNext()) { TreeNode pluginNode = pluginList.next(); TreeNode tagClassNode = pluginNode.findChild("tag-class"); if (tagClassNode == null) { // Error return; } String tagClass = tagClassNode.getBody().trim(); TreeNode pluginClassNode = pluginNode.findChild("plugin-class"); if (pluginClassNode == null) { // Error return; } String pluginClassStr = pluginClassNode.getBody(); TagPlugin tagPlugin = null; try { Class<?> pluginClass = Class.forName(pluginClassStr); tagPlugin = (TagPlugin) pluginClass.newInstance(); } catch (Exception e) { throw new JasperException(e); } if (tagPlugin == null) { return; } tagPlugins.put(tagClass, tagPlugin); } initialized = true; }
// in java/org/apache/jasper/compiler/ScriptingVariabler.java
Override public void visit(Node.CustomTag n) throws JasperException { n.setCustomTagParent(parent); Node.CustomTag tmpParent = parent; parent = n; visitBody(n); parent = tmpParent; n.setNumCount(new Integer(count++)); }
// in java/org/apache/jasper/compiler/ScriptingVariabler.java
Override public void visit(Node.CustomTag n) throws JasperException { setScriptingVars(n, VariableInfo.AT_BEGIN); setScriptingVars(n, VariableInfo.NESTED); visitBody(n); setScriptingVars(n, VariableInfo.AT_END); }
// in java/org/apache/jasper/compiler/ScriptingVariabler.java
private void setScriptingVars(Node.CustomTag n, int scope) throws JasperException { TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if (tagVarInfos.length == 0 && varInfos.length == 0) { return; } List<Object> vec = new ArrayList<Object>(); Integer ownRange = null; Node.CustomTag parent = n.getCustomTagParent(); if (scope == VariableInfo.AT_BEGIN || scope == VariableInfo.AT_END) { if (parent == null) ownRange = MAX_SCOPE; else ownRange = parent.getNumCount(); } else { // NESTED ownRange = n.getNumCount(); } if (varInfos.length > 0) { for (int i=0; i<varInfos.length; i++) { if (varInfos[i].getScope() != scope || !varInfos[i].getDeclare()) { continue; } String varName = varInfos[i].getVarName(); Integer currentRange = scriptVars.get(varName); if (currentRange == null || ownRange.compareTo(currentRange) > 0) { scriptVars.put(varName, ownRange); vec.add(varInfos[i]); } } } else { for (int i=0; i<tagVarInfos.length; i++) { if (tagVarInfos[i].getScope() != scope || !tagVarInfos[i].getDeclare()) { continue; } String varName = tagVarInfos[i].getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); if (varName == null) { err.jspError(n, "jsp.error.scripting.variable.missing_name", tagVarInfos[i].getNameFromAttribute()); } } Integer currentRange = scriptVars.get(varName); if (currentRange == null || ownRange.compareTo(currentRange) > 0) { scriptVars.put(varName, ownRange); vec.add(tagVarInfos[i]); } } } n.setScriptingVars(vec, scope); }
// in java/org/apache/jasper/compiler/ScriptingVariabler.java
public static void set(Node.Nodes page, ErrorDispatcher err) throws JasperException { page.visit(new CustomTagCounter()); page.visit(new ScriptingVariableVisitor(err)); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.Root n) throws JasperException { visitBody(n); if (n == root) { /* * Top-level page. * * Add * xmlns:jsp="http://java.sun.com/JSP/Page" * attribute only if not already present. */ if (!JSP_URI.equals(rootAttrs.getValue("xmlns:jsp"))) { rootAttrs.addAttribute("", "", "xmlns:jsp", "CDATA", JSP_URI); } if (pageInfo.isJspPrefixHijacked()) { /* * 'jsp' prefix has been hijacked, that is, bound to a * namespace other than the JSP namespace. This means that * when adding an 'id' attribute to each element, we can't * use the 'jsp' prefix. Therefore, create a new prefix * (one that is unique across the translation unit) for use * by the 'id' attribute, and bind it to the JSP namespace */ jspIdPrefix += "jsp"; while (pageInfo.containsPrefix(jspIdPrefix)) { jspIdPrefix += "jsp"; } rootAttrs.addAttribute("", "", "xmlns:" + jspIdPrefix, "CDATA", JSP_URI); } root.setAttributes(rootAttrs); } }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.JspRoot n) throws JasperException { addAttributes(n.getTaglibAttributes()); addAttributes(n.getNonTaglibXmlnsAttributes()); addAttributes(n.getAttributes()); visitBody(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.TaglibDirective n) throws JasperException { Attributes attrs = n.getAttributes(); if (attrs != null) { String qName = "xmlns:" + attrs.getValue("prefix"); /* * According to javadocs of org.xml.sax.helpers.AttributesImpl, * the addAttribute method does not check to see if the * specified attribute is already contained in the list: This * is the application's responsibility! */ if (rootAttrs.getIndex(qName) == -1) { String location = attrs.getValue("uri"); if (location != null) { if (location.startsWith("/")) { location = URN_JSPTLD + location; } rootAttrs.addAttribute("", "", qName, "CDATA", location); } else { location = attrs.getValue("tagdir"); rootAttrs.addAttribute("", "", qName, "CDATA", URN_JSPTAGDIR + location); } } } }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.Root n) throws JasperException { if (n == this.root) { // top-level page appendXmlProlog(); appendTag(n); } else { boolean resetDefaultNSSave = resetDefaultNS; if (n.isXmlSyntax()) { resetDefaultNS = true; } visitBody(n); resetDefaultNS = resetDefaultNSSave; } }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.JspRoot n) throws JasperException { visitBody(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.PageDirective n) throws JasperException { appendPageDirective(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.IncludeDirective n) throws JasperException { // expand in place visitBody(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.Comment n) throws JasperException { // Comments are ignored in XML view }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.Declaration n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.Expression n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.Scriptlet n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.JspElement n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.ELExpression n) throws JasperException { if (!n.getRoot().isXmlSyntax()) { buf.append("<").append(JSP_TEXT_ACTION); buf.append(" "); buf.append(jspIdPrefix); buf.append(":id=\""); buf.append(jspId++).append("\">"); } buf.append("${"); buf.append(JspUtil.escapeXml(n.getText())); buf.append("}"); if (!n.getRoot().isXmlSyntax()) { buf.append(JSP_TEXT_ACTION_END); } buf.append("\n"); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.IncludeAction n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.ForwardAction n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.GetProperty n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.SetProperty n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.ParamAction n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.ParamsAction n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.FallBackAction n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.UseBean n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.PlugIn n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.NamedAttribute n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.JspBody n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.CustomTag n) throws JasperException { boolean resetDefaultNSSave = resetDefaultNS; appendTag(n, resetDefaultNS); resetDefaultNS = resetDefaultNSSave; }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.UninterpretedTag n) throws JasperException { boolean resetDefaultNSSave = resetDefaultNS; appendTag(n, resetDefaultNS); resetDefaultNS = resetDefaultNSSave; }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.JspText n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.DoBodyAction n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.InvokeAction n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.TagDirective n) throws JasperException { appendTagDirective(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.AttributeDirective n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.VariableDirective n) throws JasperException { appendTag(n); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
Override public void visit(Node.TemplateText n) throws JasperException { /* * If the template text came from a JSP page written in JSP syntax, * create a jsp:text element for it (JSP 5.3.2). */ appendText(n.getText(), !n.getRoot().isXmlSyntax()); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
private void appendTag(Node n) throws JasperException { appendTag(n, false); }
// in java/org/apache/jasper/compiler/PageDataImpl.java
private void appendTag(Node n, boolean addDefaultNS) throws JasperException { Node.Nodes body = n.getBody(); String text = n.getText(); buf.append("<").append(n.getQName()); buf.append("\n"); printAttributes(n, addDefaultNS); buf.append(" ").append(jspIdPrefix).append(":id").append("=\""); buf.append(jspId++).append("\"\n"); if (ROOT_ACTION.equals(n.getLocalName()) || body != null || text != null) { buf.append(">\n"); if (ROOT_ACTION.equals(n.getLocalName())) { if (compiler.getCompilationContext().isTagFile()) { appendTagDirective(); } else { appendPageDirective(); } } if (body != null) { body.visit(this); } else { appendText(text, false); } buf.append("</" + n.getQName() + ">\n"); } else { buf.append("/>\n"); } }
// in java/org/apache/jasper/compiler/PageDataImpl.java
private void appendTagDirective(Node.TagDirective n) throws JasperException { boolean append = false; Attributes attrs = n.getAttributes(); int len = (attrs == null) ? 0 : attrs.getLength(); for (int i=0; i<len; i++) { @SuppressWarnings("null") // If attrs==null, len == 0 String attrName = attrs.getQName(i); if (!"pageEncoding".equals(attrName)) { append = true; break; } } if (!append) { return; } appendTag(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.IncludeDirective n) throws JasperException { // Since pageDirectiveSeen flag only applies to the Current page // save it here and restore it after the file is included. boolean pageEncodingSeenSave = pageEncodingSeen; pageEncodingSeen = false; visitBody(n); pageEncodingSeen = pageEncodingSeenSave; }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.PageDirective n) throws JasperException { JspUtil.checkAttributes("Page directive", n, pageDirectiveAttrs, err); // JSP.2.10.1 Attributes attrs = n.getAttributes(); for (int i = 0; attrs != null && i < attrs.getLength(); i++) { String attr = attrs.getQName(i); String value = attrs.getValue(i); if ("language".equals(attr)) { if (pageInfo.getLanguage(false) == null) { pageInfo.setLanguage(value, n, err, true); } else if (!pageInfo.getLanguage(false).equals(value)) { err.jspError(n, "jsp.error.page.conflict.language", pageInfo.getLanguage(false), value); } } else if ("extends".equals(attr)) { if (pageInfo.getExtends(false) == null) { pageInfo.setExtends(value, n); } else if (!pageInfo.getExtends(false).equals(value)) { err.jspError(n, "jsp.error.page.conflict.extends", pageInfo.getExtends(false), value); } } else if ("contentType".equals(attr)) { if (pageInfo.getContentType() == null) { pageInfo.setContentType(value); } else if (!pageInfo.getContentType().equals(value)) { err.jspError(n, "jsp.error.page.conflict.contenttype", pageInfo.getContentType(), value); } } else if ("session".equals(attr)) { if (pageInfo.getSession() == null) { pageInfo.setSession(value, n, err); } else if (!pageInfo.getSession().equals(value)) { err.jspError(n, "jsp.error.page.conflict.session", pageInfo.getSession(), value); } } else if ("buffer".equals(attr)) { if (pageInfo.getBufferValue() == null) { pageInfo.setBufferValue(value, n, err); } else if (!pageInfo.getBufferValue().equals(value)) { err.jspError(n, "jsp.error.page.conflict.buffer", pageInfo.getBufferValue(), value); } } else if ("autoFlush".equals(attr)) { if (pageInfo.getAutoFlush() == null) { pageInfo.setAutoFlush(value, n, err); } else if (!pageInfo.getAutoFlush().equals(value)) { err.jspError(n, "jsp.error.page.conflict.autoflush", pageInfo.getAutoFlush(), value); } } else if ("isThreadSafe".equals(attr)) { if (pageInfo.getIsThreadSafe() == null) { pageInfo.setIsThreadSafe(value, n, err); } else if (!pageInfo.getIsThreadSafe().equals(value)) { err.jspError(n, "jsp.error.page.conflict.isthreadsafe", pageInfo.getIsThreadSafe(), value); } } else if ("isELIgnored".equals(attr)) { if (pageInfo.getIsELIgnored() == null) { pageInfo.setIsELIgnored(value, n, err, true); } else if (!pageInfo.getIsELIgnored().equals(value)) { err.jspError(n, "jsp.error.page.conflict.iselignored", pageInfo.getIsELIgnored(), value); } } else if ("isErrorPage".equals(attr)) { if (pageInfo.getIsErrorPage() == null) { pageInfo.setIsErrorPage(value, n, err); } else if (!pageInfo.getIsErrorPage().equals(value)) { err.jspError(n, "jsp.error.page.conflict.iserrorpage", pageInfo.getIsErrorPage(), value); } } else if ("errorPage".equals(attr)) { if (pageInfo.getErrorPage() == null) { pageInfo.setErrorPage(value); } else if (!pageInfo.getErrorPage().equals(value)) { err.jspError(n, "jsp.error.page.conflict.errorpage", pageInfo.getErrorPage(), value); } } else if ("info".equals(attr)) { if (pageInfo.getInfo() == null) { pageInfo.setInfo(value); } else if (!pageInfo.getInfo().equals(value)) { err.jspError(n, "jsp.error.page.conflict.info", pageInfo.getInfo(), value); } } else if ("pageEncoding".equals(attr)) { if (pageEncodingSeen) err.jspError(n, "jsp.error.page.multi.pageencoding"); // 'pageEncoding' can occur at most once per file pageEncodingSeen = true; String actual = comparePageEncodings(value, n); n.getRoot().setPageEncoding(actual); } else if ("deferredSyntaxAllowedAsLiteral".equals(attr)) { if (pageInfo.getDeferredSyntaxAllowedAsLiteral() == null) { pageInfo.setDeferredSyntaxAllowedAsLiteral(value, n, err, true); } else if (!pageInfo.getDeferredSyntaxAllowedAsLiteral() .equals(value)) { err .jspError( n, "jsp.error.page.conflict.deferredsyntaxallowedasliteral", pageInfo .getDeferredSyntaxAllowedAsLiteral(), value); } } else if ("trimDirectiveWhitespaces".equals(attr)) { if (pageInfo.getTrimDirectiveWhitespaces() == null) { pageInfo.setTrimDirectiveWhitespaces(value, n, err, true); } else if (!pageInfo.getTrimDirectiveWhitespaces().equals( value)) { err .jspError( n, "jsp.error.page.conflict.trimdirectivewhitespaces", pageInfo.getTrimDirectiveWhitespaces(), value); } } } // Check for bad combinations if (pageInfo.getBuffer() == 0 && !pageInfo.isAutoFlush()) err.jspError(n, "jsp.error.page.badCombo"); // Attributes for imports for this node have been processed by // the parsers, just add them to pageInfo. pageInfo.addImports(n.getImports()); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.TagDirective n) throws JasperException { // Note: Most of the validation is done in TagFileProcessor // when it created a TagInfo object from the // tag file in which the directive appeared. // This method does additional processing to collect page info Attributes attrs = n.getAttributes(); for (int i = 0; attrs != null && i < attrs.getLength(); i++) { String attr = attrs.getQName(i); String value = attrs.getValue(i); if ("language".equals(attr)) { if (pageInfo.getLanguage(false) == null) { pageInfo.setLanguage(value, n, err, false); } else if (!pageInfo.getLanguage(false).equals(value)) { err.jspError(n, "jsp.error.tag.conflict.language", pageInfo.getLanguage(false), value); } } else if ("isELIgnored".equals(attr)) { if (pageInfo.getIsELIgnored() == null) { pageInfo.setIsELIgnored(value, n, err, false); } else if (!pageInfo.getIsELIgnored().equals(value)) { err.jspError(n, "jsp.error.tag.conflict.iselignored", pageInfo.getIsELIgnored(), value); } } else if ("pageEncoding".equals(attr)) { if (pageEncodingSeen) err.jspError(n, "jsp.error.tag.multi.pageencoding"); pageEncodingSeen = true; compareTagEncodings(value, n); n.getRoot().setPageEncoding(value); } else if ("deferredSyntaxAllowedAsLiteral".equals(attr)) { if (pageInfo.getDeferredSyntaxAllowedAsLiteral() == null) { pageInfo.setDeferredSyntaxAllowedAsLiteral(value, n, err, false); } else if (!pageInfo.getDeferredSyntaxAllowedAsLiteral() .equals(value)) { err .jspError( n, "jsp.error.tag.conflict.deferredsyntaxallowedasliteral", pageInfo .getDeferredSyntaxAllowedAsLiteral(), value); } } else if ("trimDirectiveWhitespaces".equals(attr)) { if (pageInfo.getTrimDirectiveWhitespaces() == null) { pageInfo.setTrimDirectiveWhitespaces(value, n, err, false); } else if (!pageInfo.getTrimDirectiveWhitespaces().equals( value)) { err .jspError( n, "jsp.error.tag.conflict.trimdirectivewhitespaces", pageInfo.getTrimDirectiveWhitespaces(), value); } } } // Attributes for imports for this node have been processed by // the parsers, just add them to pageInfo. pageInfo.addImports(n.getImports()); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.AttributeDirective n) throws JasperException { // Do nothing, since this attribute directive has already been // validated by TagFileProcessor when it created a TagInfo object // from the tag file in which the directive appeared }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.VariableDirective n) throws JasperException { // Do nothing, since this variable directive has already been // validated by TagFileProcessor when it created a TagInfo object // from the tag file in which the directive appeared }
// in java/org/apache/jasper/compiler/Validator.java
private String comparePageEncodings(String thePageDirEnc, Node.PageDirective pageDir) throws JasperException { Node.Root root = pageDir.getRoot(); String configEnc = root.getJspConfigPageEncoding(); String pageDirEnc = thePageDirEnc.toUpperCase(Locale.ENGLISH); /* * Compare the 'pageEncoding' attribute of the page directive with * the encoding specified in the JSP config element whose URL * pattern matches this page. Treat "UTF-16", "UTF-16BE", and * "UTF-16LE" as identical. */ if (configEnc != null) { configEnc = configEnc.toUpperCase(Locale.ENGLISH); if (!pageDirEnc.equals(configEnc) && (!pageDirEnc.startsWith("UTF-16") || !configEnc .startsWith("UTF-16"))) { err.jspError(pageDir, "jsp.error.config_pagedir_encoding_mismatch", configEnc, pageDirEnc); } else { return configEnc; } } /* * Compare the 'pageEncoding' attribute of the page directive with * the encoding specified in the XML prolog (only for XML syntax, * and only if JSP document contains XML prolog with encoding * declaration). Treat "UTF-16", "UTF-16BE", and "UTF-16LE" as * identical. */ if ((root.isXmlSyntax() && root.isEncodingSpecifiedInProlog()) || root.isBomPresent()) { String pageEnc = root.getPageEncoding().toUpperCase(Locale.ENGLISH); if (!pageDirEnc.equals(pageEnc) && (!pageDirEnc.startsWith("UTF-16") || !pageEnc .startsWith("UTF-16"))) { err.jspError(pageDir, "jsp.error.prolog_pagedir_encoding_mismatch", pageEnc, pageDirEnc); } else { return pageEnc; } } return pageDirEnc; }
// in java/org/apache/jasper/compiler/Validator.java
private void compareTagEncodings(String thePageDirEnc, Node.TagDirective pageDir) throws JasperException { Node.Root root = pageDir.getRoot(); String pageDirEnc = thePageDirEnc.toUpperCase(Locale.ENGLISH); /* * Compare the 'pageEncoding' attribute of the page directive with * the encoding specified in the XML prolog (only for XML syntax, * and only if JSP document contains XML prolog with encoding * declaration). Treat "UTF-16", "UTF-16BE", and "UTF-16LE" as * identical. */ if ((root.isXmlSyntax() && root.isEncodingSpecifiedInProlog()) || root.isBomPresent()) { String pageEnc = root.getPageEncoding().toUpperCase(Locale.ENGLISH); if (!pageDirEnc.equals(pageEnc) && (!pageDirEnc.startsWith("UTF-16") || !pageEnc .startsWith("UTF-16"))) { err.jspError(pageDir, "jsp.error.prolog_pagedir_encoding_mismatch", pageEnc, pageDirEnc); } } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.JspRoot n) throws JasperException { JspUtil.checkAttributes("Jsp:root", n, jspRootAttrs, err); String version = n.getTextAttribute("version"); if (!version.equals("1.2") && !version.equals("2.0") && !version.equals("2.1") && !version.equals("2.2")) { err.jspError(n, "jsp.error.jsproot.version.invalid", version); } visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.IncludeDirective n) throws JasperException { JspUtil.checkAttributes("Include directive", n, includeDirectiveAttrs, err); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.TaglibDirective n) throws JasperException { JspUtil.checkAttributes("Taglib directive", n, taglibDirectiveAttrs, err); // Either 'uri' or 'tagdir' attribute must be specified String uri = n.getAttributeValue("uri"); String tagdir = n.getAttributeValue("tagdir"); if (uri == null && tagdir == null) { err.jspError(n, "jsp.error.taglibDirective.missing.location"); } if (uri != null && tagdir != null) { err .jspError(n, "jsp.error.taglibDirective.both_uri_and_tagdir"); } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.ParamAction n) throws JasperException { JspUtil.checkAttributes("Param action", n, paramActionAttrs, err); // make sure the value of the 'name' attribute is not a // request-time expression throwErrorIfExpression(n, "name", "jsp:param"); n.setValue(getJspAttribute(null, "value", null, null, n .getAttributeValue("value"), n, false)); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.ParamsAction n) throws JasperException { // Make sure we've got at least one nested jsp:param Node.Nodes subElems = n.getBody(); if (subElems == null) { err.jspError(n, "jsp.error.params.emptyBody"); } visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.IncludeAction n) throws JasperException { JspUtil.checkAttributes("Include action", n, includeActionAttrs, err); n.setPage(getJspAttribute(null, "page", null, null, n .getAttributeValue("page"), n, false)); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.ForwardAction n) throws JasperException { JspUtil.checkAttributes("Forward", n, forwardActionAttrs, err); n.setPage(getJspAttribute(null, "page", null, null, n .getAttributeValue("page"), n, false)); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.GetProperty n) throws JasperException { JspUtil.checkAttributes("GetProperty", n, getPropertyAttrs, err); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.SetProperty n) throws JasperException { JspUtil.checkAttributes("SetProperty", n, setPropertyAttrs, err); String property = n.getTextAttribute("property"); String param = n.getTextAttribute("param"); String value = n.getAttributeValue("value"); n.setValue(getJspAttribute(null, "value", null, null, value, n, false)); boolean valueSpecified = n.getValue() != null; if ("*".equals(property)) { if (param != null || valueSpecified) err.jspError(n, "jsp.error.setProperty.invalid"); } else if (param != null && valueSpecified) { err.jspError(n, "jsp.error.setProperty.invalid"); } visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.UseBean n) throws JasperException { JspUtil.checkAttributes("UseBean", n, useBeanAttrs, err); String name = n.getTextAttribute("id"); String scope = n.getTextAttribute("scope"); JspUtil.checkScope(scope, n, err); String className = n.getTextAttribute("class"); String type = n.getTextAttribute("type"); BeanRepository beanInfo = pageInfo.getBeanRepository(); if (className == null && type == null) err.jspError(n, "jsp.error.usebean.missingType"); if (beanInfo.checkVariable(name)) err.jspError(n, "jsp.error.usebean.duplicate"); if ("session".equals(scope) && !pageInfo.isSession()) err.jspError(n, "jsp.error.usebean.noSession"); Node.JspAttribute jattr = getJspAttribute(null, "beanName", null, null, n.getAttributeValue("beanName"), n, false); n.setBeanName(jattr); if (className != null && jattr != null) err.jspError(n, "jsp.error.usebean.notBoth"); if (className == null) className = type; beanInfo.addBean(n, name, className, scope); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.PlugIn n) throws JasperException { JspUtil.checkAttributes("Plugin", n, plugInAttrs, err); throwErrorIfExpression(n, "type", "jsp:plugin"); throwErrorIfExpression(n, "code", "jsp:plugin"); throwErrorIfExpression(n, "codebase", "jsp:plugin"); throwErrorIfExpression(n, "align", "jsp:plugin"); throwErrorIfExpression(n, "archive", "jsp:plugin"); throwErrorIfExpression(n, "hspace", "jsp:plugin"); throwErrorIfExpression(n, "jreversion", "jsp:plugin"); throwErrorIfExpression(n, "name", "jsp:plugin"); throwErrorIfExpression(n, "vspace", "jsp:plugin"); throwErrorIfExpression(n, "nspluginurl", "jsp:plugin"); throwErrorIfExpression(n, "iepluginurl", "jsp:plugin"); String type = n.getTextAttribute("type"); if (type == null) err.jspError(n, "jsp.error.plugin.notype"); if (!type.equals("bean") && !type.equals("applet")) err.jspError(n, "jsp.error.plugin.badtype"); if (n.getTextAttribute("code") == null) err.jspError(n, "jsp.error.plugin.nocode"); Node.JspAttribute width = getJspAttribute(null, "width", null, null, n.getAttributeValue("width"), n, false); n.setWidth(width); Node.JspAttribute height = getJspAttribute(null, "height", null, null, n.getAttributeValue("height"), n, false); n.setHeight(height); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.NamedAttribute n) throws JasperException { JspUtil.checkAttributes("Attribute", n, attributeAttrs, err); n.setOmit(getJspAttribute(null, "omit", null, null, n .getAttributeValue("omit"), n, true)); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.JspBody n) throws JasperException { visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.Declaration n) throws JasperException { if (pageInfo.isScriptingInvalid()) { err.jspError(n.getStart(), "jsp.error.no.scriptlets"); } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.Expression n) throws JasperException { if (pageInfo.isScriptingInvalid()) { err.jspError(n.getStart(), "jsp.error.no.scriptlets"); } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.Scriptlet n) throws JasperException { if (pageInfo.isScriptingInvalid()) { err.jspError(n.getStart(), "jsp.error.no.scriptlets"); } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.ELExpression n) throws JasperException { // exit if we are ignoring EL all together if (pageInfo.isELIgnored()) return; // JSP.2.2 - '#{' not allowed in template text if (n.getType() == '#') { if (!pageInfo.isDeferredSyntaxAllowedAsLiteral()) { err.jspError(n, "jsp.error.el.template.deferred"); } else { return; } } // build expression StringBuilder expr = this.getBuffer(); expr.append(n.getType()).append('{').append(n.getText()) .append('}'); ELNode.Nodes el = ELParser.parse(expr.toString(), pageInfo .isDeferredSyntaxAllowedAsLiteral()); // validate/prepare expression prepareExpression(el, n, expr.toString()); // store it n.setEL(el); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.UninterpretedTag n) throws JasperException { if (n.getNamedAttributeNodes().size() != 0) { err.jspError(n, "jsp.error.namedAttribute.invalidUse"); } Attributes attrs = n.getAttributes(); if (attrs != null) { int attrSize = attrs.getLength(); Node.JspAttribute[] jspAttrs = new Node.JspAttribute[attrSize]; for (int i = 0; i < attrSize; i++) { // JSP.2.2 - '#{' not allowed in template text String value = attrs.getValue(i); if (!pageInfo.isDeferredSyntaxAllowedAsLiteral()) { if (containsDeferredSyntax(value)) { err.jspError(n, "jsp.error.el.template.deferred"); } } jspAttrs[i] = getJspAttribute(null, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), value, n, false); } n.setJspAttributes(jspAttrs); } visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.CustomTag n) throws JasperException { TagInfo tagInfo = n.getTagInfo(); if (tagInfo == null) { err.jspError(n, "jsp.error.missing.tagInfo", n.getQName()); } /* * The bodycontent of a SimpleTag cannot be JSP. */ if (n.implementsSimpleTag() && tagInfo.getBodyContent().equalsIgnoreCase( TagInfo.BODY_CONTENT_JSP)) { err.jspError(n, "jsp.error.simpletag.badbodycontent", tagInfo .getTagClassName()); } /* * If the tag handler declares in the TLD that it supports dynamic * attributes, it also must implement the DynamicAttributes * interface. */ if (tagInfo.hasDynamicAttributes() && !n.implementsDynamicAttributes()) { err.jspError(n, "jsp.error.dynamic.attributes.not.implemented", n.getQName()); } /* * Make sure all required attributes are present, either as * attributes or named attributes (<jsp:attribute>). Also make sure * that the same attribute is not specified in both attributes or * named attributes. */ TagAttributeInfo[] tldAttrs = tagInfo.getAttributes(); String customActionUri = n.getURI(); Attributes attrs = n.getAttributes(); int attrsSize = (attrs == null) ? 0 : attrs.getLength(); for (int i = 0; i < tldAttrs.length; i++) { String attr = null; if (attrs != null) { attr = attrs.getValue(tldAttrs[i].getName()); if (attr == null) { attr = attrs.getValue(customActionUri, tldAttrs[i] .getName()); } } Node.NamedAttribute na = n.getNamedAttributeNode(tldAttrs[i] .getName()); if (tldAttrs[i].isRequired() && attr == null && na == null) { err.jspError(n, "jsp.error.missing_attribute", tldAttrs[i] .getName(), n.getLocalName()); } if (attr != null && na != null) { err.jspError(n, "jsp.error.duplicate.name.jspattribute", tldAttrs[i].getName()); } } Node.Nodes naNodes = n.getNamedAttributeNodes(); int jspAttrsSize = naNodes.size() + attrsSize; Node.JspAttribute[] jspAttrs = null; if (jspAttrsSize > 0) { jspAttrs = new Node.JspAttribute[jspAttrsSize]; } Hashtable<String, Object> tagDataAttrs = new Hashtable<String, Object>(attrsSize); checkXmlAttributes(n, jspAttrs, tagDataAttrs); checkNamedAttributes(n, jspAttrs, attrsSize, tagDataAttrs); TagData tagData = new TagData(tagDataAttrs); // JSP.C1: It is a (translation time) error for an action that // has one or more variable subelements to have a TagExtraInfo // class that returns a non-null object. TagExtraInfo tei = tagInfo.getTagExtraInfo(); if (tei != null && tei.getVariableInfo(tagData) != null && tei.getVariableInfo(tagData).length > 0 && tagInfo.getTagVariableInfos().length > 0) { err.jspError("jsp.error.non_null_tei_and_var_subelems", n .getQName()); } n.setTagData(tagData); n.setJspAttributes(jspAttrs); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.JspElement n) throws JasperException { Attributes attrs = n.getAttributes(); if (attrs == null) { err.jspError(n, "jsp.error.jspelement.missing.name"); } @SuppressWarnings("null") // Exception will have been thrown above int xmlAttrLen = attrs.getLength(); Node.Nodes namedAttrs = n.getNamedAttributeNodes(); // XML-style 'name' attribute, which is mandatory, must not be // included in JspAttribute array int jspAttrSize = xmlAttrLen - 1 + namedAttrs.size(); Node.JspAttribute[] jspAttrs = new Node.JspAttribute[jspAttrSize]; int jspAttrIndex = 0; // Process XML-style attributes for (int i = 0; i < xmlAttrLen; i++) { if ("name".equals(attrs.getLocalName(i))) { n.setNameAttribute(getJspAttribute(null, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs .getValue(i), n, false)); } else { if (jspAttrIndex < jspAttrSize) { jspAttrs[jspAttrIndex++] = getJspAttribute(null, attrs .getQName(i), attrs.getURI(i), attrs .getLocalName(i), attrs.getValue(i), n, false); } } } if (n.getNameAttribute() == null) { err.jspError(n, "jsp.error.jspelement.missing.name"); } // Process named attributes for (int i = 0; i < namedAttrs.size(); i++) { Node.NamedAttribute na = (Node.NamedAttribute) namedAttrs .getNode(i); jspAttrs[jspAttrIndex++] = new Node.JspAttribute(na, null, false); } n.setJspAttributes(jspAttrs); visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.JspOutput n) throws JasperException { JspUtil.checkAttributes("jsp:output", n, jspOutputAttrs, err); if (n.getBody() != null) { err.jspError(n, "jsp.error.jspoutput.nonemptybody"); } String omitXmlDecl = n.getAttributeValue("omit-xml-declaration"); String doctypeName = n.getAttributeValue("doctype-root-element"); String doctypePublic = n.getAttributeValue("doctype-public"); String doctypeSystem = n.getAttributeValue("doctype-system"); String omitXmlDeclOld = pageInfo.getOmitXmlDecl(); String doctypeNameOld = pageInfo.getDoctypeName(); String doctypePublicOld = pageInfo.getDoctypePublic(); String doctypeSystemOld = pageInfo.getDoctypeSystem(); if (omitXmlDecl != null && omitXmlDeclOld != null && !omitXmlDecl.equals(omitXmlDeclOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "omit-xml-declaration", omitXmlDeclOld, omitXmlDecl); } if (doctypeName != null && doctypeNameOld != null && !doctypeName.equals(doctypeNameOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "doctype-root-element", doctypeNameOld, doctypeName); } if (doctypePublic != null && doctypePublicOld != null && !doctypePublic.equals(doctypePublicOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "doctype-public", doctypePublicOld, doctypePublic); } if (doctypeSystem != null && doctypeSystemOld != null && !doctypeSystem.equals(doctypeSystemOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "doctype-system", doctypeSystemOld, doctypeSystem); } if (doctypeName == null && doctypeSystem != null || doctypeName != null && doctypeSystem == null) { err.jspError(n, "jsp.error.jspoutput.doctypenamesystem"); } if (doctypePublic != null && doctypeSystem == null) { err.jspError(n, "jsp.error.jspoutput.doctypepulicsystem"); } if (omitXmlDecl != null) { pageInfo.setOmitXmlDecl(omitXmlDecl); } if (doctypeName != null) { pageInfo.setDoctypeName(doctypeName); } if (doctypeSystem != null) { pageInfo.setDoctypeSystem(doctypeSystem); } if (doctypePublic != null) { pageInfo.setDoctypePublic(doctypePublic); } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.InvokeAction n) throws JasperException { JspUtil.checkAttributes("Invoke", n, invokeAttrs, err); String scope = n.getTextAttribute("scope"); JspUtil.checkScope(scope, n, err); String var = n.getTextAttribute("var"); String varReader = n.getTextAttribute("varReader"); if (scope != null && var == null && varReader == null) { err.jspError(n, "jsp.error.missing_var_or_varReader"); } if (var != null && varReader != null) { err.jspError(n, "jsp.error.var_and_varReader"); } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.DoBodyAction n) throws JasperException { JspUtil.checkAttributes("DoBody", n, doBodyAttrs, err); String scope = n.getTextAttribute("scope"); JspUtil.checkScope(scope, n, err); String var = n.getTextAttribute("var"); String varReader = n.getTextAttribute("varReader"); if (scope != null && var == null && varReader == null) { err.jspError(n, "jsp.error.missing_var_or_varReader"); } if (var != null && varReader != null) { err.jspError(n, "jsp.error.var_and_varReader"); } }
// in java/org/apache/jasper/compiler/Validator.java
private void checkXmlAttributes(Node.CustomTag n, Node.JspAttribute[] jspAttrs, Hashtable<String, Object> tagDataAttrs) throws JasperException { TagInfo tagInfo = n.getTagInfo(); if (tagInfo == null) { err.jspError(n, "jsp.error.missing.tagInfo", n.getQName()); } TagAttributeInfo[] tldAttrs = tagInfo.getAttributes(); Attributes attrs = n.getAttributes(); for (int i = 0; attrs != null && i < attrs.getLength(); i++) { boolean found = false; boolean runtimeExpression = ((n.getRoot().isXmlSyntax() && attrs.getValue(i).startsWith("%=")) || (!n.getRoot().isXmlSyntax() && attrs.getValue(i).startsWith("<%="))); boolean elExpression = false; boolean deferred = false; double libraryVersion = Double.parseDouble( tagInfo.getTagLibrary().getRequiredVersion()); boolean deferredSyntaxAllowedAsLiteral = pageInfo.isDeferredSyntaxAllowedAsLiteral() || libraryVersion < 2.1; ELNode.Nodes el = null; if (!runtimeExpression && !pageInfo.isELIgnored()) { el = ELParser.parse(attrs.getValue(i), deferredSyntaxAllowedAsLiteral); Iterator<ELNode> nodes = el.iterator(); while (nodes.hasNext()) { ELNode node = nodes.next(); if (node instanceof ELNode.Root) { if (((ELNode.Root) node).getType() == '$') { if (elExpression && deferred) { err.jspError(n, "jsp.error.attribute.deferredmix"); } elExpression = true; } else if (((ELNode.Root) node).getType() == '#') { if (elExpression && !deferred) { err.jspError(n, "jsp.error.attribute.deferredmix"); } elExpression = true; deferred = true; } } } } boolean expression = runtimeExpression || elExpression; for (int j = 0; tldAttrs != null && j < tldAttrs.length; j++) { if (attrs.getLocalName(i).equals(tldAttrs[j].getName()) && (attrs.getURI(i) == null || attrs.getURI(i).length() == 0 || attrs .getURI(i).equals(n.getURI()))) { TagAttributeInfo tldAttr = tldAttrs[j]; if (tldAttr.canBeRequestTime() || tldAttr.isDeferredMethod() || tldAttr.isDeferredValue()) { // JSP 2.1 if (!expression) { String expectedType = null; if (tldAttr.isDeferredMethod()) { // The String literal must be castable to what is declared as type // for the attribute String m = tldAttr.getMethodSignature(); if (m != null) { m = m.trim(); int rti = m.indexOf(' '); if (rti > 0) { expectedType = m.substring(0, rti).trim(); } } else { expectedType = "java.lang.Object"; } if ("void".equals(expectedType)) { // Can't specify a literal for a // deferred method with an expected type // of void - JSP.2.3.4 err.jspError(n, "jsp.error.literal_with_void", tldAttr.getName()); } } if (tldAttr.isDeferredValue()) { // The String literal must be castable to what is declared as type // for the attribute expectedType = tldAttr.getExpectedTypeName(); } if (expectedType != null) { Class<?> expectedClass = String.class; try { expectedClass = JspUtil.toClass(expectedType, loader); } catch (ClassNotFoundException e) { err.jspError (n, "jsp.error.unknown_attribute_type", tldAttr.getName(), expectedType); } // Check casting - not possible for all types if (String.class.equals(expectedClass) || expectedClass == Long.TYPE || expectedClass == Double.TYPE || expectedClass == Byte.TYPE || expectedClass == Short.TYPE || expectedClass == Integer.TYPE || expectedClass == Float.TYPE || Number.class.isAssignableFrom(expectedClass) || Character.class.equals(expectedClass) || Character.TYPE == expectedClass || Boolean.class.equals(expectedClass) || Boolean.TYPE == expectedClass || expectedClass.isEnum()) { try { expressionFactory.coerceToType(attrs.getValue(i), expectedClass); } catch (Exception e) { err.jspError (n, "jsp.error.coerce_to_type", tldAttr.getName(), expectedType, attrs.getValue(i)); } } } jspAttrs[i] = new Node.JspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs .getLocalName(i), attrs.getValue(i), false, null, false); } else { if (deferred && !tldAttr.isDeferredMethod() && !tldAttr.isDeferredValue()) { // No deferred expressions allowed for this attribute err.jspError(n, "jsp.error.attribute.custom.non_rt_with_expr", tldAttr.getName()); } if (!deferred && !tldAttr.canBeRequestTime()) { // Only deferred expressions are allowed for this attribute err.jspError(n, "jsp.error.attribute.custom.non_rt_with_expr", tldAttr.getName()); } if (elExpression) { // El expression validateFunctions(el, n); jspAttrs[i] = new Node.JspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs.getValue(i), false, el, false); ELContextImpl ctx = new ELContextImpl(); ctx.setFunctionMapper(getFunctionMapper(el)); try { jspAttrs[i].validateEL(this.pageInfo.getExpressionFactory(), ctx); } catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", attrs.getValue(i), e.toString()); } } else { // Runtime expression jspAttrs[i] = getJspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs .getValue(i), n, false); } } } else { // Attribute does not accept any expressions. // Make sure its value does not contain any. if (expression) { err.jspError(n, "jsp.error.attribute.custom.non_rt_with_expr", tldAttr.getName()); } jspAttrs[i] = new Node.JspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs .getLocalName(i), attrs.getValue(i), false, null, false); } if (expression) { tagDataAttrs.put(attrs.getQName(i), TagData.REQUEST_TIME_VALUE); } else { tagDataAttrs.put(attrs.getQName(i), attrs .getValue(i)); } found = true; break; } } if (!found) { if (tagInfo.hasDynamicAttributes()) { jspAttrs[i] = getJspAttribute(null, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs .getValue(i), n, true); } else { err.jspError(n, "jsp.error.bad_attribute", attrs .getQName(i), n.getLocalName()); } } } }
// in java/org/apache/jasper/compiler/Validator.java
private void checkNamedAttributes(Node.CustomTag n, Node.JspAttribute[] jspAttrs, int start, Hashtable<String, Object> tagDataAttrs) throws JasperException { TagInfo tagInfo = n.getTagInfo(); if (tagInfo == null) { err.jspError(n, "jsp.error.missing.tagInfo", n.getQName()); } TagAttributeInfo[] tldAttrs = tagInfo.getAttributes(); Node.Nodes naNodes = n.getNamedAttributeNodes(); for (int i = 0; i < naNodes.size(); i++) { Node.NamedAttribute na = (Node.NamedAttribute) naNodes .getNode(i); boolean found = false; for (int j = 0; j < tldAttrs.length; j++) { /* * See above comment about namespace matches. For named * attributes, we use the prefix instead of URI as the match * criterion, because in the case of a JSP document, we'd * have to keep track of which namespaces are in scope when * parsing a named attribute, in order to determine the URI * that the prefix of the named attribute's name matches to. */ String attrPrefix = na.getPrefix(); if (na.getLocalName().equals(tldAttrs[j].getName()) && (attrPrefix == null || attrPrefix.length() == 0 || attrPrefix .equals(n.getPrefix()))) { jspAttrs[start + i] = new Node.JspAttribute(na, tldAttrs[j], false); NamedAttributeVisitor nav = null; if (na.getBody() != null) { nav = new NamedAttributeVisitor(); na.getBody().visit(nav); } if (nav != null && nav.hasDynamicContent()) { tagDataAttrs.put(na.getName(), TagData.REQUEST_TIME_VALUE); } else { tagDataAttrs.put(na.getName(), na.getText()); } found = true; break; } } if (!found) { if (tagInfo.hasDynamicAttributes()) { jspAttrs[start + i] = new Node.JspAttribute(na, null, true); } else { err.jspError(n, "jsp.error.bad_attribute", na.getName(), n.getLocalName()); } } } }
// in java/org/apache/jasper/compiler/Validator.java
private Node.JspAttribute getJspAttribute(TagAttributeInfo tai, String qName, String uri, String localName, String value, Node n, boolean dynamic) throws JasperException { Node.JspAttribute result = null; // XXX Is it an error to see "%=foo%" in non-Xml page? // (We won't see "<%=foo%> in xml page because '<' is not a // valid attribute value in xml). if (value != null) { if (n.getRoot().isXmlSyntax() && value.startsWith("%=")) { result = new Node.JspAttribute(tai, qName, uri, localName, value.substring(2, value.length() - 1), true, null, dynamic); } else if (!n.getRoot().isXmlSyntax() && value.startsWith("<%=")) { result = new Node.JspAttribute(tai, qName, uri, localName, value.substring(3, value.length() - 2), true, null, dynamic); } else if (pageInfo.isELIgnored()) { result = new Node.JspAttribute(tai, qName, uri, localName, value, false, null, dynamic); } else { // The attribute can contain expressions but is not a // scriptlet expression; thus, we want to run it through // the expression interpreter // validate expression syntax if string contains // expression(s) ELNode.Nodes el = ELParser.parse(value, pageInfo .isDeferredSyntaxAllowedAsLiteral()); if (el.containsEL()) { validateFunctions(el, n); result = new Node.JspAttribute(tai, qName, uri, localName, value, false, el, dynamic); ELContextImpl ctx = new ELContextImpl(); ctx.setFunctionMapper(getFunctionMapper(el)); try { result.validateEL(this.pageInfo .getExpressionFactory(), ctx); } catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", value, e .toString()); } } else { result = new Node.JspAttribute(tai, qName, uri, localName, value, false, null, dynamic); } } } else { // Value is null. Check for any NamedAttribute subnodes // that might contain the value for this attribute. // Otherwise, the attribute wasn't found so we return null. Node.NamedAttribute namedAttributeNode = n .getNamedAttributeNode(qName); if (namedAttributeNode != null) { result = new Node.JspAttribute(namedAttributeNode, tai, dynamic); } } return result; }
// in java/org/apache/jasper/compiler/Validator.java
private void throwErrorIfExpression(Node n, String attrName, String actionName) throws JasperException { if (n.getAttributes() != null && n.getAttributes().getValue(attrName) != null && isExpression(n, n.getAttributes().getValue(attrName), true)) { err.jspError(n, "jsp.error.attribute.standard.non_rt_with_expr", attrName, actionName); } }
// in java/org/apache/jasper/compiler/Validator.java
Override public void doVisit(Node n) throws JasperException { if (!(n instanceof Node.JspText) && !(n instanceof Node.TemplateText)) { hasDynamicContent = true; } visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
private void validateFunctions(ELNode.Nodes el, Node n) throws JasperException { class FVVisitor extends ELNode.Visitor { Node n; FVVisitor(Node n) { this.n = n; } @Override public void visit(ELNode.Function func) throws JasperException { String prefix = func.getPrefix(); String function = func.getName(); String uri = null; if (n.getRoot().isXmlSyntax()) { uri = findUri(prefix, n); } else if (prefix != null) { uri = pageInfo.getURI(prefix); } if (uri == null) { if (prefix == null) { err.jspError(n, "jsp.error.noFunctionPrefix", function); } else { err.jspError(n, "jsp.error.attribute.invalidPrefix", prefix); } } TagLibraryInfo taglib = pageInfo.getTaglib(uri); FunctionInfo funcInfo = null; if (taglib != null) { funcInfo = taglib.getFunction(function); } if (funcInfo == null) { err.jspError(n, "jsp.error.noFunction", function); } // Skip TLD function uniqueness check. Done by Schema ? func.setUri(uri); func.setFunctionInfo(funcInfo); processSignature(func); } } el.visit(new FVVisitor(n)); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(ELNode.Function func) throws JasperException { String prefix = func.getPrefix(); String function = func.getName(); String uri = null; if (n.getRoot().isXmlSyntax()) { uri = findUri(prefix, n); } else if (prefix != null) { uri = pageInfo.getURI(prefix); } if (uri == null) { if (prefix == null) { err.jspError(n, "jsp.error.noFunctionPrefix", function); } else { err.jspError(n, "jsp.error.attribute.invalidPrefix", prefix); } } TagLibraryInfo taglib = pageInfo.getTaglib(uri); FunctionInfo funcInfo = null; if (taglib != null) { funcInfo = taglib.getFunction(function); } if (funcInfo == null) { err.jspError(n, "jsp.error.noFunction", function); } // Skip TLD function uniqueness check. Done by Schema ? func.setUri(uri); func.setFunctionInfo(funcInfo); processSignature(func); }
// in java/org/apache/jasper/compiler/Validator.java
private void prepareExpression(ELNode.Nodes el, Node n, String expr) throws JasperException { validateFunctions(el, n); // test it out ELContextImpl ctx = new ELContextImpl(); ctx.setFunctionMapper(this.getFunctionMapper(el)); ExpressionFactory ef = this.pageInfo.getExpressionFactory(); try { ef.createValueExpression(ctx, expr, Object.class); } catch (ELException e) { } }
// in java/org/apache/jasper/compiler/Validator.java
private void processSignature(ELNode.Function func) throws JasperException { func.setMethodName(getMethod(func)); func.setParameters(getParameters(func)); }
// in java/org/apache/jasper/compiler/Validator.java
private String getMethod(ELNode.Function func) throws JasperException { FunctionInfo funcInfo = func.getFunctionInfo(); String signature = funcInfo.getFunctionSignature(); int start = signature.indexOf(' '); if (start < 0) { err.jspError("jsp.error.tld.fn.invalid.signature", func .getPrefix(), func.getName()); } int end = signature.indexOf('('); if (end < 0) { err.jspError( "jsp.error.tld.fn.invalid.signature.parenexpected", func.getPrefix(), func.getName()); } return signature.substring(start + 1, end).trim(); }
// in java/org/apache/jasper/compiler/Validator.java
private String[] getParameters(ELNode.Function func) throws JasperException { FunctionInfo funcInfo = func.getFunctionInfo(); String signature = funcInfo.getFunctionSignature(); ArrayList<String> params = new ArrayList<String>(); // Signature is of the form // <return-type> S <method-name S? '(' // < <arg-type> ( ',' <arg-type> )* )? ')' int start = signature.indexOf('(') + 1; boolean lastArg = false; while (true) { int p = signature.indexOf(',', start); if (p < 0) { p = signature.indexOf(')', start); if (p < 0) { err.jspError("jsp.error.tld.fn.invalid.signature", func .getPrefix(), func.getName()); } lastArg = true; } String arg = signature.substring(start, p).trim(); if (!"".equals(arg)) { params.add(arg); } if (lastArg) { break; } start = p + 1; } return params.toArray(new String[params.size()]); }
// in java/org/apache/jasper/compiler/Validator.java
private FunctionMapper getFunctionMapper(ELNode.Nodes el) throws JasperException { class ValidateFunctionMapper extends FunctionMapper { private HashMap<String, Method> fnmap = new HashMap<String, Method>(); public void mapFunction(String fnQName, Method method) { fnmap.put(fnQName, method); } @Override public Method resolveFunction(String prefix, String localName) { return this.fnmap.get(prefix + ":" + localName); } } class MapperELVisitor extends ELNode.Visitor { ValidateFunctionMapper fmapper; MapperELVisitor(ValidateFunctionMapper fmapper) { this.fmapper = fmapper; } @Override public void visit(ELNode.Function n) throws JasperException { Class<?> c = null; Method method = null; try { c = loader.loadClass(n.getFunctionInfo() .getFunctionClass()); } catch (ClassNotFoundException e) { err.jspError("jsp.error.function.classnotfound", n .getFunctionInfo().getFunctionClass(), n .getPrefix() + ':' + n.getName(), e.getMessage()); } String paramTypes[] = n.getParameters(); int size = paramTypes.length; Class<?> params[] = new Class[size]; int i = 0; try { for (i = 0; i < size; i++) { params[i] = JspUtil.toClass(paramTypes[i], loader); } method = c.getDeclaredMethod(n.getMethodName(), params); } catch (ClassNotFoundException e) { err.jspError("jsp.error.signature.classnotfound", paramTypes[i], n.getPrefix() + ':' + n.getName(), e.getMessage()); } catch (NoSuchMethodException e) { err.jspError("jsp.error.noFunctionMethod", n .getMethodName(), n.getName(), c.getName()); } fmapper.mapFunction(n.getPrefix() + ':' + n.getName(), method); } } ValidateFunctionMapper fmapper = new ValidateFunctionMapper(); el.visit(new MapperELVisitor(fmapper)); return fmapper; }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(ELNode.Function n) throws JasperException { Class<?> c = null; Method method = null; try { c = loader.loadClass(n.getFunctionInfo() .getFunctionClass()); } catch (ClassNotFoundException e) { err.jspError("jsp.error.function.classnotfound", n .getFunctionInfo().getFunctionClass(), n .getPrefix() + ':' + n.getName(), e.getMessage()); } String paramTypes[] = n.getParameters(); int size = paramTypes.length; Class<?> params[] = new Class[size]; int i = 0; try { for (i = 0; i < size; i++) { params[i] = JspUtil.toClass(paramTypes[i], loader); } method = c.getDeclaredMethod(n.getMethodName(), params); } catch (ClassNotFoundException e) { err.jspError("jsp.error.signature.classnotfound", paramTypes[i], n.getPrefix() + ':' + n.getName(), e.getMessage()); } catch (NoSuchMethodException e) { err.jspError("jsp.error.noFunctionMethod", n .getMethodName(), n.getName(), c.getName()); } fmapper.mapFunction(n.getPrefix() + ':' + n.getName(), method); }
// in java/org/apache/jasper/compiler/Validator.java
Override public void visit(Node.CustomTag n) throws JasperException { TagInfo tagInfo = n.getTagInfo(); if (tagInfo == null) { err.jspError(n, "jsp.error.missing.tagInfo", n.getQName()); } ValidationMessage[] errors = tagInfo.validate(n.getTagData()); if (errors != null && errors.length != 0) { StringBuilder errMsg = new StringBuilder(); errMsg.append("<h3>"); errMsg.append(Localizer.getMessage( "jsp.error.tei.invalid.attributes", n.getQName())); errMsg.append("</h3>"); for (int i = 0; i < errors.length; i++) { errMsg.append("<p>"); if (errors[i].getId() != null) { errMsg.append(errors[i].getId()); errMsg.append(": "); } errMsg.append(errors[i].getMessage()); errMsg.append("</p>"); } err.jspError(n, errMsg.toString()); } visitBody(n); }
// in java/org/apache/jasper/compiler/Validator.java
public static void validateDirectives(Compiler compiler, Node.Nodes page) throws JasperException { page.visit(new DirectiveVisitor(compiler)); }
// in java/org/apache/jasper/compiler/Validator.java
public static void validateExDirectives(Compiler compiler, Node.Nodes page) throws JasperException { // Determine the default output content type PageInfo pageInfo = compiler.getPageInfo(); String contentType = pageInfo.getContentType(); if (contentType == null || contentType.indexOf("charset=") < 0) { boolean isXml = page.getRoot().isXmlSyntax(); String defaultType; if (contentType == null) { defaultType = isXml ? "text/xml" : "text/html"; } else { defaultType = contentType; } String charset = null; if (isXml) { charset = "UTF-8"; } else { if (!page.getRoot().isDefaultPageEncoding()) { charset = page.getRoot().getPageEncoding(); } } if (charset != null) { pageInfo.setContentType(defaultType + ";charset=" + charset); } else { pageInfo.setContentType(defaultType); } } /* * Validate all other nodes. This validation step includes checking a * custom tag's mandatory and optional attributes against information in * the TLD (first validation step for custom tags according to * JSP.10.5). */ page.visit(new ValidateVisitor(compiler)); /* * Invoke TagLibraryValidator classes of all imported tags (second * validation step for custom tags according to JSP.10.5). */ validateXmlView(new PageDataImpl(page, compiler), compiler); /* * Invoke TagExtraInfo method isValid() for all imported tags (third * validation step for custom tags according to JSP.10.5). */ page.visit(new TagExtraInfoVisitor(compiler)); }
// in java/org/apache/jasper/compiler/Validator.java
private static void validateXmlView(PageData xmlView, Compiler compiler) throws JasperException { StringBuilder errMsg = null; ErrorDispatcher errDisp = compiler.getErrorDispatcher(); for (Iterator<TagLibraryInfo> iter = compiler.getPageInfo().getTaglibs().iterator(); iter.hasNext();) { Object o = iter.next(); if (!(o instanceof TagLibraryInfoImpl)) continue; TagLibraryInfoImpl tli = (TagLibraryInfoImpl) o; ValidationMessage[] errors = tli.validate(xmlView); if ((errors != null) && (errors.length != 0)) { if (errMsg == null) { errMsg = new StringBuilder(); } errMsg.append("<h3>"); errMsg.append(Localizer.getMessage( "jsp.error.tlv.invalid.page", tli.getShortName(), compiler.getPageInfo().getJspFile())); errMsg.append("</h3>"); for (int i = 0; i < errors.length; i++) { if (errors[i] != null) { errMsg.append("<p>"); errMsg.append(errors[i].getId()); errMsg.append(": "); errMsg.append(errors[i].getMessage()); errMsg.append("</p>"); } } } } if (errMsg != null) { errDisp.jspError(errMsg.toString()); } }
// in java/org/apache/jasper/compiler/Dumper.java
private void dumpBody(Node n) throws JasperException { Node.Nodes page = n.getBody(); if (page != null) { // indent++; page.visit(this); // indent--; } }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.PageDirective n) throws JasperException { printAttributes("<%@ page", n.getAttributes(), "%>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.TaglibDirective n) throws JasperException { printAttributes("<%@ taglib", n.getAttributes(), "%>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.IncludeDirective n) throws JasperException { printAttributes("<%@ include", n.getAttributes(), "%>"); dumpBody(n); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.Comment n) throws JasperException { printString("<%--", n.getText(), "--%>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.Declaration n) throws JasperException { printString("<%!", n.getText(), "%>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.Expression n) throws JasperException { printString("<%=", n.getText(), "%>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.Scriptlet n) throws JasperException { printString("<%", n.getText(), "%>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.IncludeAction n) throws JasperException { printAttributes("<jsp:include", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:include>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.ForwardAction n) throws JasperException { printAttributes("<jsp:forward", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:forward>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.GetProperty n) throws JasperException { printAttributes("<jsp:getProperty", n.getAttributes(), "/>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.SetProperty n) throws JasperException { printAttributes("<jsp:setProperty", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:setProperty>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.UseBean n) throws JasperException { printAttributes("<jsp:useBean", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:useBean>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.PlugIn n) throws JasperException { printAttributes("<jsp:plugin", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:plugin>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.ParamsAction n) throws JasperException { printAttributes("<jsp:params", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:params>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.ParamAction n) throws JasperException { printAttributes("<jsp:param", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:param>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.NamedAttribute n) throws JasperException { printAttributes("<jsp:attribute", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:attribute>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.JspBody n) throws JasperException { printAttributes("<jsp:body", n.getAttributes(), ">"); dumpBody(n); printString("</jsp:body>"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.ELExpression n) throws JasperException { printString( "${" + n.getText() + "}" ); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.CustomTag n) throws JasperException { printAttributes("<" + n.getQName(), n.getAttributes(), ">"); dumpBody(n); printString("</" + n.getQName() + ">"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.UninterpretedTag n) throws JasperException { String tag = n.getQName(); printAttributes("<"+tag, n.getAttributes(), ">"); dumpBody(n); printString("</" + tag + ">"); }
// in java/org/apache/jasper/compiler/Dumper.java
Override public void visit(Node.TemplateText n) throws JasperException { printString(n.getText()); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(String errCode) throws JasperException { dispatch(null, errCode, null, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Mark where, String errCode) throws JasperException { dispatch(where, errCode, null, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Node n, String errCode) throws JasperException { dispatch(n.getStart(), errCode, null, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(String errCode, String arg) throws JasperException { dispatch(null, errCode, new Object[] {arg}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Mark where, String errCode, String arg) throws JasperException { dispatch(where, errCode, new Object[] {arg}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Node n, String errCode, String arg) throws JasperException { dispatch(n.getStart(), errCode, new Object[] {arg}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(String errCode, String arg1, String arg2) throws JasperException { dispatch(null, errCode, new Object[] {arg1, arg2}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(String errCode, String arg1, String arg2, String arg3) throws JasperException { dispatch(null, errCode, new Object[] {arg1, arg2, arg3}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Mark where, String errCode, String arg1, String arg2) throws JasperException { dispatch(where, errCode, new Object[] {arg1, arg2}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Mark where, String errCode, String arg1, String arg2, String arg3) throws JasperException { dispatch(where, errCode, new Object[] {arg1, arg2, arg3}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Node n, String errCode, String arg1, String arg2) throws JasperException { dispatch(n.getStart(), errCode, new Object[] {arg1, arg2}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Node n, String errCode, String arg1, String arg2, String arg3) throws JasperException { dispatch(n.getStart(), errCode, new Object[] {arg1, arg2, arg3}, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Exception e) throws JasperException { dispatch(null, null, null, e); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(String errCode, String arg, Exception e) throws JasperException { dispatch(null, errCode, new Object[] {arg}, e); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void jspError(Node n, String errCode, String arg, Exception e) throws JasperException { dispatch(n.getStart(), errCode, new Object[] {arg}, e); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public static JavacErrorDetail[] parseJavacErrors(String errMsg, String fname, Node.Nodes page) throws JasperException, IOException { return parseJavacMessage(errMsg, fname, page); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void javacError(JavacErrorDetail[] javacErrors) throws JasperException { errHandler.javacError(javacErrors); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public void javacError(String errorReport, Exception e) throws JasperException { errHandler.javacError(errorReport, e); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
private void dispatch(Mark where, String errCode, Object[] args, Exception e) throws JasperException { String file = null; String errMsg = null; int line = -1; int column = -1; boolean hasLocation = false; // Localize if (errCode != null) { errMsg = Localizer.getMessage(errCode, args); } else if (e != null) { // give a hint about what's wrong errMsg = e.getMessage(); } // Get error location if (where != null) { if (jspcMode) { // Get the full URL of the resource that caused the error try { file = where.getURL().toString(); } catch (MalformedURLException me) { // Fallback to using context-relative path file = where.getFile(); } } else { // Get the context-relative resource path, so as to not // disclose any local filesystem details file = where.getFile(); } line = where.getLineNumber(); column = where.getColumnNumber(); hasLocation = true; } // Get nested exception Exception nestedEx = e; if ((e instanceof SAXException) && (((SAXException) e).getException() != null)) { nestedEx = ((SAXException) e).getException(); } if (hasLocation) { errHandler.jspError(file, line, column, errMsg, nestedEx); } else { errHandler.jspError(errMsg, nestedEx); } }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
private static JavacErrorDetail[] parseJavacMessage( String errMsg, String fname, Node.Nodes page) throws IOException, JasperException { ArrayList<JavacErrorDetail> errors = new ArrayList<JavacErrorDetail>(); StringBuilder errMsgBuf = null; int lineNum = -1; JavacErrorDetail javacError = null; BufferedReader reader = new BufferedReader(new StringReader(errMsg)); /* * Parse compilation errors. Each compilation error consists of a file * path and error line number, followed by a number of lines describing * the error. */ String line = null; while ((line = reader.readLine()) != null) { /* * Error line number is delimited by set of colons. * Ignore colon following drive letter on Windows (fromIndex = 2). * XXX Handle deprecation warnings that don't have line info */ int beginColon = line.indexOf(':', 2); int endColon = line.indexOf(':', beginColon + 1); if ((beginColon >= 0) && (endColon >= 0)) { if (javacError != null) { // add previous error to error vector errors.add(javacError); } String lineNumStr = line.substring(beginColon + 1, endColon); try { lineNum = Integer.parseInt(lineNumStr); } catch (NumberFormatException e) { lineNum = -1; } errMsgBuf = new StringBuilder(); javacError = createJavacError(fname, page, errMsgBuf, lineNum); } // Ignore messages preceding first error if (errMsgBuf != null) { errMsgBuf.append(line); errMsgBuf.append(Constants.NEWLINE); } } // Add last error to error vector if (javacError != null) { errors.add(javacError); } reader.close(); JavacErrorDetail[] errDetails = null; if (errors.size() > 0) { errDetails = new JavacErrorDetail[errors.size()]; errors.toArray(errDetails); } return errDetails; }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public static JavacErrorDetail createJavacError(String fname, Node.Nodes page, StringBuilder errMsgBuf, int lineNum) throws JasperException { return createJavacError(fname, page, errMsgBuf, lineNum, null); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
public static JavacErrorDetail createJavacError(String fname, Node.Nodes page, StringBuilder errMsgBuf, int lineNum, JspCompilationContext ctxt) throws JasperException { JavacErrorDetail javacError; // Attempt to map javac error line number to line in JSP page ErrorVisitor errVisitor = new ErrorVisitor(lineNum); page.visit(errVisitor); Node errNode = errVisitor.getJspSourceNode(); if ((errNode != null) && (errNode.getStart() != null)) { // If this is a scriplet node then there is a one to one mapping // between JSP lines and Java lines if (errVisitor.getJspSourceNode() instanceof Node.Scriptlet) { javacError = new JavacErrorDetail( fname, lineNum, errNode.getStart().getFile(), errNode.getStart().getLineNumber() + lineNum - errVisitor.getJspSourceNode().getBeginJavaLine(), errMsgBuf, ctxt); } else { javacError = new JavacErrorDetail( fname, lineNum, errNode.getStart().getFile(), errNode.getStart().getLineNumber(), errMsgBuf, ctxt); } } else { /* * javac error line number cannot be mapped to JSP page * line number. For example, this is the case if a * scriptlet is missing a closing brace, which causes * havoc with the try-catch-finally block that the code * generator places around all generated code: As a result * of this, the javac error line numbers will be outside * the range of begin and end java line numbers that were * generated for the scriptlet, and therefore cannot be * mapped to the start line number of the scriptlet in the * JSP page. * Include just the javac error info in the error detail. */ javacError = new JavacErrorDetail( fname, lineNum, errMsgBuf); } return javacError; }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
Override public void doVisit(Node n) throws JasperException { if ((lineNum >= n.getBeginJavaLine()) && (lineNum < n.getEndJavaLine())) { found = n; } }
// in java/org/apache/jasper/compiler/AntCompiler.java
Override protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception { long t1 = 0; if (log.isDebugEnabled()) { t1 = System.currentTimeMillis(); } String javaEncoding = ctxt.getOptions().getJavaEncoding(); String javaFileName = ctxt.getServletJavaFileName(); String classpath = ctxt.getClassPath(); String sep = System.getProperty("path.separator"); StringBuilder errorReport = new StringBuilder(); StringBuilder info=new StringBuilder(); info.append("Compile: javaFileName=" + javaFileName + "\n" ); info.append(" classpath=" + classpath + "\n" ); // Start capturing the System.err output for this thread SystemLogHandler.setThread(); // Initializing javac task getProject(); Javac javac = (Javac) project.createTask("javac"); // Initializing classpath Path path = new Path(project); path.setPath(System.getProperty("java.class.path")); info.append(" cp=" + System.getProperty("java.class.path") + "\n"); StringTokenizer tokenizer = new StringTokenizer(classpath, sep); while (tokenizer.hasMoreElements()) { String pathElement = tokenizer.nextToken(); File repository = new File(pathElement); path.setLocation(repository); info.append(" cp=" + repository + "\n"); } if( log.isDebugEnabled() ) log.debug( "Using classpath: " + System.getProperty("java.class.path") + sep + classpath); // Initializing sourcepath Path srcPath = new Path(project); srcPath.setLocation(options.getScratchDir()); info.append(" work dir=" + options.getScratchDir() + "\n"); // Initialize and set java extensions String exts = System.getProperty("java.ext.dirs"); if (exts != null) { Path extdirs = new Path(project); extdirs.setPath(exts); javac.setExtdirs(extdirs); info.append(" extension dir=" + exts + "\n"); } // Add endorsed directories if any are specified and we're forking // See Bugzilla 31257 if(ctxt.getOptions().getFork()) { String endorsed = System.getProperty("java.endorsed.dirs"); if(endorsed != null) { Javac.ImplementationSpecificArgument endorsedArg = javac.createCompilerArg(); endorsedArg.setLine("-J-Djava.endorsed.dirs=" + quotePathList(endorsed)); info.append(" endorsed dir=" + quotePathList(endorsed) + "\n"); } else { info.append(" no endorsed dirs specified\n"); } } // Configure the compiler object javac.setEncoding(javaEncoding); javac.setClasspath(path); javac.setDebug(ctxt.getOptions().getClassDebugInfo()); javac.setSrcdir(srcPath); javac.setTempdir(options.getScratchDir()); javac.setOptimize(! ctxt.getOptions().getClassDebugInfo() ); javac.setFork(ctxt.getOptions().getFork()); info.append(" srcDir=" + srcPath + "\n" ); // Set the Java compiler to use if (options.getCompiler() != null) { javac.setCompiler(options.getCompiler()); info.append(" compiler=" + options.getCompiler() + "\n"); } if (options.getCompilerTargetVM() != null) { javac.setTarget(options.getCompilerTargetVM()); info.append(" compilerTargetVM=" + options.getCompilerTargetVM() + "\n"); } if (options.getCompilerSourceVM() != null) { javac.setSource(options.getCompilerSourceVM()); info.append(" compilerSourceVM=" + options.getCompilerSourceVM() + "\n"); } // Build includes path PatternSet.NameEntry includes = javac.createInclude(); includes.setName(ctxt.getJavaPath()); info.append(" include="+ ctxt.getJavaPath() + "\n" ); BuildException be = null; try { if (ctxt.getOptions().getFork()) { javac.execute(); } else { synchronized(javacLock) { javac.execute(); } } } catch (BuildException e) { be = e; log.error(Localizer.getMessage("jsp.error.javac"), e); log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString()); } errorReport.append(logger.getReport()); // Stop capturing the System.err output for this thread String errorCapture = SystemLogHandler.unsetThread(); if (errorCapture != null) { errorReport.append(Constants.NEWLINE); errorReport.append(errorCapture); } if (!ctxt.keepGenerated()) { File javaFile = new File(javaFileName); javaFile.delete(); } if (be != null) { String errorReportString = errorReport.toString(); log.error(Localizer.getMessage("jsp.error.compilation", javaFileName, errorReportString)); JavacErrorDetail[] javacErrors = ErrorDispatcher.parseJavacErrors( errorReportString, javaFileName, pageNodes); if (javacErrors != null) { errDispatcher.javacError(javacErrors); } else { errDispatcher.javacError(errorReportString, be); } } if( log.isDebugEnabled() ) { long t2 = System.currentTimeMillis(); log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2-t1) + "ms"); } logger = null; project = null; if (ctxt.isPrototypeMode()) { return; } // JSR45 Support if (! options.isSmapSuppressed()) { SmapUtil.installSmap(smap); } }
// in java/org/apache/jasper/compiler/JspConfig.java
private void processWebDotXml() throws JasperException { WebXml webXml = null; try { webXml = new WebXml(ctxt); TreeNode webApp = null; if (webXml.getInputSource() != null) { ParserUtils pu = new ParserUtils(); webApp = pu.parseXMLDocument(webXml.getSystemId(), webXml.getInputSource()); } if (webApp == null || getVersion(webApp) < 2.4) { defaultIsELIgnored = "true"; defaultDeferedSyntaxAllowedAsLiteral = "true"; return; } if (getVersion(webApp) < 2.5) { defaultDeferedSyntaxAllowedAsLiteral = "true"; } TreeNode jspConfig = webApp.findChild("jsp-config"); if (jspConfig == null) { return; } jspProperties = new Vector<JspPropertyGroup>(); Iterator<TreeNode> jspPropertyList = jspConfig.findChildren("jsp-property-group"); while (jspPropertyList.hasNext()) { TreeNode element = jspPropertyList.next(); Iterator<TreeNode> list = element.findChildren(); Vector<String> urlPatterns = new Vector<String>(); String pageEncoding = null; String scriptingInvalid = null; String elIgnored = null; String isXml = null; Vector<String> includePrelude = new Vector<String>(); Vector<String> includeCoda = new Vector<String>(); String deferredSyntaxAllowedAsLiteral = null; String trimDirectiveWhitespaces = null; String defaultContentType = null; String buffer = null; String errorOnUndeclaredNamespace = null; while (list.hasNext()) { element = list.next(); String tname = element.getName(); if ("url-pattern".equals(tname)) urlPatterns.addElement( element.getBody() ); else if ("page-encoding".equals(tname)) pageEncoding = element.getBody(); else if ("is-xml".equals(tname)) isXml = element.getBody(); else if ("el-ignored".equals(tname)) elIgnored = element.getBody(); else if ("scripting-invalid".equals(tname)) scriptingInvalid = element.getBody(); else if ("include-prelude".equals(tname)) includePrelude.addElement(element.getBody()); else if ("include-coda".equals(tname)) includeCoda.addElement(element.getBody()); else if ("deferred-syntax-allowed-as-literal".equals(tname)) deferredSyntaxAllowedAsLiteral = element.getBody(); else if ("trim-directive-whitespaces".equals(tname)) trimDirectiveWhitespaces = element.getBody(); else if ("default-content-type".equals(tname)) defaultContentType = element.getBody(); else if ("buffer".equals(tname)) buffer = element.getBody(); else if ("error-on-undeclared-namespace".equals(tname)) errorOnUndeclaredNamespace = element.getBody(); } if (urlPatterns.size() == 0) { continue; } // Add one JspPropertyGroup for each URL Pattern. This makes // the matching logic easier. for( int p = 0; p < urlPatterns.size(); p++ ) { String urlPattern = urlPatterns.elementAt( p ); String path = null; String extension = null; if (urlPattern.indexOf('*') < 0) { // Exact match path = urlPattern; } else { int i = urlPattern.lastIndexOf('/'); String file; if (i >= 0) { path = urlPattern.substring(0,i+1); file = urlPattern.substring(i+1); } else { file = urlPattern; } // pattern must be "*", or of the form "*.jsp" if (file.equals("*")) { extension = "*"; } else if (file.startsWith("*.")) { extension = file.substring(file.indexOf('.')+1); } // The url patterns are reconstructed as the following: // path != null, extension == null: / or /foo/bar.ext // path == null, extension != null: *.ext // path != null, extension == "*": /foo/* boolean isStar = "*".equals(extension); if ((path == null && (extension == null || isStar)) || (path != null && !isStar)) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage( "jsp.warning.bad.urlpattern.propertygroup", urlPattern)); } continue; } } JspProperty property = new JspProperty(isXml, elIgnored, scriptingInvalid, pageEncoding, includePrelude, includeCoda, deferredSyntaxAllowedAsLiteral, trimDirectiveWhitespaces, defaultContentType, buffer, errorOnUndeclaredNamespace); JspPropertyGroup propertyGroup = new JspPropertyGroup(path, extension, property); jspProperties.addElement(propertyGroup); } } } catch (Exception ex) { throw new JasperException(ex); } finally { if (webXml != null) { webXml.close(); } } }
// in java/org/apache/jasper/compiler/JspConfig.java
private void init() throws JasperException { if (!initialized) { synchronized (this) { if (!initialized) { processWebDotXml(); defaultJspProperty = new JspProperty(defaultIsXml, defaultIsELIgnored, defaultIsScriptingInvalid, null, null, null, defaultDeferedSyntaxAllowedAsLiteral, defaultTrimDirectiveWhitespaces, defaultDefaultContentType, defaultBuffer, defaultErrorOnUndeclaredNamespace); initialized = true; } } } }
// in java/org/apache/jasper/compiler/JspConfig.java
public JspProperty findJspProperty(String uri) throws JasperException { init(); // JSP Configuration settings do not apply to tag files if (jspProperties == null || uri.endsWith(".tag") || uri.endsWith(".tagx")) { return defaultJspProperty; } String uriPath = null; int index = uri.lastIndexOf('/'); if (index >=0 ) { uriPath = uri.substring(0, index+1); } String uriExtension = null; index = uri.lastIndexOf('.'); if (index >=0) { uriExtension = uri.substring(index+1); } Vector<String> includePreludes = new Vector<String>(); Vector<String> includeCodas = new Vector<String>(); JspPropertyGroup isXmlMatch = null; JspPropertyGroup elIgnoredMatch = null; JspPropertyGroup scriptingInvalidMatch = null; JspPropertyGroup pageEncodingMatch = null; JspPropertyGroup deferedSyntaxAllowedAsLiteralMatch = null; JspPropertyGroup trimDirectiveWhitespacesMatch = null; JspPropertyGroup defaultContentTypeMatch = null; JspPropertyGroup bufferMatch = null; JspPropertyGroup errorOnUndeclaredNamespaceMatch = null; Iterator<JspPropertyGroup> iter = jspProperties.iterator(); while (iter.hasNext()) { JspPropertyGroup jpg = iter.next(); JspProperty jp = jpg.getJspProperty(); // (arrays will be the same length) String extension = jpg.getExtension(); String path = jpg.getPath(); if (extension == null) { // exact match pattern: /a/foo.jsp if (!uri.equals(path)) { // not matched; continue; } } else { // Matching patterns *.ext or /p/* if (path != null && uriPath != null && ! uriPath.startsWith(path)) { // not matched continue; } if (!extension.equals("*") && !extension.equals(uriExtension)) { // not matched continue; } } // We have a match // Add include-preludes and include-codas if (jp.getIncludePrelude() != null) { includePreludes.addAll(jp.getIncludePrelude()); } if (jp.getIncludeCoda() != null) { includeCodas.addAll(jp.getIncludeCoda()); } // If there is a previous match for the same property, remember // the one that is more restrictive. if (jp.isXml() != null) { isXmlMatch = selectProperty(isXmlMatch, jpg); } if (jp.isELIgnored() != null) { elIgnoredMatch = selectProperty(elIgnoredMatch, jpg); } if (jp.isScriptingInvalid() != null) { scriptingInvalidMatch = selectProperty(scriptingInvalidMatch, jpg); } if (jp.getPageEncoding() != null) { pageEncodingMatch = selectProperty(pageEncodingMatch, jpg); } if (jp.isDeferedSyntaxAllowedAsLiteral() != null) { deferedSyntaxAllowedAsLiteralMatch = selectProperty(deferedSyntaxAllowedAsLiteralMatch, jpg); } if (jp.isTrimDirectiveWhitespaces() != null) { trimDirectiveWhitespacesMatch = selectProperty(trimDirectiveWhitespacesMatch, jpg); } if (jp.getDefaultContentType() != null) { defaultContentTypeMatch = selectProperty(defaultContentTypeMatch, jpg); } if (jp.getBuffer() != null) { bufferMatch = selectProperty(bufferMatch, jpg); } if (jp.isErrorOnUndeclaredNamespace() != null) { errorOnUndeclaredNamespaceMatch = selectProperty(errorOnUndeclaredNamespaceMatch, jpg); } } String isXml = defaultIsXml; String isELIgnored = defaultIsELIgnored; String isScriptingInvalid = defaultIsScriptingInvalid; String pageEncoding = null; String isDeferedSyntaxAllowedAsLiteral = defaultDeferedSyntaxAllowedAsLiteral; String isTrimDirectiveWhitespaces = defaultTrimDirectiveWhitespaces; String defaultContentType = defaultDefaultContentType; String buffer = defaultBuffer; String errorOnUndelcaredNamespace = defaultErrorOnUndeclaredNamespace; if (isXmlMatch != null) { isXml = isXmlMatch.getJspProperty().isXml(); } if (elIgnoredMatch != null) { isELIgnored = elIgnoredMatch.getJspProperty().isELIgnored(); } if (scriptingInvalidMatch != null) { isScriptingInvalid = scriptingInvalidMatch.getJspProperty().isScriptingInvalid(); } if (pageEncodingMatch != null) { pageEncoding = pageEncodingMatch.getJspProperty().getPageEncoding(); } if (deferedSyntaxAllowedAsLiteralMatch != null) { isDeferedSyntaxAllowedAsLiteral = deferedSyntaxAllowedAsLiteralMatch.getJspProperty().isDeferedSyntaxAllowedAsLiteral(); } if (trimDirectiveWhitespacesMatch != null) { isTrimDirectiveWhitespaces = trimDirectiveWhitespacesMatch.getJspProperty().isTrimDirectiveWhitespaces(); } if (defaultContentTypeMatch != null) { defaultContentType = defaultContentTypeMatch.getJspProperty().getDefaultContentType(); } if (bufferMatch != null) { buffer = bufferMatch.getJspProperty().getBuffer(); } if (errorOnUndeclaredNamespaceMatch != null) { errorOnUndelcaredNamespace = errorOnUndeclaredNamespaceMatch.getJspProperty().isErrorOnUndeclaredNamespace(); } return new JspProperty(isXml, isELIgnored, isScriptingInvalid, pageEncoding, includePreludes, includeCodas, isDeferedSyntaxAllowedAsLiteral, isTrimDirectiveWhitespaces, defaultContentType, buffer, errorOnUndelcaredNamespace); }
// in java/org/apache/jasper/compiler/JspConfig.java
public boolean isJspPage(String uri) throws JasperException { init(); if (jspProperties == null) { return false; } String uriPath = null; int index = uri.lastIndexOf('/'); if (index >=0 ) { uriPath = uri.substring(0, index+1); } String uriExtension = null; index = uri.lastIndexOf('.'); if (index >=0) { uriExtension = uri.substring(index+1); } Iterator<JspPropertyGroup> iter = jspProperties.iterator(); while (iter.hasNext()) { JspPropertyGroup jpg = iter.next(); String extension = jpg.getExtension(); String path = jpg.getPath(); if (extension == null) { if (uri.equals(path)) { // There is an exact match return true; } } else { if ((path == null || path.equals(uriPath)) && (extension.equals("*") || extension.equals(uriExtension))) { // Matches *, *.ext, /p/*, or /p/*.ext return true; } } } return false; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public Class<?> loadTagFile() throws JasperException { try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; ctxt.compile(); } } else { if (compileException != null) { throw compileException; } } if (reload) { tagHandlerClass = ctxt.load(); reload = false; } } catch (FileNotFoundException ex) { throw new JasperException(ex); } return tagHandlerClass; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public Class<?> loadTagFilePrototype() throws JasperException { ctxt.setPrototypeMode(true); try { return loadTagFile(); } finally { ctxt.setPrototypeMode(false); } }
// in java/org/apache/jasper/JspCompilationContext.java
public TldLocation getTldLocation(String uri) throws JasperException { TldLocation location = getOptions().getTldLocationsCache().getLocation(uri); return location; }
// in java/org/apache/jasper/JspCompilationContext.java
public void compile() throws JasperException, FileNotFoundException { createCompiler(); if (jspCompiler.isOutDated()) { if (isRemoved()) { throw new FileNotFoundException(jspUri); } try { jspCompiler.removeGeneratedFiles(); jspLoader = null; jspCompiler.compile(); jsw.setReload(true); jsw.setCompilationException(null); } catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; } catch (FileNotFoundException fnfe) { // Re-throw to let caller handle this - will result in a 404 throw fnfe; } catch (Exception ex) { JasperException je = new JasperException( Localizer.getMessage("jsp.error.unable.compile"), ex); // Cache compilation exception jsw.setCompilationException(je); throw je; } } }
// in java/org/apache/jasper/JspCompilationContext.java
public Class<?> load() throws JasperException { try { getJspLoader(); String name = getFQCN(); servletClass = jspLoader.loadClass(name); } catch (ClassNotFoundException cex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.load"), cex); } catch (Exception ex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); } removed = 0; return servletClass; }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
public TreeNode parseXMLDocument(String location, InputSource is) throws JasperException { Document document = null; // Perform an XML parse of this document, via JAXP try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(validating); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(entityResolver); builder.setErrorHandler(errorHandler); document = builder.parse(is); } catch (ParserConfigurationException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), ex); } catch (SAXParseException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); } catch (SAXException sx) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), sx); } catch (IOException io) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), io); } // Convert the resulting document to a graph of TreeNodes return (convert(null, document.getDocumentElement())); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
public TreeNode parseXMLDocument(String uri, InputStream is) throws JasperException { return (parseXMLDocument(uri, new InputSource(is))); }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public static Object[] getEncoding(String fname, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err) throws IOException, JasperException { InputStream inStream = JspUtil.getInputStream(fname, jarFile, ctxt); XMLEncodingDetector detector = new XMLEncodingDetector(); Object[] ret = detector.getEncoding(inStream, err); inStream.close(); return ret; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private Object[] getEncoding(InputStream in, ErrorDispatcher err) throws IOException, JasperException { this.stream = in; this.err=err; createInitialReader(); scanXMLDecl(); return new Object[] { this.encoding, Boolean.valueOf(this.isEncodingSetInProlog), Boolean.valueOf(this.isBomPresent), Integer.valueOf(this.skip) }; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void createInitialReader() throws IOException, JasperException { // wrap this stream in RewindableInputStream stream = new RewindableInputStream(stream); // perform auto-detect of encoding if necessary if (encoding == null) { // read first four bytes and determine encoding final byte[] b4 = new byte[4]; int count = 0; for (; count<4; count++ ) { b4[count] = (byte)stream.read(); } if (count == 4) { Object [] encodingDesc = getEncodingName(b4, count); encoding = (String)(encodingDesc[0]); isBigEndian = (Boolean)(encodingDesc[1]); if (encodingDesc.length > 3) { isBomPresent = ((Boolean)(encodingDesc[2])).booleanValue(); skip = ((Integer)(encodingDesc[3])).intValue(); } else { isBomPresent = true; skip = ((Integer)(encodingDesc[2])).intValue(); } stream.reset(); // Special case UTF-8 files with BOM created by Microsoft // tools. It's more efficient to consume the BOM than make // the reader perform extra checks. -Ac if (count > 2 && encoding.equals("UTF-8")) { int b0 = b4[0] & 0xFF; int b1 = b4[1] & 0xFF; int b2 = b4[2] & 0xFF; if (b0 == 0xEF && b1 == 0xBB && b2 == 0xBF) { // ignore first three bytes... long skipped = stream.skip(3); if (skipped != 3) { throw new IOException(Localizer.getMessage( "xmlParser.skipBomFail")); } } } reader = createReader(stream, encoding, isBigEndian); } else { reader = createReader(stream, encoding, isBigEndian); } } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private Reader createReader(InputStream inputStream, String encoding, Boolean isBigEndian) throws IOException, JasperException { // normalize encoding name if (encoding == null) { encoding = "UTF-8"; } // try to use an optimized reader String ENCODING = encoding.toUpperCase(Locale.ENGLISH); if (ENCODING.equals("UTF-8")) { return new UTF8Reader(inputStream, fBufferSize); } if (ENCODING.equals("US-ASCII")) { return new ASCIIReader(inputStream, fBufferSize); } if (ENCODING.equals("ISO-10646-UCS-4")) { if (isBigEndian != null) { boolean isBE = isBigEndian.booleanValue(); if (isBE) { return new UCSReader(inputStream, UCSReader.UCS4BE); } else { return new UCSReader(inputStream, UCSReader.UCS4LE); } } else { err.jspError("jsp.error.xml.encodingByteOrderUnsupported", encoding); } } if (ENCODING.equals("ISO-10646-UCS-2")) { if (isBigEndian != null) { // sould never happen with this encoding... boolean isBE = isBigEndian.booleanValue(); if (isBE) { return new UCSReader(inputStream, UCSReader.UCS2BE); } else { return new UCSReader(inputStream, UCSReader.UCS2LE); } } else { err.jspError("jsp.error.xml.encodingByteOrderUnsupported", encoding); } } // check for valid name boolean validIANA = XMLChar.isValidIANAEncoding(encoding); boolean validJava = XMLChar.isValidJavaEncoding(encoding); if (!validIANA || (fAllowJavaEncodings && !validJava)) { err.jspError("jsp.error.xml.encodingDeclInvalid", encoding); // NOTE: AndyH suggested that, on failure, we use ISO Latin 1 // because every byte is a valid ISO Latin 1 character. // It may not translate correctly but if we failed on // the encoding anyway, then we're expecting the content // of the document to be bad. This will just prevent an // invalid UTF-8 sequence to be detected. This is only // important when continue-after-fatal-error is turned // on. -Ac encoding = "ISO-8859-1"; } // try to use a Java reader String javaEncoding = EncodingMap.getIANA2JavaMapping(ENCODING); if (javaEncoding == null) { if (fAllowJavaEncodings) { javaEncoding = encoding; } else { err.jspError("jsp.error.xml.encodingDeclInvalid", encoding); // see comment above. javaEncoding = "ISO8859_1"; } } return new InputStreamReader(inputStream, javaEncoding); }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanXMLDecl() throws IOException, JasperException { if (skipString("<?xml")) { // NOTE: special case where document starts with a PI // whose name starts with "xml" (e.g. "xmlfoo") if (XMLChar.isName(peekChar())) { fStringBuffer.clear(); fStringBuffer.append("xml"); while (XMLChar.isName(peekChar())) { fStringBuffer.append((char)scanChar()); } String target = fSymbolTable.addSymbol(fStringBuffer.ch, fStringBuffer.offset, fStringBuffer.length); scanPIData(target, fString); } // standard XML declaration else { scanXMLDeclOrTextDecl(false); } } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanXMLDeclOrTextDecl(boolean scanningTextDecl) throws IOException, JasperException { // scan decl scanXMLDeclOrTextDecl(scanningTextDecl, fStrings); // pseudo-attribute values String encodingPseudoAttr = fStrings[1]; // set encoding on reader if (encodingPseudoAttr != null) { isEncodingSetInProlog = true; encoding = encodingPseudoAttr; } }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanXMLDeclOrTextDecl(boolean scanningTextDecl, String[] pseudoAttributeValues) throws IOException, JasperException { // pseudo-attribute values String version = null; String encoding = null; String standalone = null; // scan pseudo-attributes final int STATE_VERSION = 0; final int STATE_ENCODING = 1; final int STATE_STANDALONE = 2; final int STATE_DONE = 3; int state = STATE_VERSION; boolean dataFoundForTarget = false; boolean sawSpace = skipSpaces(); while (peekChar() != '?') { dataFoundForTarget = true; String name = scanPseudoAttribute(scanningTextDecl, fString); switch (state) { case STATE_VERSION: { if (name == fVersionSymbol) { if (!sawSpace) { reportFatalError(scanningTextDecl ? "jsp.error.xml.spaceRequiredBeforeVersionInTextDecl" : "jsp.error.xml.spaceRequiredBeforeVersionInXMLDecl", null); } version = fString.toString(); state = STATE_ENCODING; if (!version.equals("1.0")) { // REVISIT: XML REC says we should throw an error // in such cases. // some may object the throwing of fatalError. err.jspError("jsp.error.xml.versionNotSupported", version); } } else if (name == fEncodingSymbol) { if (!scanningTextDecl) { err.jspError("jsp.error.xml.versionInfoRequired"); } if (!sawSpace) { reportFatalError(scanningTextDecl ? "jsp.error.xml.spaceRequiredBeforeEncodingInTextDecl" : "jsp.error.xml.spaceRequiredBeforeEncodingInXMLDecl", null); } encoding = fString.toString(); state = scanningTextDecl ? STATE_DONE : STATE_STANDALONE; } else { if (scanningTextDecl) { err.jspError("jsp.error.xml.encodingDeclRequired"); } else { err.jspError("jsp.error.xml.versionInfoRequired"); } } break; } case STATE_ENCODING: { if (name == fEncodingSymbol) { if (!sawSpace) { reportFatalError(scanningTextDecl ? "jsp.error.xml.spaceRequiredBeforeEncodingInTextDecl" : "jsp.error.xml.spaceRequiredBeforeEncodingInXMLDecl", null); } encoding = fString.toString(); state = scanningTextDecl ? STATE_DONE : STATE_STANDALONE; // TODO: check encoding name; set encoding on // entity scanner } else if (!scanningTextDecl && name == fStandaloneSymbol) { if (!sawSpace) { err.jspError("jsp.error.xml.spaceRequiredBeforeStandalone"); } standalone = fString.toString(); state = STATE_DONE; if (!standalone.equals("yes") && !standalone.equals("no")) { err.jspError("jsp.error.xml.sdDeclInvalid"); } } else { err.jspError("jsp.error.xml.encodingDeclRequired"); } break; } case STATE_STANDALONE: { if (name == fStandaloneSymbol) { if (!sawSpace) { err.jspError("jsp.error.xml.spaceRequiredBeforeStandalone"); } standalone = fString.toString(); state = STATE_DONE; if (!standalone.equals("yes") && !standalone.equals("no")) { err.jspError("jsp.error.xml.sdDeclInvalid"); } } else { err.jspError("jsp.error.xml.encodingDeclRequired"); } break; } default: { err.jspError("jsp.error.xml.noMorePseudoAttributes"); } } sawSpace = skipSpaces(); } // REVISIT: should we remove this error reporting? if (scanningTextDecl && state != STATE_DONE) { err.jspError("jsp.error.xml.morePseudoAttributes"); } // If there is no data in the xml or text decl then we fail to report // error for version or encoding info above. if (scanningTextDecl) { if (!dataFoundForTarget && encoding == null) { err.jspError("jsp.error.xml.encodingDeclRequired"); } } else { if (!dataFoundForTarget && version == null) { err.jspError("jsp.error.xml.versionInfoRequired"); } } // end if (!skipChar('?')) { err.jspError("jsp.error.xml.xmlDeclUnterminated"); } if (!skipChar('>')) { err.jspError("jsp.error.xml.xmlDeclUnterminated"); } // fill in return array pseudoAttributeValues[0] = version; pseudoAttributeValues[1] = encoding; pseudoAttributeValues[2] = standalone; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
public String scanPseudoAttribute(boolean scanningTextDecl, XMLString value) throws IOException, JasperException { String name = scanName(); if (name == null) { err.jspError("jsp.error.xml.pseudoAttrNameExpected"); } skipSpaces(); if (!skipChar('=')) { reportFatalError(scanningTextDecl ? "jsp.error.xml.eqRequiredInTextDecl" : "jsp.error.xml.eqRequiredInXMLDecl", name); } skipSpaces(); int quote = peekChar(); if (quote != '\'' && quote != '"') { reportFatalError(scanningTextDecl ? "jsp.error.xml.quoteRequiredInTextDecl" : "jsp.error.xml.quoteRequiredInXMLDecl" , name); } scanChar(); int c = scanLiteral(quote, value); if (c != quote) { fStringBuffer2.clear(); do { fStringBuffer2.append(value); if (c != -1) { if (c == '&' || c == '%' || c == '<' || c == ']') { fStringBuffer2.append((char)scanChar()); } else if (XMLChar.isHighSurrogate(c)) { scanSurrogates(fStringBuffer2); } else if (XMLChar.isInvalid(c)) { String key = scanningTextDecl ? "jsp.error.xml.invalidCharInTextDecl" : "jsp.error.xml.invalidCharInXMLDecl"; reportFatalError(key, Integer.toString(c, 16)); scanChar(); } } c = scanLiteral(quote, value); } while (c != quote); fStringBuffer2.append(value); value.setValues(fStringBuffer2); } if (!skipChar(quote)) { reportFatalError(scanningTextDecl ? "jsp.error.xml.closeQuoteMissingInTextDecl" : "jsp.error.xml.closeQuoteMissingInXMLDecl", name); } // return return name; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void scanPIData(String target, XMLString data) throws IOException, JasperException { // check target if (target.length() == 3) { char c0 = Character.toLowerCase(target.charAt(0)); char c1 = Character.toLowerCase(target.charAt(1)); char c2 = Character.toLowerCase(target.charAt(2)); if (c0 == 'x' && c1 == 'm' && c2 == 'l') { err.jspError("jsp.error.xml.reservedPITarget"); } } // spaces if (!skipSpaces()) { if (skipString("?>")) { // we found the end, there is no data data.clear(); return; } else { // if there is data there should be some space err.jspError("jsp.error.xml.spaceRequiredInPI"); } } fStringBuffer.clear(); // data if (scanData("?>", fStringBuffer)) { do { int c = peekChar(); if (c != -1) { if (XMLChar.isHighSurrogate(c)) { scanSurrogates(fStringBuffer); } else if (XMLChar.isInvalid(c)) { err.jspError("jsp.error.xml.invalidCharInPI", Integer.toHexString(c)); scanChar(); } } } while (scanData("?>", fStringBuffer)); } data.setValues(fStringBuffer); }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private boolean scanSurrogates(XMLStringBuffer buf) throws IOException, JasperException { int high = scanChar(); int low = peekChar(); if (!XMLChar.isLowSurrogate(low)) { err.jspError("jsp.error.xml.invalidCharInContent", Integer.toString(high, 16)); return false; } scanChar(); // convert surrogates to supplemental character int c = XMLChar.supplemental((char)high, (char)low); // supplemental character must be a valid XML character if (!XMLChar.isValid(c)) { err.jspError("jsp.error.xml.invalidCharInContent", Integer.toString(c, 16)); return false; } // fill in the buffer buf.append((char)high); buf.append((char)low); return true; }
// in java/org/apache/jasper/xmlparser/XMLEncodingDetector.java
private void reportFatalError(String msgId, String arg) throws JasperException { err.jspError(msgId, arg); }
// in java/org/apache/jasper/JspC.java
public void setArgs(String[] arg) throws JasperException { args = arg; String tok; dieLevel = NO_DIE_LEVEL; while ((tok = nextArg()) != null) { if (tok.equals(SWITCH_VERBOSE)) { verbose = true; showSuccess = true; listErrors = true; } else if (tok.equals(SWITCH_OUTPUT_DIR)) { tok = nextArg(); setOutputDir( tok ); } else if (tok.equals(SWITCH_PACKAGE_NAME)) { targetPackage = nextArg(); } else if (tok.equals(SWITCH_COMPILE)) { compile=true; } else if (tok.equals(SWITCH_CLASS_NAME)) { targetClassName = nextArg(); } else if (tok.equals(SWITCH_URI_BASE)) { uriBase=nextArg(); } else if (tok.equals(SWITCH_URI_ROOT)) { setUriroot( nextArg()); } else if (tok.equals(SWITCH_FILE_WEBAPP)) { setUriroot( nextArg()); } else if ( tok.equals( SHOW_SUCCESS ) ) { showSuccess = true; } else if ( tok.equals( LIST_ERRORS ) ) { listErrors = true; } else if (tok.equals(SWITCH_WEBAPP_INC)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = INC_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = ALL_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML_ENCODING)) { setWebXmlEncoding(nextArg()); } else if (tok.equals(SWITCH_ADD_WEBAPP_XML_MAPPINGS)) { setAddWebXmlMappings(true); } else if (tok.equals(SWITCH_MAPPED)) { mappedFile = true; } else if (tok.equals(SWITCH_XPOWERED_BY)) { xpoweredBy = true; } else if (tok.equals(SWITCH_TRIM_SPACES)) { setTrimSpaces(true); } else if (tok.equals(SWITCH_CACHE)) { tok = nextArg(); if ("false".equals(tok)) { caching = false; } else { caching = true; } } else if (tok.equals(SWITCH_CLASSPATH)) { setClassPath(nextArg()); } else if (tok.startsWith(SWITCH_DIE)) { try { dieLevel = Integer.parseInt( tok.substring(SWITCH_DIE.length())); } catch (NumberFormatException nfe) { dieLevel = DEFAULT_DIE_LEVEL; } } else if (tok.equals(SWITCH_HELP)) { helpNeeded = true; } else if (tok.equals(SWITCH_POOLING)) { tok = nextArg(); if ("false".equals(tok)) { poolingEnabled = false; } else { poolingEnabled = true; } } else if (tok.equals(SWITCH_ENCODING)) { setJavaEncoding(nextArg()); } else if (tok.equals(SWITCH_SOURCE)) { setCompilerSourceVM(nextArg()); } else if (tok.equals(SWITCH_TARGET)) { setCompilerTargetVM(nextArg()); } else if (tok.equals(SWITCH_SMAP)) { smapSuppressed = false; } else if (tok.equals(SWITCH_DUMP_SMAP)) { smapDumped = true; } else { if (tok.startsWith("-")) { throw new JasperException("Unrecognized option: " + tok + ". Use -help for help."); } if (!fullstop) { argPos--; } // Start treating the rest as JSP Pages break; } } // Add all extra arguments to the list of files while( true ) { String file = nextFile(); if( file==null ) { break; } pages.add( file ); } }
// in java/org/apache/jasper/JspC.java
protected void processFile(String file) throws JasperException { if (log.isDebugEnabled()) { log.debug("Processing file: " + file); } ClassLoader originalClassLoader = null; try { // set up a scratch/output dir if none is provided if (scratchDir == null) { String temp = System.getProperty("java.io.tmpdir"); if (temp == null) { temp = ""; } scratchDir = new File(new File(temp).getAbsolutePath()); } String jspUri=file.replace('\\','/'); JspCompilationContext clctxt = new JspCompilationContext ( jspUri, this, context, null, rctxt ); /* Override the defaults */ if ((targetClassName != null) && (targetClassName.length() > 0)) { clctxt.setServletClassName(targetClassName); targetClassName = null; } if (targetPackage != null) { clctxt.setServletPackageName(targetPackage); } originalClassLoader = Thread.currentThread().getContextClassLoader(); if( loader==null ) { initClassLoader( clctxt ); } Thread.currentThread().setContextClassLoader(loader); clctxt.setClassLoader(loader); clctxt.setClassPath(classPath); Compiler clc = clctxt.createCompiler(); // If compile is set, generate both .java and .class, if // .jsp file is newer than .class file; // Otherwise only generate .java, if .jsp file is newer than // the .java file if( clc.isOutDated(compile) ) { if (log.isDebugEnabled()) { log.debug(jspUri + " is out dated, compiling..."); } clc.compile(compile, true); } // Generate mapping generateWebMapping( file, clctxt ); if ( showSuccess ) { log.info( "Built File: " + file ); } } catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } } catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); } finally { if(originalClassLoader != null) { Thread.currentThread().setContextClassLoader(originalClassLoader); } } }
// in java/org/apache/jasper/JspC.java
public void scanFiles( File base ) throws JasperException { Stack<String> dirs = new Stack<String>(); dirs.push(base.toString()); // Make sure default extensions are always included if ((getExtensions() == null) || (getExtensions().size() < 2)) { addExtension("jsp"); addExtension("jspx"); } while (!dirs.isEmpty()) { String s = dirs.pop(); File f = new File(s); if (f.exists() && f.isDirectory()) { String[] files = f.list(); String ext; for (int i = 0; (files != null) && i < files.length; i++) { File f2 = new File(s, files[i]); if (f2.isDirectory()) { dirs.push(f2.getPath()); } else { String path = f2.getPath(); String uri = path.substring(uriRoot.length()); ext = files[i].substring(files[i].lastIndexOf('.') +1); if (getExtensions().contains(ext) || jspConfig.isJspPage(uri)) { pages.add(path); } } } } }
// in java/org/apache/jasper/JspC.java
public void execute() throws JasperException { if(log.isDebugEnabled()) { log.debug("execute() starting for " + pages.size() + " pages."); } try { if (uriRoot == null) { if( pages.size() == 0 ) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.missingTarget")); } String firstJsp = pages.get( 0 ); File firstJspF = new File( firstJsp ); if (!firstJspF.exists()) { throw new JasperException( Localizer.getMessage("jspc.error.fileDoesNotExist", firstJsp)); } locateUriRoot( firstJspF ); } if (uriRoot == null) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.no_uriroot")); } File uriRootF = new File(uriRoot); if (!uriRootF.isDirectory()) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.uriroot_not_dir")); } if(context == null) { initServletContext(); } // No explicit pages, we'll process all .jsp in the webapp if (pages.size() == 0) { scanFiles(uriRootF); } initWebXml(); Iterator<String> iter = pages.iterator(); while (iter.hasNext()) { String nextjsp = iter.next().toString(); File fjsp = new File(nextjsp); if (!fjsp.isAbsolute()) { fjsp = new File(uriRootF, nextjsp); } if (!fjsp.exists()) { if (log.isWarnEnabled()) { log.warn (Localizer.getMessage ("jspc.error.fileDoesNotExist", fjsp.toString())); } continue; } String s = fjsp.getAbsolutePath(); if (s.startsWith(uriRoot)) { nextjsp = s.substring(uriRoot.length()); } if (nextjsp.startsWith("." + File.separatorChar)) { nextjsp = nextjsp.substring(2); } processFile(nextjsp); } completeWebXml(); if (addWebXmlMappings) { mergeIntoWebXml(); } } catch (IOException ioe) { throw new JasperException(ioe); } catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { rootCause.printStackTrace(); } throw je; } finally { if (loader != null) { LogFactory.release(loader); } } }
14
            
// in java/org/apache/jasper/compiler/SmapUtil.java
catch (JasperException ex) { }
// in java/org/apache/jasper/compiler/SmapUtil.java
catch (JasperException ex) { }
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
catch (JasperException je) { throw new RuntimeException(je.toString(), je); }
// in java/org/apache/jasper/compiler/Node.java
catch (JasperException e) { }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (JasperException e) { // Hack - makes exception handling simpler throw new IOException(e); }
// in java/org/apache/jasper/compiler/JDTCompiler.java
catch (JasperException e) { log.error("Error visiting node", e); }
// in java/org/apache/jasper/compiler/Generator.java
catch (JasperException ex) { // Ignore }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (JasperException je) { throw new SAXParseException( Localizer.getMessage("jsp.error.could.not.add.taglibraries"), locator, je); }
// in java/org/apache/jasper/compiler/Dumper.java
catch (JasperException e) { e.printStackTrace(); }
// in java/org/apache/jasper/compiler/Dumper.java
catch (JasperException e) { e.printStackTrace(); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { System.err.println(je); if (jspc.dieLevel != NO_DIE_LEVEL) { System.exit(jspc.dieLevel); } }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { rootCause.printStackTrace(); } throw je; }
6
            
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
catch (JasperException je) { throw new RuntimeException(je.toString(), je); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (JasperException e) { // Hack - makes exception handling simpler throw new IOException(e); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (JasperException je) { throw new SAXParseException( Localizer.getMessage("jsp.error.could.not.add.taglibraries"), locator, je); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } }
// in java/org/apache/jasper/JspC.java
catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { rootCause.printStackTrace(); } throw je; }
1
runtime (Domain) JspELException
public class JspELException extends ELException {

    private static final long serialVersionUID = 1L;

    public JspELException(String mark, ELException e) {
        super(mark + " " + e.getMessage(), e.getCause());
    }
}
6
            
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public MethodInfo getMethodInfo(ELContext context) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.getMethodInfo(context); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public Object invoke(ELContext context, Object[] params) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.invoke(context, params); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Class<?> getType(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getType(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public boolean isReadOnly(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.isReadOnly(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void setValue(ELContext context, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { try { this.target.setValue(context, value); } catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Object getValue(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getValue(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
6
            
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); }
0 0 0 0
checked (Domain) JspException
public class JspException extends Exception {

    private static final long serialVersionUID = 1L;


    /**
     * Construct a JspException.
     */
    public JspException() {
        // NOOP
    }


    /**
     * Constructs a new JSP exception with the
     * specified message. The message can be written
     * to the server log and/or displayed for the user.
     *
     * @param msg   a <code>String</code> specifying the text of the exception
     *              message
     */
    public JspException(String msg) {
        super(msg);
    }


    /**
     * Constructs a new <code>JSPException</code> with the specified detail
     * message and cause. The cause is saved for later retrieval by the
     * <code>java.lang.Throwable.getCause()</code> and {@link #getRootCause()}
     * methods.
     *
     * @see <code>java.lang.Exception.Exception(String, Throwable)</code>
     *
     * @param message       a <code>String</code> containing the text of the
     *                      exception message
     *
     * @param cause         the <code>Throwable</code> exception that
     *                      interfered with the JSP's normal operation,
     *                      making this JSP exception necessary
     */

    public JspException(String message, Throwable cause) {
        super(message, cause);
    }


    /**
     * Constructs a new <code>JSPException</code> with the specified cause.
     * The cause is saved for later retrieval by the
     * <code>java.lang.Throwable.getCause()</code> and {@link #getRootCause()}
     * methods.
     *
     * @see <code>java.lang.Exception.Exception(Throwable)</code>
     *
     * @param cause         the <code>Throwable</code> exception that
     *                      interfered with the JSP's normal operation, making
     *                      the JSP exception necessary
     */

    public JspException(Throwable cause) {
        super(cause);
    }


    /**
     * Returns the exception that caused this JSP exception.
     *
     * @return  the <code>Throwable</code> that caused this JSP exception
     *
     * @deprecated As of JSP 2.1, replaced by
     * <code>java.lang.Throwable.getCause()</code>
     */
    @SuppressWarnings("dep-ann") // TCK signature test fails with annotation
    public Throwable getRootCause() {
        return getCause();
    }
1
            
// in java/org/apache/jasper/runtime/TagHandlerPool.java
public Tag get(Class<? extends Tag> handlerClass) throws JspException { Tag handler; synchronized (this) { if (current >= 0) { handler = handlers[current--]; return handler; } } // Out of sync block - there is no need for other threads to // wait for us to construct a tag for this thread. try { if (Constants.USE_INSTANCE_MANAGER_FOR_TAGS) { return (Tag) instanceManager.newInstance( handlerClass.getName(), handlerClass.getClassLoader()); } else { Tag instance = handlerClass.newInstance(); instanceManager.newInstance(instance); return instance; } } catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JspException(e.getMessage(), t); } }
1
            
// in java/org/apache/jasper/runtime/TagHandlerPool.java
catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JspException(e.getMessage(), t); }
12
            
// in java/org/apache/jasper/tagplugins/jstl/Util.java
public static String resolveUrl( String url, String context, PageContext pageContext) throws JspException { // don't touch absolute URLs if (isAbsoluteUrl(url)) return url; // normalize relative URLs against a context root HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); if (context == null) { if (url.startsWith("/")) return (request.getContextPath() + url); else return url; } else { if (!context.startsWith("/") || !url.startsWith("/")) { throw new JspTagException( "In URL tags, when the \"context\" attribute is specified, values of both \"context\" and \"url\" must start with \"/\"."); } if (context.equals("/")) { // Don't produce string starting with '//', many // browsers interpret this as host name, not as // path on same host. return url; } else { return (context + url); } } }
// in java/org/apache/jasper/runtime/TagHandlerPool.java
public Tag get(Class<? extends Tag> handlerClass) throws JspException { Tag handler; synchronized (this) { if (current >= 0) { handler = handlers[current--]; return handler; } } // Out of sync block - there is no need for other threads to // wait for us to construct a tag for this thread. try { if (Constants.USE_INSTANCE_MANAGER_FOR_TAGS) { return (Tag) instanceManager.newInstance( handlerClass.getName(), handlerClass.getClassLoader()); } else { Tag instance = handlerClass.newInstance(); instanceManager.newInstance(instance); return instance; } } catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JspException(e.getMessage(), t); } }
// in java/javax/servlet/jsp/tagext/TagSupport.java
Override public int doStartTag() throws JspException { return SKIP_BODY; }
// in java/javax/servlet/jsp/tagext/TagSupport.java
Override public int doEndTag() throws JspException { return EVAL_PAGE; }
// in java/javax/servlet/jsp/tagext/TagSupport.java
Override public int doAfterBody() throws JspException { return SKIP_BODY; }
// in java/javax/servlet/jsp/tagext/TagAdapter.java
Override public int doStartTag() throws JspException { throw new UnsupportedOperationException( "Illegal to invoke doStartTag() on TagAdapter wrapper"); }
// in java/javax/servlet/jsp/tagext/TagAdapter.java
Override public int doEndTag() throws JspException { throw new UnsupportedOperationException( "Illegal to invoke doEndTag() on TagAdapter wrapper"); }
// in java/javax/servlet/jsp/tagext/SimpleTagSupport.java
Override public void doTag() throws JspException, IOException { // NOOP by default }
// in java/javax/servlet/jsp/tagext/BodyTagSupport.java
Override public int doStartTag() throws JspException { return EVAL_BODY_BUFFERED; }
// in java/javax/servlet/jsp/tagext/BodyTagSupport.java
Override public int doEndTag() throws JspException { return super.doEndTag(); }
// in java/javax/servlet/jsp/tagext/BodyTagSupport.java
Override public void doInitBody() throws JspException { // NOOP by default }
// in java/javax/servlet/jsp/tagext/BodyTagSupport.java
Override public int doAfterBody() throws JspException { return SKIP_BODY; }
0 0 0
runtime (Domain) JspMethodNotFoundException
public class JspMethodNotFoundException extends MethodNotFoundException {

    private static final long serialVersionUID = 1L;

    public JspMethodNotFoundException(String mark, MethodNotFoundException e) {
        super(mark + " " + e.getMessage(), e.getCause());
    }
}
2
            
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public MethodInfo getMethodInfo(ELContext context) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.getMethodInfo(context); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public Object invoke(ELContext context, Object[] params) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.invoke(context, params); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
2
            
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
0 0 0 0
runtime (Domain) JspPropertyNotFoundException
public final class JspPropertyNotFoundException extends
        PropertyNotFoundException {

    private static final long serialVersionUID = 1L;

    public JspPropertyNotFoundException(String mark, PropertyNotFoundException e) {
        super(mark + " " + e.getMessage(), e.getCause());
    }

}
6
            
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public MethodInfo getMethodInfo(ELContext context) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.getMethodInfo(context); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public Object invoke(ELContext context, Object[] params) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.invoke(context, params); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Class<?> getType(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getType(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public boolean isReadOnly(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.isReadOnly(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void setValue(ELContext context, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { try { this.target.setValue(context, value); } catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Object getValue(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getValue(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
6
            
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
0 0 0 0
runtime (Domain) JspPropertyNotWritableException
public class JspPropertyNotWritableException extends
        PropertyNotWritableException {

    private static final long serialVersionUID = 1L;

    public JspPropertyNotWritableException(String mark, PropertyNotWritableException e) {
        super(mark + " " + e.getMessage(), e.getCause());
    }
}
1
            
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void setValue(ELContext context, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { try { this.target.setValue(context, value); } catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
1
            
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); }
0 0 0 0
checked (Domain) JspTagException
public class JspTagException extends JspException {

    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new JspTagException with the specified message. The message
     * can be written to the server log and/or displayed for the user.
     *
     * @param msg
     *            a <code>String</code> specifying the text of the exception
     *            message
     */
    public JspTagException(String msg) {
        super(msg);
    }

    /**
     * Constructs a new JspTagException with no message.
     */
    public JspTagException() {
        super();
    }

    /**
     * Constructs a new JspTagException when the JSP Tag needs to throw an
     * exception and include a message about the "root cause" exception that
     * interfered with its normal operation, including a description message.
     *
     * @param message
     *            a <code>String</code> containing the text of the exception
     *            message
     * @param rootCause
     *            the <code>Throwable</code> exception that interfered with the
     *            JSP Tag's normal operation, making this JSP Tag exception
     *            necessary
     * @since 2.0
     */
    public JspTagException(String message, Throwable rootCause) {
        super(message, rootCause);
    }

    /**
     * Constructs a new JSP Tag exception when the JSP Tag needs to throw an
     * exception and include a message about the "root cause" exception that
     * interfered with its normal operation. The exception's message is based on
     * the localized message of the underlying exception.
     * <p>
     * This method calls the <code>getLocalizedMessage</code> method on the
     * <code>Throwable</code> exception to get a localized exception message.
     * When subclassing <code>JspTagException</code>, this method can be
     * overridden to create an exception message designed for a specific locale.
     *
     * @param rootCause
     *            the <code>Throwable</code> exception that interfered with the
     *            JSP Tag's normal operation, making the JSP Tag exception
     *            necessary
     * @since 2.0
     */
    public JspTagException(Throwable rootCause) {
        super(rootCause);
    }
}
1
            
// in java/org/apache/jasper/tagplugins/jstl/Util.java
public static String resolveUrl( String url, String context, PageContext pageContext) throws JspException { // don't touch absolute URLs if (isAbsoluteUrl(url)) return url; // normalize relative URLs against a context root HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); if (context == null) { if (url.startsWith("/")) return (request.getContextPath() + url); else return url; } else { if (!context.startsWith("/") || !url.startsWith("/")) { throw new JspTagException( "In URL tags, when the \"context\" attribute is specified, values of both \"context\" and \"url\" must start with \"/\"."); } if (context.equals("/")) { // Don't produce string starting with '//', many // browsers interpret this as host name, not as // path on same host. return url; } else { return (context + url); } } }
0 0 0 0 0
unknown (Lib) KeyManagementException 0 0 0 1
            
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (KeyManagementException e) { // Assume no RFC 5746 support }
0 0
checked (Domain) LifecycleException
public final class LifecycleException extends Exception {

    private static final long serialVersionUID = 1L;

    //------------------------------------------------------------ Constructors


    /**
     * Construct a new LifecycleException with no other information.
     */
    public LifecycleException() {
        super();
    }


    /**
     * Construct a new LifecycleException for the specified message.
     *
     * @param message Message describing this exception
     */
    public LifecycleException(String message) {
        super(message);
    }


    /**
     * Construct a new LifecycleException for the specified throwable.
     *
     * @param throwable Throwable that caused this exception
     */
    public LifecycleException(Throwable throwable) {
        super(throwable);
    }


    /**
     * Construct a new LifecycleException for the specified message
     * and throwable.
     *
     * @param message Message describing this exception
     * @param throwable Throwable that caused this exception
     */
    public LifecycleException(String message, Throwable throwable) {
        super(message, throwable);
    }
}
33
            
// in java/org/apache/catalina/startup/FailedContext.java
Override protected void startInternal() throws LifecycleException { throw new LifecycleException( sm.getString("failedContext.start", getName())); }
// in java/org/apache/catalina/loader/WebappLoader.java
Override protected void startInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug(sm.getString("webappLoader.starting")); if (container.getResources() == null) { log.info("No resources for " + container); setState(LifecycleState.STARTING); return; } // Register a stream handler factory for the JNDI protocol URLStreamHandlerFactory streamHandlerFactory = DirContextURLStreamHandlerFactory.getInstance(); if (first) { first = false; try { URL.setURLStreamHandlerFactory(streamHandlerFactory); } catch (Exception e) { // Log and continue anyway, this is not critical log.error("Error registering jndi stream handler", e); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This is likely a dual registration log.info("Dual registration of jndi stream handler: " + t.getMessage()); } } // Construct a class loader based on our current repositories list try { classLoader = createClassLoader(); classLoader.setResources(container.getResources()); classLoader.setDelegate(this.delegate); classLoader.setSearchExternalFirst(searchExternalFirst); for (int i = 0; i < repositories.length; i++) { classLoader.addRepository(repositories[i]); } // Configure our repositories setRepositories(); setClassPath(); setPermissions(); ((Lifecycle) classLoader).start(); // Binding the Webapp class loader to the directory context DirContextURLStreamHandler.bind(classLoader, this.container.getResources()); String contextName = container.getName(); if (!contextName.startsWith("/")) { contextName = "/" + contextName; } ObjectName cloname = new ObjectName(container.getDomain() + ":type=WebappClassLoader,context=" + contextName + ",host=" + container.getParent().getName()); Registry.getRegistry(null, null) .registerComponent(classLoader, cloname, null); } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error( "LifecycleException ", t ); throw new LifecycleException("start: ", t); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/realm/MemoryRealm.java
Override protected void startInternal() throws LifecycleException { // Validate the existence of our database file File file = new File(pathname); if (!file.isAbsolute()) file = new File(getContainer().getCatalinaBase(), pathname); if (!file.exists() || !file.canRead()) throw new LifecycleException (sm.getString("memoryRealm.loadExist", file.getAbsolutePath())); // Load the contents of the database file if (log.isDebugEnabled()) log.debug(sm.getString("memoryRealm.loadPath", file.getAbsolutePath())); Digester digester = getDigester(); try { synchronized (digester) { digester.push(this); digester.parse(file); } } catch (Exception e) { throw new LifecycleException (sm.getString("memoryRealm.readXml"), e); } finally { digester.reset(); } super.startInternal(); }
// in java/org/apache/catalina/realm/JNDIRealm.java
Override protected void startInternal() throws LifecycleException { // Validate that we can open our connection try { open(); } catch (NamingException e) { throw new LifecycleException(sm.getString("jndiRealm.open"), e); } super.startInternal(); }
// in java/org/apache/catalina/realm/UserDatabaseRealm.java
Override protected void startInternal() throws LifecycleException { try { Context context = getServer().getGlobalNamingContext(); database = (UserDatabase) context.lookup(resourceName); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); containerLog.error(sm.getString("userDatabaseRealm.lookup", resourceName), e); database = null; } if (database == null) { throw new LifecycleException (sm.getString("userDatabaseRealm.noDatabase", resourceName)); } super.startInternal(); }
// in java/org/apache/catalina/realm/RealmBase.java
Override protected void startInternal() throws LifecycleException { // Create a MessageDigest instance for credentials, if desired if (digest != null) { try { md = MessageDigest.getInstance(digest); } catch (NoSuchAlgorithmException e) { throw new LifecycleException (sm.getString("realmBase.algorithm", digest), e); } } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/realm/RealmBase.java
private static X509UsernameRetriever createUsernameRetriever(String className) throws LifecycleException { if(null == className || "".equals(className.trim())) return new X509SubjectDnRetriever(); try { @SuppressWarnings("unchecked") Class<? extends X509UsernameRetriever> clazz = (Class<? extends X509UsernameRetriever>)Class.forName(className); return clazz.newInstance(); } catch (ClassNotFoundException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassNotFoundException", className), e); } catch (InstantiationException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.InstantiationException", className), e); } catch (IllegalAccessException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.IllegalAccessException", className), e); } catch (ClassCastException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e); } }
// in java/org/apache/catalina/valves/RequestFilterValve.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); if (!allowValid || !denyValid) { throw new LifecycleException( sm.getString("requestFilterValve.configInvalid")); } }
// in java/org/apache/catalina/valves/RequestFilterValve.java
Override protected synchronized void startInternal() throws LifecycleException { if (!allowValid || !denyValid) { throw new LifecycleException( sm.getString("requestFilterValve.configInvalid")); } super.startInternal(); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
Override protected synchronized void startInternal() throws LifecycleException { try { open() ; } catch (SQLException e) { throw new LifecycleException(e); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/ha/context/ReplicatedContext.java
Override protected synchronized void startInternal() throws LifecycleException { try { CatalinaCluster catclust = (CatalinaCluster)this.getCluster(); if (this.context == null) this.context = new ReplApplContext(this); if ( catclust != null ) { ReplicatedMap<String,Object> map = new ReplicatedMap<String,Object>(this, catclust.getChannel(),DEFAULT_REPL_TIMEOUT, getName(),getClassLoaders()); map.setChannelSendOptions(mapSendOptions); ((ReplApplContext)this.context).setAttributeMap(map); if (getAltDDName() != null) context.setAttribute(Globals.ALT_DD_ATTR, getAltDDName()); } super.startInternal(); } catch ( Exception x ) { log.error("Unable to start ReplicatedContext",x); throw new LifecycleException("Failed to start ReplicatedContext",x); } }
// in java/org/apache/catalina/ha/session/BackupManager.java
Override protected synchronized void startInternal() throws LifecycleException { super.startInternal(); try { if (getCluster() == null) { Cluster cluster = getContainer().getCluster(); if (cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster)cluster); } else { throw new LifecycleException( sm.getString("backupManager.noCluster", getName())); } } cluster.registerManager(this); LazyReplicatedMap<String,Session> map = new LazyReplicatedMap<String,Session>(this, cluster.getChannel(), rpcTimeout, getMapName(), getClassLoaders()); map.setChannelSendOptions(mapSendOptions); this.sessions = map; } catch ( Exception x ) { log.error(sm.getString("backupManager.startUnable", getName()),x); throw new LifecycleException(sm.getString("backupManager.startFailed", getName()),x); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOn.java
Override protected synchronized void startInternal() throws LifecycleException { clusterSSOListener = new ClusterSingleSignOnListener(); clusterSSOListener.setClusterSSO(this); // Load the cluster component, if any try { //the channel is already running Cluster cluster = getCluster(); // stop remove cluster binding if(cluster == null) { Container host = getContainer(); if(host != null && host instanceof Host) { cluster = host.getCluster(); if(cluster != null && cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster) cluster); getCluster().addClusterListener(clusterSSOListener); } else { Container engine = host.getParent(); if(engine != null && engine instanceof Engine) { cluster = engine.getCluster(); if(cluster != null && cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster) cluster); getCluster().addClusterListener(clusterSSOListener); } } else { cluster = null; } } } } if (cluster == null) { throw new LifecycleException( "There is no Cluster for ClusterSingleSignOn"); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new LifecycleException( "ClusterSingleSignOn exception during clusterLoad " + t); } super.startInternal(); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
Override protected void startInternal() throws LifecycleException { if (log.isInfoEnabled()) log.info("Cluster is about to start"); try { checkDefaults(); registerClusterValve(); channel.addMembershipListener(this); channel.addChannelListener(this); channel.start(channelStartOptions); if (clusterDeployer != null) clusterDeployer.start(); //register JMX objects ClusterJmxHelper.registerDefaultCluster(this); // Notify our interested LifecycleListeners } catch (Exception x) { log.error("Unable to start cluster.", x); throw new LifecycleException(x); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/connector/Connector.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); // Initialize adapter adapter = new CoyoteAdapter(this); protocolHandler.setAdapter(adapter); // Make sure parseBodyMethodsSet has a default if( null == parseBodyMethodsSet ) { setParseBodyMethods(getParseBodyMethods()); } try { protocolHandler.init(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerInitializationFailed"), e); } // Initialize mapper listener mapperListener.init(); }
// in java/org/apache/catalina/connector/Connector.java
Override protected void startInternal() throws LifecycleException { // Validate settings before starting if (getPort() < 0) { throw new LifecycleException(sm.getString( "coyoteConnector.invalidPort", Integer.valueOf(getPort()))); } setState(LifecycleState.STARTING); try { protocolHandler.start(); } catch (Exception e) { String errPrefix = ""; if(this.service != null) { errPrefix += "service.getName(): \"" + this.service.getName() + "\"; "; } throw new LifecycleException (errPrefix + " " + sm.getString ("coyoteConnector.protocolHandlerStartFailed"), e); } mapperListener.start(); }
// in java/org/apache/catalina/connector/Connector.java
Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); try { protocolHandler.stop(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerStopFailed"), e); } mapperListener.stop(); }
// in java/org/apache/catalina/connector/Connector.java
Override protected void destroyInternal() throws LifecycleException { mapperListener.destroy(); try { protocolHandler.destroy(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerDestroyFailed"), e); } if (getService() != null) { getService().removeConnector(this); } super.destroyInternal(); }
// in java/org/apache/catalina/core/ContainerBase.java
Override protected synchronized void startInternal() throws LifecycleException { // Start our subordinate components, if any if ((loader != null) && (loader instanceof Lifecycle)) ((Lifecycle) loader).start(); logger = null; getLogger(); if ((manager != null) && (manager instanceof Lifecycle)) ((Lifecycle) manager).start(); if ((cluster != null) && (cluster instanceof Lifecycle)) ((Lifecycle) cluster).start(); Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) ((Lifecycle) realm).start(); if ((resources != null) && (resources instanceof Lifecycle)) ((Lifecycle) resources).start(); // Start our child containers, if any Container children[] = findChildren(); List<Future<Void>> results = new ArrayList<Future<Void>>(); for (int i = 0; i < children.length; i++) { results.add(startStopExecutor.submit(new StartChild(children[i]))); } boolean fail = false; for (Future<Void> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString("containerBase.threadedStartFailed"), e); fail = true; } } if (fail) { throw new LifecycleException( sm.getString("containerBase.threadedStartFailed")); } // Start the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle) ((Lifecycle) pipeline).start(); setState(LifecycleState.STARTING); // Start our thread threadStart(); }
// in java/org/apache/catalina/core/ContainerBase.java
Override protected synchronized void stopInternal() throws LifecycleException { // Stop our thread threadStop(); setState(LifecycleState.STOPPING); // Stop the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle && ((Lifecycle) pipeline).getState().isAvailable()) { ((Lifecycle) pipeline).stop(); } // Stop our child containers, if any Container children[] = findChildren(); List<Future<Void>> results = new ArrayList<Future<Void>>(); for (int i = 0; i < children.length; i++) { results.add(startStopExecutor.submit(new StopChild(children[i]))); } boolean fail = false; for (Future<Void> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString("containerBase.threadedStopFailed"), e); fail = true; } } if (fail) { throw new LifecycleException( sm.getString("containerBase.threadedStopFailed")); } // Stop our subordinate components, if any if ((resources != null) && (resources instanceof Lifecycle)) { ((Lifecycle) resources).stop(); } Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) { ((Lifecycle) realm).stop(); } if ((cluster != null) && (cluster instanceof Lifecycle)) { ((Lifecycle) cluster).stop(); } if ((manager != null) && (manager instanceof Lifecycle) && ((Lifecycle) manager).getState().isAvailable() ) { ((Lifecycle) manager).stop(); } if ((loader != null) && (loader instanceof Lifecycle)) { ((Lifecycle) loader).stop(); } }
// in java/org/apache/catalina/core/StandardService.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); if (container != null) { container.init(); } // Initialize any Executors for (Executor executor : findExecutors()) { if (executor instanceof JmxEnabled) { ((JmxEnabled) executor).setDomain(getDomain()); } executor.init(); } // Initialize our defined Connectors synchronized (connectors) { for (Connector connector : connectors) { try { connector.init(); } catch (Exception e) { String message = sm.getString( "standardService.connector.initFailed", connector); log.error(message, e); if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) throw new LifecycleException(message); } } } }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void init() throws LifecycleException { if (!state.equals(LifecycleState.NEW)) { invalidTransition(Lifecycle.BEFORE_INIT_EVENT); } setStateInternal(LifecycleState.INITIALIZING, null, false); try { initInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); } setStateInternal(LifecycleState.INITIALIZED, null, false); }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void start() throws LifecycleException { if (LifecycleState.STARTING_PREP.equals(state) || LifecycleState.STARTING.equals(state) || LifecycleState.STARTED.equals(state)) { if (log.isDebugEnabled()) { Exception e = new LifecycleException(); log.debug(sm.getString("lifecycleBase.alreadyStarted", toString()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("lifecycleBase.alreadyStarted", toString())); } return; } if (state.equals(LifecycleState.NEW)) { init(); } else if (state.equals(LifecycleState.FAILED)){ stop(); } else if (!state.equals(LifecycleState.INITIALIZED) && !state.equals(LifecycleState.STOPPED)) { invalidTransition(Lifecycle.BEFORE_START_EVENT); } setStateInternal(LifecycleState.STARTING_PREP, null, false); try { startInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.startFail",toString()), t); } if (state.equals(LifecycleState.FAILED) || state.equals(LifecycleState.MUST_STOP)) { stop(); } else { // Shouldn't be necessary but acts as a check that sub-classes are // doing what they are supposed to. if (!state.equals(LifecycleState.STARTING)) { invalidTransition(Lifecycle.AFTER_START_EVENT); } setStateInternal(LifecycleState.STARTED, null, false); } }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void stop() throws LifecycleException { if (LifecycleState.STOPPING_PREP.equals(state) || LifecycleState.STOPPING.equals(state) || LifecycleState.STOPPED.equals(state)) { if (log.isDebugEnabled()) { Exception e = new LifecycleException(); log.debug(sm.getString("lifecycleBase.alreadyStopped", toString()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("lifecycleBase.alreadyStopped", toString())); } return; } if (state.equals(LifecycleState.NEW)) { state = LifecycleState.STOPPED; return; } if (!state.equals(LifecycleState.STARTED) && !state.equals(LifecycleState.FAILED) && !state.equals(LifecycleState.MUST_STOP)) { invalidTransition(Lifecycle.BEFORE_STOP_EVENT); } if (state.equals(LifecycleState.FAILED)) { // Don't transition to STOPPING_PREP as that would briefly mark the // component as available but do ensure the BEFORE_STOP_EVENT is // fired fireLifecycleEvent(BEFORE_STOP_EVENT, null); } else { setStateInternal(LifecycleState.STOPPING_PREP, null, false); } try { stopInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.stopFail",toString()), t); } if (state.equals(LifecycleState.MUST_DESTROY)) { // Complete stop process first setStateInternal(LifecycleState.STOPPED, null, false); destroy(); } else { // Shouldn't be necessary but acts as a check that sub-classes are // doing what they are supposed to. if (!state.equals(LifecycleState.STOPPING)) { invalidTransition(Lifecycle.AFTER_STOP_EVENT); } setStateInternal(LifecycleState.STOPPED, null, false); } }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void destroy() throws LifecycleException { if (LifecycleState.FAILED.equals(state)) { try { // Triggers clean-up stop(); } catch (LifecycleException e) { // Just log. Still want to destroy. log.warn(sm.getString("lifecycleBase.destroyStopFail"), e); } } if (LifecycleState.DESTROYING.equals(state) || LifecycleState.DESTROYED.equals(state)) { if (log.isDebugEnabled()) { Exception e = new LifecycleException(); log.debug(sm.getString("lifecycleBase.alreadyDestroyed", toString()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("lifecycleBase.alreadyDestroyed", toString())); } return; } if (!state.equals(LifecycleState.STOPPED) && !state.equals(LifecycleState.FAILED) && !state.equals(LifecycleState.NEW) && !state.equals(LifecycleState.INITIALIZED)) { invalidTransition(Lifecycle.BEFORE_DESTROY_EVENT); } setStateInternal(LifecycleState.DESTROYING, null, false); try { destroyInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); } setStateInternal(LifecycleState.DESTROYED, null, false); }
// in java/org/apache/catalina/util/LifecycleBase.java
private void invalidTransition(String type) throws LifecycleException { String msg = sm.getString("lifecycleBase.invalidTransition", type, toString(), state); throw new LifecycleException(msg); }
22
            
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error( "LifecycleException ", t ); throw new LifecycleException("start: ", t); }
// in java/org/apache/catalina/realm/MemoryRealm.java
catch (Exception e) { throw new LifecycleException (sm.getString("memoryRealm.readXml"), e); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { throw new LifecycleException(sm.getString("jndiRealm.open"), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { throw new LifecycleException (sm.getString("realmBase.algorithm", digest), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassNotFoundException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassNotFoundException", className), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (InstantiationException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.InstantiationException", className), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (IllegalAccessException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.IllegalAccessException", className), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (ClassCastException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { throw new LifecycleException(e); }
// in java/org/apache/catalina/ha/context/ReplicatedContext.java
catch ( Exception x ) { log.error("Unable to start ReplicatedContext",x); throw new LifecycleException("Failed to start ReplicatedContext",x); }
// in java/org/apache/catalina/ha/session/BackupManager.java
catch ( Exception x ) { log.error(sm.getString("backupManager.startUnable", getName()),x); throw new LifecycleException(sm.getString("backupManager.startFailed", getName()),x); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOn.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new LifecycleException( "ClusterSingleSignOn exception during clusterLoad " + t); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
catch (Exception x) { log.error("Unable to start cluster.", x); throw new LifecycleException(x); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerInitializationFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { String errPrefix = ""; if(this.service != null) { errPrefix += "service.getName(): \"" + this.service.getName() + "\"; "; } throw new LifecycleException (errPrefix + " " + sm.getString ("coyoteConnector.protocolHandlerStartFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerStopFailed"), e); }
// in java/org/apache/catalina/connector/Connector.java
catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerDestroyFailed"), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (Exception e) { String message = sm.getString( "standardService.connector.initFailed", connector); log.error(message, e); if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) throw new LifecycleException(message); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.startFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.stopFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); }
122
            
// in java/org/apache/catalina/startup/FailedContext.java
Override protected void startInternal() throws LifecycleException { throw new LifecycleException( sm.getString("failedContext.start", getName())); }
// in java/org/apache/catalina/startup/FailedContext.java
Override protected void stopInternal() throws LifecycleException { // NO-OP // Allow stop to complete since it is used for clean-up }
// in java/org/apache/catalina/startup/Tomcat.java
public void init() throws LifecycleException { getServer(); getConnector(); server.init(); }
// in java/org/apache/catalina/startup/Tomcat.java
public void start() throws LifecycleException { getServer(); getConnector(); server.start(); }
// in java/org/apache/catalina/startup/Tomcat.java
public void stop() throws LifecycleException { getServer(); server.stop(); }
// in java/org/apache/catalina/startup/Tomcat.java
public void destroy() throws LifecycleException { getServer(); server.destroy(); // Could null out objects here }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public void start() throws LifecycleException { started = true; String encoding = null; try { encoding = System.getProperty("file.encoding"); } catch (SecurityException e) { return; } if (encoding.indexOf("EBCDIC")!=-1) { needConvert = true; } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
Override public void stop() throws LifecycleException { // Clearing references should be done before setting started to // false, due to possible side effects clearReferences(); started = false; int length = files.length; for (int i = 0; i < length; i++) { files[i] = null; } length = jarFiles.length; for (int i = 0; i < length; i++) { try { if (jarFiles[i] != null) { jarFiles[i].close(); } } catch (IOException e) { // Ignore } jarFiles[i] = null; } notFoundResources.clear(); resourceEntries.clear(); resources = null; repositories = null; repositoryURLs = null; files = null; jarFiles = null; jarRealFiles = null; jarPath = null; jarNames = null; lastModifiedDates = null; paths = null; hasExternalRepositories = false; parent = null; permissionList.clear(); loaderPC.clear(); if (loaderDir != null) { deleteDir(loaderDir); } }
// in java/org/apache/catalina/loader/WebappLoader.java
Override protected void startInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug(sm.getString("webappLoader.starting")); if (container.getResources() == null) { log.info("No resources for " + container); setState(LifecycleState.STARTING); return; } // Register a stream handler factory for the JNDI protocol URLStreamHandlerFactory streamHandlerFactory = DirContextURLStreamHandlerFactory.getInstance(); if (first) { first = false; try { URL.setURLStreamHandlerFactory(streamHandlerFactory); } catch (Exception e) { // Log and continue anyway, this is not critical log.error("Error registering jndi stream handler", e); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This is likely a dual registration log.info("Dual registration of jndi stream handler: " + t.getMessage()); } } // Construct a class loader based on our current repositories list try { classLoader = createClassLoader(); classLoader.setResources(container.getResources()); classLoader.setDelegate(this.delegate); classLoader.setSearchExternalFirst(searchExternalFirst); for (int i = 0; i < repositories.length; i++) { classLoader.addRepository(repositories[i]); } // Configure our repositories setRepositories(); setClassPath(); setPermissions(); ((Lifecycle) classLoader).start(); // Binding the Webapp class loader to the directory context DirContextURLStreamHandler.bind(classLoader, this.container.getResources()); String contextName = container.getName(); if (!contextName.startsWith("/")) { contextName = "/" + contextName; } ObjectName cloname = new ObjectName(container.getDomain() + ":type=WebappClassLoader,context=" + contextName + ",host=" + container.getParent().getName()); Registry.getRegistry(null, null) .registerComponent(classLoader, cloname, null); } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error( "LifecycleException ", t ); throw new LifecycleException("start: ", t); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/loader/WebappLoader.java
Override protected void stopInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug(sm.getString("webappLoader.stopping")); setState(LifecycleState.STOPPING); // Remove context attributes as appropriate if (container instanceof Context) { ServletContext servletContext = ((Context) container).getServletContext(); servletContext.removeAttribute(Globals.CLASS_PATH_ATTR); } // Throw away our current class loader ((Lifecycle) classLoader).stop(); DirContextURLStreamHandler.unbind(classLoader); try { String contextName = container.getName(); if (!contextName.startsWith("/")) { contextName = "/" + contextName; } ObjectName cloname = new ObjectName(container.getDomain() + ":type=WebappClassLoader,context=" + contextName + ",host=" + container.getParent().getName()); Registry.getRegistry(null, null).unregisterComponent(cloname); } catch (Exception e) { log.error("LifecycleException ", e); } classLoader = null; }
// in java/org/apache/catalina/loader/VirtualWebappLoader.java
Override protected void startInternal() throws LifecycleException { // just add any jar/directory set in virtual classpath to the // repositories list before calling start on the standard WebappLoader StringTokenizer tkn = new StringTokenizer(virtualClasspath, ";"); Set<String> set = new LinkedHashSet<String>(); while (tkn.hasMoreTokens()) { String token = tkn.nextToken().trim(); if (token.isEmpty()) { continue; } if (log.isDebugEnabled()) log.debug(sm.getString("virtualWebappLoader.token", token)); if (token.endsWith("*.jar")) { // glob token = token.substring(0, token.length() - "*.jar".length()); File directory = new File(token); if (!directory.isDirectory()) { if (log.isDebugEnabled()) { log.debug(sm.getString( "virtualWebappLoader.token.notDirectory", directory.getAbsolutePath())); } continue; } if (log.isDebugEnabled()) { log.debug(sm.getString( "virtualWebappLoader.token.glob.dir", directory.getAbsolutePath())); } String filenames[] = directory.list(); Arrays.sort(filenames); for (int j = 0; j < filenames.length; j++) { String filename = filenames[j].toLowerCase(Locale.ENGLISH); if (!filename.endsWith(".jar")) continue; File file = new File(directory, filenames[j]); if (!file.isFile()) { if (log.isDebugEnabled()) { log.debug(sm.getString( "virtualWebappLoader.token.notFile", file.getAbsolutePath())); } continue; } if (log.isDebugEnabled()) { log.debug(sm.getString( "virtualWebappLoader.token.file", file.getAbsolutePath())); } set.add(file.toURI().toString()); } } else { // single file or directory File file = new File(token); if (!file.exists()) { if (log.isDebugEnabled()) { log.debug(sm.getString( "virtualWebappLoader.token.notExists", file.getAbsolutePath())); } continue; } if (log.isDebugEnabled()) { log.debug(sm.getString( "virtualWebappLoader.token.file", file.getAbsolutePath())); } set.add(file.toURI().toString()); } } for (String repository: set) { addRepository(repository); } super.startInternal(); }
// in java/org/apache/catalina/realm/MemoryRealm.java
Override protected void startInternal() throws LifecycleException { // Validate the existence of our database file File file = new File(pathname); if (!file.isAbsolute()) file = new File(getContainer().getCatalinaBase(), pathname); if (!file.exists() || !file.canRead()) throw new LifecycleException (sm.getString("memoryRealm.loadExist", file.getAbsolutePath())); // Load the contents of the database file if (log.isDebugEnabled()) log.debug(sm.getString("memoryRealm.loadPath", file.getAbsolutePath())); Digester digester = getDigester(); try { synchronized (digester) { digester.push(this); digester.parse(file); } } catch (Exception e) { throw new LifecycleException (sm.getString("memoryRealm.readXml"), e); } finally { digester.reset(); } super.startInternal(); }
// in java/org/apache/catalina/realm/CombinedRealm.java
Override protected void startInternal() throws LifecycleException { // Start 'sub-realms' then this one Iterator<Realm> iter = realms.iterator(); while (iter.hasNext()) { Realm realm = iter.next(); if (realm instanceof Lifecycle) { try { ((Lifecycle) realm).start(); } catch (LifecycleException e) { // If realm doesn't start can't authenticate against it iter.remove(); log.error(sm.getString("combinedRealm.realmStartFail", realm.getClass().getName()), e); } } } super.startInternal(); }
// in java/org/apache/catalina/realm/CombinedRealm.java
Override protected void stopInternal() throws LifecycleException { // Stop this realm, then the sub-realms (reverse order to start) super.stopInternal(); for (Realm realm : realms) { if (realm instanceof Lifecycle) { ((Lifecycle) realm).stop(); } } }
// in java/org/apache/catalina/realm/JNDIRealm.java
Override protected void startInternal() throws LifecycleException { // Validate that we can open our connection try { open(); } catch (NamingException e) { throw new LifecycleException(sm.getString("jndiRealm.open"), e); } super.startInternal(); }
// in java/org/apache/catalina/realm/JNDIRealm.java
Override protected void stopInternal() throws LifecycleException { super.stopInternal(); // Close any open directory server connection close(this.context); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
Override protected void startInternal() throws LifecycleException { // Create the roles PreparedStatement string StringBuilder temp = new StringBuilder("SELECT "); temp.append(roleNameCol); temp.append(" FROM "); temp.append(userRoleTable); temp.append(" WHERE "); temp.append(userNameCol); temp.append(" = ?"); preparedRoles = temp.toString(); // Create the credentials PreparedStatement string temp = new StringBuilder("SELECT "); temp.append(userCredCol); temp.append(" FROM "); temp.append(userTable); temp.append(" WHERE "); temp.append(userNameCol); temp.append(" = ?"); preparedCredentials = temp.toString(); super.startInternal(); }
// in java/org/apache/catalina/realm/UserDatabaseRealm.java
Override protected void startInternal() throws LifecycleException { try { Context context = getServer().getGlobalNamingContext(); database = (UserDatabase) context.lookup(resourceName); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); containerLog.error(sm.getString("userDatabaseRealm.lookup", resourceName), e); database = null; } if (database == null) { throw new LifecycleException (sm.getString("userDatabaseRealm.noDatabase", resourceName)); } super.startInternal(); }
// in java/org/apache/catalina/realm/UserDatabaseRealm.java
Override protected void stopInternal() throws LifecycleException { // Perform normal superclass finalization super.stopInternal(); // Release reference to our user database database = null; }
// in java/org/apache/catalina/realm/LockOutRealm.java
Override protected void startInternal() throws LifecycleException { // Configure the list of failed users to delete the oldest entry once it // exceeds the specified size failedUsers = new LinkedHashMap<String, LockRecord>(cacheSize, 0.75f, true) { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry( Map.Entry<String, LockRecord> eldest) { if (size() > cacheSize) { // Check to see if this element has been removed too quickly long timeInCache = (System.currentTimeMillis() - eldest.getValue().getLastFailureTime())/1000; if (timeInCache < cacheRemovalWarningTime) { log.warn(sm.getString("lockOutRealm.removeWarning", eldest.getKey(), Long.valueOf(timeInCache))); } return true; } return false; } }; super.startInternal(); }
// in java/org/apache/catalina/realm/JAASRealm.java
Override protected void startInternal() throws LifecycleException { // These need to be called after loading configuration, in case // useContextClassLoader appears after them in xml config parseClassNames(userClassNames, userClasses); parseClassNames(roleClassNames, roleClasses); super.startInternal(); }
// in java/org/apache/catalina/realm/RealmBase.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); // We want logger as soon as possible if (container != null) { this.containerLog = container.getLogger(); } x509UsernameRetriever = createUsernameRetriever(x509UsernameRetrieverClassName); }
// in java/org/apache/catalina/realm/RealmBase.java
Override protected void startInternal() throws LifecycleException { // Create a MessageDigest instance for credentials, if desired if (digest != null) { try { md = MessageDigest.getInstance(digest); } catch (NoSuchAlgorithmException e) { throw new LifecycleException (sm.getString("realmBase.algorithm", digest), e); } } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/realm/RealmBase.java
Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); // Clean up allocated resources md = null; }
// in java/org/apache/catalina/realm/RealmBase.java
private static X509UsernameRetriever createUsernameRetriever(String className) throws LifecycleException { if(null == className || "".equals(className.trim())) return new X509SubjectDnRetriever(); try { @SuppressWarnings("unchecked") Class<? extends X509UsernameRetriever> clazz = (Class<? extends X509UsernameRetriever>)Class.forName(className); return clazz.newInstance(); } catch (ClassNotFoundException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassNotFoundException", className), e); } catch (InstantiationException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.InstantiationException", className), e); } catch (IllegalAccessException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.IllegalAccessException", className), e); } catch (ClassCastException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e); } }
// in java/org/apache/catalina/realm/JDBCRealm.java
Override protected void startInternal() throws LifecycleException { // Validate that we can open our connection - but let tomcat // startup in case the database is temporarily unavailable try { open(); } catch (SQLException e) { containerLog.error(sm.getString("jdbcRealm.open"), e); } super.startInternal(); }
// in java/org/apache/catalina/realm/JDBCRealm.java
Override protected void stopInternal() throws LifecycleException { super.stopInternal(); // Close any open DB connection close(this.dbConnection); }
// in java/org/apache/catalina/session/StandardManager.java
Override protected synchronized void startInternal() throws LifecycleException { super.startInternal(); // Load unloaded sessions, if any try { load(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardManager.managerLoad"), t); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/session/StandardManager.java
Override protected synchronized void stopInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug("Stopping"); setState(LifecycleState.STOPPING); // Write out sessions try { unload(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardManager.managerUnload"), t); } // Expire all active sessions Session sessions[] = findSessions(); for (int i = 0; i < sessions.length; i++) { Session session = sessions[i]; try { if (session.isValid()) { session.expire(); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } finally { // Measure against memory leaking if references to the session // object are kept in a shared field somewhere session.recycle(); } } // Require a new random number generator if we are restarted super.stopInternal(); }
// in java/org/apache/catalina/session/StoreBase.java
Override protected synchronized void startInternal() throws LifecycleException { setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/session/StoreBase.java
Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); }
// in java/org/apache/catalina/session/ManagerBase.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); setDistributable(((Context) getContainer()).getDistributable()); }
// in java/org/apache/catalina/session/ManagerBase.java
Override protected void startInternal() throws LifecycleException { // Ensure caches for timing stats are the right size by filling with // nulls. while (sessionCreationTiming.size() < TIMING_STATS_CACHE_SIZE) { sessionCreationTiming.add(null); } while (sessionExpirationTiming.size() < TIMING_STATS_CACHE_SIZE) { sessionExpirationTiming.add(null); } sessionIdGenerator = new SessionIdGenerator(); sessionIdGenerator.setJvmRoute(getJvmRoute()); sessionIdGenerator.setSecureRandomAlgorithm(getSecureRandomAlgorithm()); sessionIdGenerator.setSecureRandomClass(getSecureRandomClass()); sessionIdGenerator.setSecureRandomProvider(getSecureRandomProvider()); sessionIdGenerator.setSessionIdLength(getSessionIdLength()); // Force initialization of the random number generator if (log.isDebugEnabled()) log.debug("Force random number initialization starting"); sessionIdGenerator.generateSessionId(); if (log.isDebugEnabled()) log.debug("Force random number initialization completed"); }
// in java/org/apache/catalina/session/ManagerBase.java
Override protected void stopInternal() throws LifecycleException { this.sessionIdGenerator = null; }
// in java/org/apache/catalina/session/JDBCStore.java
Override protected synchronized void startInternal() throws LifecycleException { if (dataSourceName == null) { // If not using a connection pool, open a connection to the database this.dbConnection = getConnection(); } super.startInternal(); }
// in java/org/apache/catalina/session/JDBCStore.java
Override protected synchronized void stopInternal() throws LifecycleException { super.stopInternal(); // Close and release everything associated with our db. if (dbConnection != null) { try { dbConnection.commit(); } catch (SQLException e) { // Ignore } close(dbConnection); } }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override protected synchronized void startInternal() throws LifecycleException { super.startInternal(); if (store == null) log.error("No Store configured, persistence disabled"); else if (store instanceof Lifecycle) ((Lifecycle)store).start(); setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
Override protected synchronized void stopInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug("Stopping"); setState(LifecycleState.STOPPING); if (getStore() != null && saveOnRestart) { unload(); } else { // Expire all active sessions Session sessions[] = findSessions(); for (int i = 0; i < sessions.length; i++) { StandardSession session = (StandardSession) sessions[i]; if (!session.isValid()) continue; session.expire(); } } if (getStore() != null && getStore() instanceof Lifecycle) ((Lifecycle)getStore()).stop(); // Require a new random number generator if we are restarted super.stopInternal(); }
// in java/org/apache/catalina/valves/RequestFilterValve.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); if (!allowValid || !denyValid) { throw new LifecycleException( sm.getString("requestFilterValve.configInvalid")); } }
// in java/org/apache/catalina/valves/RequestFilterValve.java
Override protected synchronized void startInternal() throws LifecycleException { if (!allowValid || !denyValid) { throw new LifecycleException( sm.getString("requestFilterValve.configInvalid")); } super.startInternal(); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
Override protected synchronized void startInternal() throws LifecycleException { if (container instanceof Context) { container.addLifecycleListener(this); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); if (container instanceof Context) { container.removeLifecycleListener(this); } }
// in java/org/apache/catalina/valves/CrawlerSessionManagerValve.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); uaPattern = Pattern.compile(crawlerUserAgents); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
Override protected synchronized void startInternal() throws LifecycleException { try { open() ; } catch (SQLException e) { throw new LifecycleException(e); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); close() ; }
// in java/org/apache/catalina/valves/StuckThreadDetectionValve.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); if (log.isDebugEnabled()) { log.debug("Monitoring stuck threads with threshold = " + threshold + " sec"); } }
// in java/org/apache/catalina/valves/SemaphoreValve.java
Override protected synchronized void startInternal() throws LifecycleException { semaphore = new Semaphore(concurrency, fairness); setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/valves/SemaphoreValve.java
Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); semaphore = null; }
// in java/org/apache/catalina/valves/AccessLogValve.java
Override protected synchronized void startInternal() throws LifecycleException { // Initialize the Date formatters String format = getFileDateFormat(); if (format == null || format.length() == 0) { format = "yyyy-MM-dd"; setFileDateFormat(format); } fileDateFormatter = new SimpleDateFormat(format, Locale.US); fileDateFormatter.setTimeZone(timezone); dateStamp = fileDateFormatter.format(new Date(System.currentTimeMillis())); open(); setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/valves/AccessLogValve.java
Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); close(); }
// in java/org/apache/catalina/valves/ValveBase.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); containerLog = getContainer().getLogger(); }
// in java/org/apache/catalina/valves/ValveBase.java
Override protected synchronized void startInternal() throws LifecycleException { setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/valves/ValveBase.java
Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
Override protected synchronized void startInternal() throws LifecycleException { // Look up the SingleSignOn implementation in our request processing // path, if there is one Container parent = context.getParent(); while ((sso == null) && (parent != null)) { Valve valves[] = parent.getPipeline().getValves(); for (int i = 0; i < valves.length; i++) { if (valves[i] instanceof SingleSignOn) { sso = (SingleSignOn) valves[i]; break; } } if (sso == null) { parent = parent.getParent(); } } if (log.isDebugEnabled()) { if (sso != null) { log.debug("Found SingleSignOn Valve at " + sso); } else { log.debug("No SingleSignOn Valve is present"); } } sessionIdGenerator = new SessionIdGenerator(); sessionIdGenerator.setSecureRandomAlgorithm(getSecureRandomAlgorithm()); sessionIdGenerator.setSecureRandomClass(getSecureRandomClass()); sessionIdGenerator.setSecureRandomProvider(getSecureRandomProvider()); super.startInternal(); }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
Override protected synchronized void stopInternal() throws LifecycleException { super.stopInternal(); sso = null; }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
Override protected synchronized void startInternal() throws LifecycleException { super.startInternal(); // Generate a random secret key if (getKey() == null) { setKey(sessionIdGenerator.generateSessionId()); } // Generate the opaque string the same way if (getOpaque() == null) { setOpaque(sessionIdGenerator.generateSessionId()); } cnonces = new LinkedHashMap<String, DigestAuthenticator.NonceInfo>() { private static final long serialVersionUID = 1L; private static final long LOG_SUPPRESS_TIME = 5 * 60 * 1000; private long lastLog = 0; @Override protected boolean removeEldestEntry( Map.Entry<String,NonceInfo> eldest) { // This is called from a sync so keep it simple long currentTime = System.currentTimeMillis(); if (size() > getCnonceCacheSize()) { if (lastLog < currentTime && currentTime - eldest.getValue().getTimestamp() < getNonceValidity()) { // Replay attack is possible log.warn(sm.getString( "digestAuthenticator.cacheRemove")); lastLog = currentTime + LOG_SUPPRESS_TIME; } return true; } return false; } }; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); // Kerberos configuration file location String krb5Conf = System.getProperty(Constants.KRB5_CONF_PROPERTY); if (krb5Conf == null) { // System property not set, use the Tomcat default File krb5ConfFile = new File(container.getCatalinaBase(), Constants.DEFAULT_KRB5_CONF); System.setProperty(Constants.KRB5_CONF_PROPERTY, krb5ConfFile.getAbsolutePath()); } // JAAS configuration file location String jaasConf = System.getProperty(Constants.JAAS_CONF_PROPERTY); if (jaasConf == null) { // System property not set, use the Tomcat default File jaasConfFile = new File(container.getCatalinaBase(), Constants.DEFAULT_JAAS_CONF); System.setProperty(Constants.JAAS_CONF_PROPERTY, jaasConfFile.getAbsolutePath()); } // This property must be false for SPNEGO to work System.setProperty(Constants.USE_SUBJECT_CREDS_ONLY_PROPERTY, "false"); }
// in java/org/apache/catalina/deploy/NamingResources.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); // Set this before we register currently known naming resources to avoid // timing issues. Duplication registration is not an issue. resourceRequireExplicitRegistration = true; for (ContextResource cr : resources.values()) { try { MBeanUtils.createMBean(cr); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", cr.getName()), e); } } for (ContextEnvironment ce : envs.values()) { try { MBeanUtils.createMBean(ce); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", ce.getName()), e); } } for (ContextResourceLink crl : resourceLinks.values()) { try { MBeanUtils.createMBean(crl); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", crl.getName()), e); } } }
// in java/org/apache/catalina/deploy/NamingResources.java
Override protected void startInternal() throws LifecycleException { fireLifecycleEvent(CONFIGURE_START_EVENT, null); setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/deploy/NamingResources.java
Override protected void stopInternal() throws LifecycleException { cleanUp(); setState(LifecycleState.STOPPING); fireLifecycleEvent(CONFIGURE_STOP_EVENT, null); }
// in java/org/apache/catalina/deploy/NamingResources.java
Override protected void destroyInternal() throws LifecycleException { // Set this before we de-register currently known naming resources to // avoid timing issues. Duplication de-registration is not an issue. resourceRequireExplicitRegistration = false; // Destroy in reverse order to create, although it should not matter for (ContextResourceLink crl : resourceLinks.values()) { try { MBeanUtils.destroyMBean(crl); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", crl.getName()), e); } } for (ContextEnvironment ce : envs.values()) { try { MBeanUtils.destroyMBean(ce); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", ce.getName()), e); } } for (ContextResource cr : resources.values()) { try { MBeanUtils.destroyMBean(cr); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", cr.getName()), e); } } super.destroyInternal(); }
// in java/org/apache/catalina/ha/context/ReplicatedContext.java
Override protected synchronized void startInternal() throws LifecycleException { try { CatalinaCluster catclust = (CatalinaCluster)this.getCluster(); if (this.context == null) this.context = new ReplApplContext(this); if ( catclust != null ) { ReplicatedMap<String,Object> map = new ReplicatedMap<String,Object>(this, catclust.getChannel(),DEFAULT_REPL_TIMEOUT, getName(),getClassLoaders()); map.setChannelSendOptions(mapSendOptions); ((ReplApplContext)this.context).setAttributeMap(map); if (getAltDDName() != null) context.setAttribute(Globals.ALT_DD_ATTR, getAltDDName()); } super.startInternal(); } catch ( Exception x ) { log.error("Unable to start ReplicatedContext",x); throw new LifecycleException("Failed to start ReplicatedContext",x); } }
// in java/org/apache/catalina/ha/context/ReplicatedContext.java
Override protected synchronized void stopInternal() throws LifecycleException { super.stopInternal(); Map<String,Object> map = ((ReplApplContext)this.context).getAttributeMap(); if ( map!=null && map instanceof ReplicatedMap) { ((ReplicatedMap<?,?>)map).breakdown(); } }
// in java/org/apache/catalina/ha/session/JvmRouteBinderValve.java
Override protected synchronized void startInternal() throws LifecycleException { if (cluster == null) { Container hostContainer = getContainer(); // compatibility with JvmRouteBinderValve version 1.1 // ( setup at context.xml or context.xml.default ) if (!(hostContainer instanceof Host)) { if (log.isWarnEnabled()) { log.warn(sm.getString("jvmRoute.configure.warn")); } hostContainer = hostContainer.getParent(); } if (hostContainer instanceof Host && ((Host) hostContainer).getCluster() != null) { cluster = (CatalinaCluster) ((Host) hostContainer).getCluster(); } else { Container engine = hostContainer.getParent() ; if (engine instanceof Engine && ((Engine) engine).getCluster() != null) { cluster = (CatalinaCluster) ((Engine) engine).getCluster(); } } } if (log.isInfoEnabled()) { log.info(sm.getString("jvmRoute.valve.started")); if (cluster == null) { log.info(sm.getString("jvmRoute.noCluster")); } } super.startInternal(); }
// in java/org/apache/catalina/ha/session/JvmRouteBinderValve.java
Override protected synchronized void stopInternal() throws LifecycleException { super.stopInternal(); cluster = null; numberOfSessions = 0; if (log.isInfoEnabled()) { log.info(sm.getString("jvmRoute.valve.stopped")); } }
// in java/org/apache/catalina/ha/session/BackupManager.java
Override protected synchronized void startInternal() throws LifecycleException { super.startInternal(); try { if (getCluster() == null) { Cluster cluster = getContainer().getCluster(); if (cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster)cluster); } else { throw new LifecycleException( sm.getString("backupManager.noCluster", getName())); } } cluster.registerManager(this); LazyReplicatedMap<String,Session> map = new LazyReplicatedMap<String,Session>(this, cluster.getChannel(), rpcTimeout, getMapName(), getClassLoaders()); map.setChannelSendOptions(mapSendOptions); this.sessions = map; } catch ( Exception x ) { log.error(sm.getString("backupManager.startUnable", getName()),x); throw new LifecycleException(sm.getString("backupManager.startFailed", getName()),x); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/ha/session/BackupManager.java
Override protected synchronized void stopInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug(sm.getString("backupManager.stopped", getName())); setState(LifecycleState.STOPPING); if (sessions instanceof LazyReplicatedMap) { LazyReplicatedMap<String,Session> map = (LazyReplicatedMap<String,Session>)sessions; map.breakdown(); } cluster.removeManager(this); super.stopInternal(); }
// in java/org/apache/catalina/ha/session/JvmRouteSessionIDBinderListener.java
public void start() throws LifecycleException { if (started) return; getCluster().addClusterListener(this); started = true; if (log.isInfoEnabled()) log.info(sm.getString("jvmRoute.clusterListener.started")); }
// in java/org/apache/catalina/ha/session/JvmRouteSessionIDBinderListener.java
public void stop() throws LifecycleException { started = false; getCluster().removeClusterListener(this); if (log.isInfoEnabled()) log.info(sm.getString("jvmRoute.clusterListener.stopped")); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
Override protected synchronized void startInternal() throws LifecycleException { super.startInternal(); // Load unloaded sessions, if any try { //the channel is already running Cluster cluster = getCluster() ; // stop remove cluster binding //wow, how many nested levels of if statements can we have ;) if(cluster == null) { Container context = getContainer() ; if(context != null && context instanceof Context) { Container host = context.getParent() ; if(host != null && host instanceof Host) { cluster = host.getCluster(); if(cluster != null && cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster) cluster) ; } else { Container engine = host.getParent() ; if(engine != null && engine instanceof Engine) { cluster = engine.getCluster(); if(cluster != null && cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster) cluster) ; } } else { cluster = null ; } } } } } if (cluster == null) { log.error(sm.getString("deltaManager.noCluster", getName())); return; } else { if (log.isInfoEnabled()) { String type = "unknown" ; if( cluster.getContainer() instanceof Host){ type = "Host" ; } else if( cluster.getContainer() instanceof Engine){ type = "Engine" ; } log.info(sm.getString("deltaManager.registerCluster", getName(), type, cluster.getClusterName())); } } if (log.isInfoEnabled()) log.info(sm.getString("deltaManager.startClustering", getName())); //to survice context reloads, as only a stop/start is called, not // createManager cluster.registerManager(this); getAllClusterSessions(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("deltaManager.managerLoad"), t); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
Override protected synchronized void stopInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.stopped", getName())); setState(LifecycleState.STOPPING); // Expire all active sessions if (log.isInfoEnabled()) log.info(sm.getString("deltaManager.expireSessions", getName())); Session sessions[] = findSessions(); for (int i = 0; i < sessions.length; i++) { DeltaSession session = (DeltaSession) sessions[i]; if (!session.isValid()) continue; try { session.expire(true, isExpireSessionsOnShutdown()); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } // Require a new random number generator if we are restarted getCluster().removeManager(this); super.stopInternal(); replicationValve = null; }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOn.java
Override protected synchronized void startInternal() throws LifecycleException { clusterSSOListener = new ClusterSingleSignOnListener(); clusterSSOListener.setClusterSSO(this); // Load the cluster component, if any try { //the channel is already running Cluster cluster = getCluster(); // stop remove cluster binding if(cluster == null) { Container host = getContainer(); if(host != null && host instanceof Host) { cluster = host.getCluster(); if(cluster != null && cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster) cluster); getCluster().addClusterListener(clusterSSOListener); } else { Container engine = host.getParent(); if(engine != null && engine instanceof Engine) { cluster = engine.getCluster(); if(cluster != null && cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster) cluster); getCluster().addClusterListener(clusterSSOListener); } } else { cluster = null; } } } } if (cluster == null) { throw new LifecycleException( "There is no Cluster for ClusterSingleSignOn"); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new LifecycleException( "ClusterSingleSignOn exception during clusterLoad " + t); } super.startInternal(); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOn.java
Override protected synchronized void stopInternal() throws LifecycleException { super.stopInternal(); if (getCluster() != null) { getCluster().removeClusterListener(clusterSSOListener); } }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
Override public void stop() throws LifecycleException { started = false; getCluster().removeClusterListener(this); count = 0; if (watcher != null) { watcher.clear(); watcher = null; } if (log.isInfoEnabled()) log.info(sm.getString("farmWarDeployer.stopped")); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
Override protected void startInternal() throws LifecycleException { if (log.isInfoEnabled()) log.info("Cluster is about to start"); try { checkDefaults(); registerClusterValve(); channel.addMembershipListener(this); channel.addChannelListener(this); channel.start(channelStartOptions); if (clusterDeployer != null) clusterDeployer.start(); //register JMX objects ClusterJmxHelper.registerDefaultCluster(this); // Notify our interested LifecycleListeners } catch (Exception x) { log.error("Unable to start cluster.", x); throw new LifecycleException(x); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/ha/tcp/SimpleTcpCluster.java
Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); if (clusterDeployer != null) clusterDeployer.stop(); this.managers.clear(); try { if ( clusterDeployer != null ) clusterDeployer.setCluster(null); channel.stop(channelStartOptions); channel.removeChannelListener(this); channel.removeMembershipListener(this); this.unregisterClusterValve(); //unregister JMX objects ClusterJmxHelper.unregisterDefaultCluster(this); } catch (Exception x) { log.error("Unable to stop cluster valve.", x); } }
// in java/org/apache/catalina/connector/Connector.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); // Initialize adapter adapter = new CoyoteAdapter(this); protocolHandler.setAdapter(adapter); // Make sure parseBodyMethodsSet has a default if( null == parseBodyMethodsSet ) { setParseBodyMethods(getParseBodyMethods()); } try { protocolHandler.init(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerInitializationFailed"), e); } // Initialize mapper listener mapperListener.init(); }
// in java/org/apache/catalina/connector/Connector.java
Override protected void startInternal() throws LifecycleException { // Validate settings before starting if (getPort() < 0) { throw new LifecycleException(sm.getString( "coyoteConnector.invalidPort", Integer.valueOf(getPort()))); } setState(LifecycleState.STARTING); try { protocolHandler.start(); } catch (Exception e) { String errPrefix = ""; if(this.service != null) { errPrefix += "service.getName(): \"" + this.service.getName() + "\"; "; } throw new LifecycleException (errPrefix + " " + sm.getString ("coyoteConnector.protocolHandlerStartFailed"), e); } mapperListener.start(); }
// in java/org/apache/catalina/connector/Connector.java
Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); try { protocolHandler.stop(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerStopFailed"), e); } mapperListener.stop(); }
// in java/org/apache/catalina/connector/Connector.java
Override protected void destroyInternal() throws LifecycleException { mapperListener.destroy(); try { protocolHandler.destroy(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerDestroyFailed"), e); } if (getService() != null) { getService().removeConnector(this); } super.destroyInternal(); }
// in java/org/apache/catalina/connector/MapperListener.java
Override public void startInternal() throws LifecycleException { setState(LifecycleState.STARTING); // Find any components that have already been initialized since the // MBean listener won't be notified as those components will have // already registered their MBeans findDefaultHost(); Engine engine = (Engine) connector.getService().getContainer(); addListeners(engine); Container[] conHosts = engine.findChildren(); for (Container conHost : conHosts) { Host host = (Host) conHost; if (!LifecycleState.NEW.equals(host.getState())) { // Registering the host will register the context and wrappers registerHost(host); } } }
// in java/org/apache/catalina/connector/MapperListener.java
Override public void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
Override protected void initInternal() throws LifecycleException { // NOOP - Don't register this Valve in JMX }
// in java/org/apache/catalina/core/StandardHost.java
Override protected synchronized void startInternal() throws LifecycleException { // Set error report valve String errorValve = getErrorReportValveClass(); if ((errorValve != null) && (!errorValve.equals(""))) { try { boolean found = false; Valve[] valves = getPipeline().getValves(); for (Valve valve : valves) { if (errorValve.equals(valve.getClass().getName())) { found = true; break; } } if(!found) { Valve valve = (Valve) Class.forName(errorValve).newInstance(); getPipeline().addValve(valve); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString( "standardHost.invalidErrorReportValveClass", errorValve), t); } } super.startInternal(); }
// in java/org/apache/catalina/core/ContainerBase.java
Override protected void initInternal() throws LifecycleException { BlockingQueue<Runnable> startStopQueue = new LinkedBlockingQueue<Runnable>(); startStopExecutor = new ThreadPoolExecutor( getStartStopThreadsInternal(), getStartStopThreadsInternal(), 10, TimeUnit.SECONDS, startStopQueue); startStopExecutor.allowCoreThreadTimeOut(true); super.initInternal(); }
// in java/org/apache/catalina/core/ContainerBase.java
Override protected synchronized void startInternal() throws LifecycleException { // Start our subordinate components, if any if ((loader != null) && (loader instanceof Lifecycle)) ((Lifecycle) loader).start(); logger = null; getLogger(); if ((manager != null) && (manager instanceof Lifecycle)) ((Lifecycle) manager).start(); if ((cluster != null) && (cluster instanceof Lifecycle)) ((Lifecycle) cluster).start(); Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) ((Lifecycle) realm).start(); if ((resources != null) && (resources instanceof Lifecycle)) ((Lifecycle) resources).start(); // Start our child containers, if any Container children[] = findChildren(); List<Future<Void>> results = new ArrayList<Future<Void>>(); for (int i = 0; i < children.length; i++) { results.add(startStopExecutor.submit(new StartChild(children[i]))); } boolean fail = false; for (Future<Void> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString("containerBase.threadedStartFailed"), e); fail = true; } } if (fail) { throw new LifecycleException( sm.getString("containerBase.threadedStartFailed")); } // Start the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle) ((Lifecycle) pipeline).start(); setState(LifecycleState.STARTING); // Start our thread threadStart(); }
// in java/org/apache/catalina/core/ContainerBase.java
Override protected synchronized void stopInternal() throws LifecycleException { // Stop our thread threadStop(); setState(LifecycleState.STOPPING); // Stop the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle && ((Lifecycle) pipeline).getState().isAvailable()) { ((Lifecycle) pipeline).stop(); } // Stop our child containers, if any Container children[] = findChildren(); List<Future<Void>> results = new ArrayList<Future<Void>>(); for (int i = 0; i < children.length; i++) { results.add(startStopExecutor.submit(new StopChild(children[i]))); } boolean fail = false; for (Future<Void> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString("containerBase.threadedStopFailed"), e); fail = true; } } if (fail) { throw new LifecycleException( sm.getString("containerBase.threadedStopFailed")); } // Stop our subordinate components, if any if ((resources != null) && (resources instanceof Lifecycle)) { ((Lifecycle) resources).stop(); } Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) { ((Lifecycle) realm).stop(); } if ((cluster != null) && (cluster instanceof Lifecycle)) { ((Lifecycle) cluster).stop(); } if ((manager != null) && (manager instanceof Lifecycle) && ((Lifecycle) manager).getState().isAvailable() ) { ((Lifecycle) manager).stop(); } if ((loader != null) && (loader instanceof Lifecycle)) { ((Lifecycle) loader).stop(); } }
// in java/org/apache/catalina/core/ContainerBase.java
Override protected void destroyInternal() throws LifecycleException { if ((manager != null) && (manager instanceof Lifecycle)) { ((Lifecycle) manager).destroy(); } Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) { ((Lifecycle) realm).destroy(); } if ((cluster != null) && (cluster instanceof Lifecycle)) { ((Lifecycle) cluster).destroy(); } if ((loader != null) && (loader instanceof Lifecycle)) { ((Lifecycle) loader).destroy(); } // Stop the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle) { ((Lifecycle) pipeline).destroy(); } // Remove children now this container is being destroyed for (Container child : findChildren()) { removeChild(child); } // Required if the child is destroyed directly. if (parent != null) { parent.removeChild(this); } // If init fails, this may be null if (startStopExecutor != null) { startStopExecutor.shutdownNow(); } super.destroyInternal(); }
// in java/org/apache/catalina/core/ContainerBase.java
Override public Void call() throws LifecycleException { child.start(); return null; }
// in java/org/apache/catalina/core/ContainerBase.java
Override public Void call() throws LifecycleException { if (child.getState().isAvailable()) { child.stop(); } return null; }
// in java/org/apache/catalina/core/StandardServer.java
Override protected void startInternal() throws LifecycleException { fireLifecycleEvent(CONFIGURE_START_EVENT, null); setState(LifecycleState.STARTING); globalNamingResources.start(); // Start our defined Services synchronized (services) { for (int i = 0; i < services.length; i++) { services[i].start(); } } }
// in java/org/apache/catalina/core/StandardServer.java
Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); fireLifecycleEvent(CONFIGURE_STOP_EVENT, null); // Stop our defined Services for (int i = 0; i < services.length; i++) { services[i].stop(); } globalNamingResources.stop(); stopAwait(); }
// in java/org/apache/catalina/core/StandardServer.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); // Register global String cache // Note although the cache is global, if there are multiple Servers // present in the JVM (may happen when embedding) then the same cache // will be registered under multiple names onameStringCache = register(new StringCache(), "type=StringCache"); // Register the MBeanFactory MBeanFactory factory = new MBeanFactory(); factory.setContainer(this); onameMBeanFactory = register(factory, "type=MBeanFactory"); // Register the naming resources globalNamingResources.init(); // Populate the extension validator with JARs from common and shared // class loaders if (getCatalina() != null) { ClassLoader cl = getCatalina().getParentClassLoader(); // Walk the class loader hierarchy. Stop at the system class loader. // This will add the shared (if present) and common class loaders while (cl != null && cl != ClassLoader.getSystemClassLoader()) { if (cl instanceof URLClassLoader) { URL[] urls = ((URLClassLoader) cl).getURLs(); for (URL url : urls) { if (url.getProtocol().equals("file")) { try { File f = new File (url.toURI()); if (f.isFile() && f.getName().endsWith(".jar")) { ExtensionValidator.addSystemResource(f); } } catch (URISyntaxException e) { // Ignore } catch (IOException e) { // Ignore } } } } cl = cl.getParent(); } } // Initialize our defined Services for (int i = 0; i < services.length; i++) { services[i].init(); } }
// in java/org/apache/catalina/core/StandardServer.java
Override protected void destroyInternal() throws LifecycleException { // Destroy our defined Services for (int i = 0; i < services.length; i++) { services[i].destroy(); } globalNamingResources.destroy(); unregister(onameMBeanFactory); unregister(onameStringCache); super.destroyInternal(); }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
Override protected void startInternal() throws LifecycleException { taskqueue = new TaskQueue(maxQueueSize); TaskThreadFactory tf = new TaskThreadFactory(namePrefix,daemon,getThreadPriority()); executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), maxIdleTime, TimeUnit.MILLISECONDS,taskqueue, tf); if (prestartminSpareThreads) { executor.prestartAllCoreThreads(); } taskqueue.setParent(executor); setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); if ( executor != null ) executor.shutdownNow(); executor = null; taskqueue = null; }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
Override protected void destroyInternal() throws LifecycleException { super.destroyInternal(); }
// in java/org/apache/catalina/core/StandardService.java
Override protected void startInternal() throws LifecycleException { if(log.isInfoEnabled()) log.info(sm.getString("standardService.start.name", this.name)); setState(LifecycleState.STARTING); // Start our defined Container first if (container != null) { synchronized (container) { container.start(); } } synchronized (executors) { for (Executor executor: executors) { executor.start(); } } // Start our defined Connectors second synchronized (connectors) { for (Connector connector: connectors) { try { // If it has already failed, don't try and start it if (connector.getState() != LifecycleState.FAILED) { connector.start(); } } catch (Exception e) { log.error(sm.getString( "standardService.connector.startFailed", connector), e); } } } }
// in java/org/apache/catalina/core/StandardService.java
Override protected void stopInternal() throws LifecycleException { // Pause connectors first synchronized (connectors) { for (Connector connector: connectors) { try { connector.pause(); } catch (Exception e) { log.error(sm.getString( "standardService.connector.pauseFailed", connector), e); } } } if(log.isInfoEnabled()) log.info(sm.getString("standardService.stop.name", this.name)); setState(LifecycleState.STOPPING); // Stop our defined Container second if (container != null) { synchronized (container) { container.stop(); } } // Now stop the connectors synchronized (connectors) { for (Connector connector: connectors) { if (!LifecycleState.STARTED.equals( connector.getState())) { // Connectors only need stopping if they are currently // started. They may have failed to start or may have been // stopped (e.g. via a JMX call) continue; } try { connector.stop(); } catch (Exception e) { log.error(sm.getString( "standardService.connector.stopFailed", connector), e); } } } synchronized (executors) { for (Executor executor: executors) { executor.stop(); } } }
// in java/org/apache/catalina/core/StandardService.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); if (container != null) { container.init(); } // Initialize any Executors for (Executor executor : findExecutors()) { if (executor instanceof JmxEnabled) { ((JmxEnabled) executor).setDomain(getDomain()); } executor.init(); } // Initialize our defined Connectors synchronized (connectors) { for (Connector connector : connectors) { try { connector.init(); } catch (Exception e) { String message = sm.getString( "standardService.connector.initFailed", connector); log.error(message, e); if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) throw new LifecycleException(message); } } } }
// in java/org/apache/catalina/core/StandardService.java
Override protected void destroyInternal() throws LifecycleException { // Destroy our defined Connectors synchronized (connectors) { for (Connector connector : connectors) { try { connector.destroy(); } catch (Exception e) { log.error(sm.getString( "standardService.connector.destroyfailed", connector), e); } } } // Destroy any Executors for (Executor executor : findExecutors()) { executor.destroy(); } if (container != null) { container.destroy(); } super.destroyInternal(); }
// in java/org/apache/catalina/core/StandardContext.java
Override protected synchronized void startInternal() throws LifecycleException { if(log.isDebugEnabled()) log.debug("Starting " + getBaseName()); // Send j2ee.state.starting notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.starting", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } setConfigured(false); boolean ok = true; // Currently this is effectively a NO-OP but needs to be called to // ensure the NamingResources follows the correct lifecycle if (namingResources != null) { namingResources.start(); } // Add missing components as necessary if (webappResources == null) { // (1) Required by Loader if (log.isDebugEnabled()) log.debug("Configuring default Resources"); try { if ((getDocBase() != null) && (getDocBase().endsWith(".war")) && (!(new File(getBasePath())).isDirectory())) setResources(new WARDirContext()); else setResources(new FileDirContext()); } catch (IllegalArgumentException e) { log.error("Error initializing resources: " + e.getMessage()); ok = false; } } if (ok) { if (!resourcesStart()) { log.error( "Error in resourceStart()"); ok = false; } } if (getLoader() == null) { WebappLoader webappLoader = new WebappLoader(getParentClassLoader()); webappLoader.setDelegate(getDelegate()); setLoader(webappLoader); } // Initialize character set mapper getCharsetMapper(); // Post work directory postWorkDirectory(); // Validate required extensions boolean dependencyCheck = true; try { dependencyCheck = ExtensionValidator.validateApplication (getResources(), this); } catch (IOException ioe) { log.error("Error in dependencyCheck", ioe); dependencyCheck = false; } if (!dependencyCheck) { // do not make application available if depency check fails ok = false; } // Reading the "catalina.useNaming" environment variable String useNamingProperty = System.getProperty("catalina.useNaming"); if ((useNamingProperty != null) && (useNamingProperty.equals("false"))) { useNaming = false; } if (ok && isUseNaming()) { if (getNamingContextListener() == null) { NamingContextListener ncl = new NamingContextListener(); ncl.setName(getNamingContextName()); ncl.setExceptionOnFailedWrite(getJndiExceptionOnFailedWrite()); addLifecycleListener(ncl); setNamingContextListener(ncl); } } // Standard container startup if (log.isDebugEnabled()) log.debug("Processing standard container startup"); // Binding thread ClassLoader oldCCL = bindThread(); try { if (ok) { // Start our subordinate components, if any if ((loader != null) && (loader instanceof Lifecycle)) ((Lifecycle) loader).start(); // since the loader just started, the webapp classloader is now // created. setClassLoaderProperty("antiJARLocking", getAntiJARLocking()); setClassLoaderProperty("clearReferencesStatic", getClearReferencesStatic()); setClassLoaderProperty("clearReferencesStopThreads", getClearReferencesStopThreads()); setClassLoaderProperty("clearReferencesStopTimerThreads", getClearReferencesStopTimerThreads()); setClassLoaderProperty("clearReferencesHttpClientKeepAliveThread", getClearReferencesHttpClientKeepAliveThread()); // By calling unbindThread and bindThread in a row, we setup the // current Thread CCL to be the webapp classloader unbindThread(oldCCL); oldCCL = bindThread(); // Initialize logger again. Other components might have used it // too early, so it should be reset. logger = null; getLogger(); if ((cluster != null) && (cluster instanceof Lifecycle)) ((Lifecycle) cluster).start(); Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) ((Lifecycle) realm).start(); if ((resources != null) && (resources instanceof Lifecycle)) ((Lifecycle) resources).start(); // Notify our interested LifecycleListeners fireLifecycleEvent(Lifecycle.CONFIGURE_START_EVENT, null); // Start our child containers, if not already started for (Container child : findChildren()) { if (!child.getState().isAvailable()) { child.start(); } } // Start the Valves in our pipeline (including the basic), // if any if (pipeline instanceof Lifecycle) { ((Lifecycle) pipeline).start(); } // Acquire clustered manager Manager contextManager = null; if (manager == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("standardContext.cluster.noManager", Boolean.valueOf((getCluster() != null)), Boolean.valueOf(distributable))); } if ( (getCluster() != null) && distributable) { try { contextManager = getCluster().createManager(getName()); } catch (Exception ex) { log.error("standardContext.clusterFail", ex); ok = false; } } else { contextManager = new StandardManager(); } } // Configure default manager if none was specified if (contextManager != null) { if (log.isDebugEnabled()) { log.debug(sm.getString("standardContext.manager", contextManager.getClass().getName())); } setManager(contextManager); } if (manager!=null && (getCluster() != null) && distributable) { //let the cluster know that there is a context that is distributable //and that it has its own manager getCluster().registerManager(manager); } } } finally { // Unbinding thread unbindThread(oldCCL); } if (!getConfigured()) { log.error( "Error getConfigured"); ok = false; } // We put the resources into the servlet context if (ok) getServletContext().setAttribute (Globals.RESOURCES_ATTR, getResources()); // Initialize associated mapper mapper.setContext(getPath(), welcomeFiles, resources); // Binding thread oldCCL = bindThread(); if (ok ) { if (getInstanceManager() == null) { javax.naming.Context context = null; if (isUseNaming() && getNamingContextListener() != null) { context = getNamingContextListener().getEnvContext(); } Map<String, Map<String, String>> injectionMap = buildInjectionMap( getIgnoreAnnotations() ? new NamingResources(): getNamingResources()); setInstanceManager(new DefaultInstanceManager(context, injectionMap, this, this.getClass().getClassLoader())); getServletContext().setAttribute( InstanceManager.class.getName(), getInstanceManager()); } } try { // Create context attributes that will be required if (ok) { getServletContext().setAttribute( JarScanner.class.getName(), getJarScanner()); } // Set up the context init params mergeParameters(); // Call ServletContainerInitializers for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializers.entrySet()) { try { entry.getKey().onStartup(entry.getValue(), getServletContext()); } catch (ServletException e) { // TODO: Log error ok = false; break; } } // Configure and call application event listeners if (ok) { if (!listenerStart()) { log.error( "Error listenerStart"); ok = false; } } try { // Start manager if ((manager != null) && (manager instanceof Lifecycle)) { ((Lifecycle) getManager()).start(); } // Start ContainerBackgroundProcessor thread super.threadStart(); } catch(Exception e) { log.error("Error manager.start()", e); ok = false; } // Configure and call application filters if (ok) { if (!filterStart()) { log.error("Error filterStart"); ok = false; } } // Load and initialize all "load on startup" servlets if (ok) { loadOnStartup(findChildren()); } } finally { // Unbinding thread unbindThread(oldCCL); } // Set available status depending upon startup success if (ok) { if (log.isDebugEnabled()) log.debug("Starting completed"); } else { log.error(sm.getString("standardContext.startFailed", getName())); } startTime=System.currentTimeMillis(); // Send j2ee.state.running notification if (ok && (this.getObjectName() != null)) { Notification notification = new Notification("j2ee.state.running", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } // Close all JARs right away to avoid always opening a peak number // of files on startup if (getLoader() instanceof WebappLoader) { ((WebappLoader) getLoader()).closeJARs(true); } // Reinitializing if something went wrong if (!ok) { setState(LifecycleState.FAILED); } else { setState(LifecycleState.STARTING); } }
// in java/org/apache/catalina/core/StandardContext.java
Override protected synchronized void stopInternal() throws LifecycleException { // Send j2ee.state.stopping notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.stopping", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } setState(LifecycleState.STOPPING); // Binding thread ClassLoader oldCCL = bindThread(); try { // Stop our child containers, if any final Container[] children = findChildren(); ClassLoader old = bindThread(); try { for (int i = 0; i < children.length; i++) { children[i].stop(); } // Stop our filters filterStop(); // Stop ContainerBackgroundProcessor thread threadStop(); if (manager != null && manager instanceof Lifecycle && ((Lifecycle) manager).getState().isAvailable()) { ((Lifecycle) manager).stop(); } // Stop our application listeners listenerStop(); } finally{ unbindThread(old); } // Finalize our character set mapper setCharsetMapper(null); // Normal container shutdown processing if (log.isDebugEnabled()) log.debug("Processing standard container shutdown"); // JNDI resources are unbound in CONFIGURE_STOP_EVENT so stop // naming resoucres before they are unbound since NamingResoucres // does a JNDI lookup to retrieve the resource. This needs to be // after the application has finished with the resource if (namingResources != null) { namingResources.stop(); } fireLifecycleEvent(Lifecycle.CONFIGURE_STOP_EVENT, null); // Stop the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle && ((Lifecycle) pipeline).getState().isAvailable()) { ((Lifecycle) pipeline).stop(); } // Clear all application-originated servlet context attributes if (context != null) context.clearAttributes(); // Stop resources resourcesStop(); Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) { ((Lifecycle) realm).stop(); } if ((cluster != null) && (cluster instanceof Lifecycle)) { ((Lifecycle) cluster).stop(); } if ((loader != null) && (loader instanceof Lifecycle)) { ((Lifecycle) loader).stop(); } } finally { // Unbinding thread unbindThread(oldCCL); } // Send j2ee.state.stopped notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.stopped", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } // Reset application context context = null; // This object will no longer be visible or used. try { resetContext(); } catch( Exception ex ) { log.error( "Error reseting context " + this + " " + ex, ex ); } //reset the instance manager instanceManager = null; if (log.isDebugEnabled()) log.debug("Stopping complete"); }
// in java/org/apache/catalina/core/StandardContext.java
Override protected void destroyInternal() throws LifecycleException { // If in state NEW when destroy is called, the object name will never // have been set so the notification can't be created if (getObjectName() != null) { // Send j2ee.object.deleted notification Notification notification = new Notification("j2ee.object.deleted", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } if (namingResources != null) { namingResources.destroy(); } synchronized (instanceListenersLock) { instanceListeners = new String[0]; } super.destroyInternal(); }
// in java/org/apache/catalina/core/StandardContext.java
Override protected void initInternal() throws LifecycleException { super.initInternal(); if (processTlds) { this.addLifecycleListener(new TldConfig()); } // Register the naming resources if (namingResources != null) { namingResources.init(); } // Send j2ee.object.created notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.object.created", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } }
// in java/org/apache/catalina/core/StandardPipeline.java
Override protected synchronized void startInternal() throws LifecycleException { // Start the Valves in our pipeline (including the basic), if any Valve current = first; if (current == null) { current = basic; } while (current != null) { if (current instanceof Lifecycle) ((Lifecycle) current).start(); current = current.getNext(); } setState(LifecycleState.STARTING); }
// in java/org/apache/catalina/core/StandardPipeline.java
Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); // Stop the Valves in our pipeline (including the basic), if any Valve current = first; if (current == null) { current = basic; } while (current != null) { if (current instanceof Lifecycle) ((Lifecycle) current).stop(); current = current.getNext(); } }
// in java/org/apache/catalina/core/StandardWrapper.java
Override protected synchronized void startInternal() throws LifecycleException { // Send j2ee.state.starting notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.starting", this.getObjectName(), sequenceNumber++); broadcaster.sendNotification(notification); } // Start up this component super.startInternal(); setAvailable(0L); // Send j2ee.state.running notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.running", this.getObjectName(), sequenceNumber++); broadcaster.sendNotification(notification); } }
// in java/org/apache/catalina/core/StandardWrapper.java
Override protected synchronized void stopInternal() throws LifecycleException { setAvailable(Long.MAX_VALUE); // Send j2ee.state.stopping notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.stopping", this.getObjectName(), sequenceNumber++); broadcaster.sendNotification(notification); } // Shut down our servlet instance (if it has been initialized) try { unload(); } catch (ServletException e) { getServletContext().log(sm.getString ("standardWrapper.unloadException", getName()), e); } // Shut down this component super.stopInternal(); // Send j2ee.state.stoppped notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.stopped", this.getObjectName(), sequenceNumber++); broadcaster.sendNotification(notification); } // Send j2ee.object.deleted notification Notification notification = new Notification("j2ee.object.deleted", this.getObjectName(), sequenceNumber++); broadcaster.sendNotification(notification); }
// in java/org/apache/catalina/core/StandardEngine.java
Override protected void initInternal() throws LifecycleException { // Ensure that a Realm is present before any attempt is made to start // one. This will create the default NullRealm if necessary. getRealm(); super.initInternal(); }
// in java/org/apache/catalina/core/StandardEngine.java
Override protected synchronized void startInternal() throws LifecycleException { // Log our server identification information if(log.isInfoEnabled()) log.info( "Starting Servlet Engine: " + ServerInfo.getServerInfo()); // Standard container startup super.startInternal(); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
Override protected void initInternal() throws LifecycleException { // If oname is not null then registration has already happened via // preRegister(). if (oname == null) { mserver = Registry.getRegistry(null, null).getMBeanServer(); oname = register(this, getObjectNameKeyProperties()); } }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
Override protected void destroyInternal() throws LifecycleException { unregister(oname); }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void init() throws LifecycleException { if (!state.equals(LifecycleState.NEW)) { invalidTransition(Lifecycle.BEFORE_INIT_EVENT); } setStateInternal(LifecycleState.INITIALIZING, null, false); try { initInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); } setStateInternal(LifecycleState.INITIALIZED, null, false); }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void start() throws LifecycleException { if (LifecycleState.STARTING_PREP.equals(state) || LifecycleState.STARTING.equals(state) || LifecycleState.STARTED.equals(state)) { if (log.isDebugEnabled()) { Exception e = new LifecycleException(); log.debug(sm.getString("lifecycleBase.alreadyStarted", toString()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("lifecycleBase.alreadyStarted", toString())); } return; } if (state.equals(LifecycleState.NEW)) { init(); } else if (state.equals(LifecycleState.FAILED)){ stop(); } else if (!state.equals(LifecycleState.INITIALIZED) && !state.equals(LifecycleState.STOPPED)) { invalidTransition(Lifecycle.BEFORE_START_EVENT); } setStateInternal(LifecycleState.STARTING_PREP, null, false); try { startInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.startFail",toString()), t); } if (state.equals(LifecycleState.FAILED) || state.equals(LifecycleState.MUST_STOP)) { stop(); } else { // Shouldn't be necessary but acts as a check that sub-classes are // doing what they are supposed to. if (!state.equals(LifecycleState.STARTING)) { invalidTransition(Lifecycle.AFTER_START_EVENT); } setStateInternal(LifecycleState.STARTED, null, false); } }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void stop() throws LifecycleException { if (LifecycleState.STOPPING_PREP.equals(state) || LifecycleState.STOPPING.equals(state) || LifecycleState.STOPPED.equals(state)) { if (log.isDebugEnabled()) { Exception e = new LifecycleException(); log.debug(sm.getString("lifecycleBase.alreadyStopped", toString()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("lifecycleBase.alreadyStopped", toString())); } return; } if (state.equals(LifecycleState.NEW)) { state = LifecycleState.STOPPED; return; } if (!state.equals(LifecycleState.STARTED) && !state.equals(LifecycleState.FAILED) && !state.equals(LifecycleState.MUST_STOP)) { invalidTransition(Lifecycle.BEFORE_STOP_EVENT); } if (state.equals(LifecycleState.FAILED)) { // Don't transition to STOPPING_PREP as that would briefly mark the // component as available but do ensure the BEFORE_STOP_EVENT is // fired fireLifecycleEvent(BEFORE_STOP_EVENT, null); } else { setStateInternal(LifecycleState.STOPPING_PREP, null, false); } try { stopInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.stopFail",toString()), t); } if (state.equals(LifecycleState.MUST_DESTROY)) { // Complete stop process first setStateInternal(LifecycleState.STOPPED, null, false); destroy(); } else { // Shouldn't be necessary but acts as a check that sub-classes are // doing what they are supposed to. if (!state.equals(LifecycleState.STOPPING)) { invalidTransition(Lifecycle.AFTER_STOP_EVENT); } setStateInternal(LifecycleState.STOPPED, null, false); } }
// in java/org/apache/catalina/util/LifecycleBase.java
Override public final synchronized void destroy() throws LifecycleException { if (LifecycleState.FAILED.equals(state)) { try { // Triggers clean-up stop(); } catch (LifecycleException e) { // Just log. Still want to destroy. log.warn(sm.getString("lifecycleBase.destroyStopFail"), e); } } if (LifecycleState.DESTROYING.equals(state) || LifecycleState.DESTROYED.equals(state)) { if (log.isDebugEnabled()) { Exception e = new LifecycleException(); log.debug(sm.getString("lifecycleBase.alreadyDestroyed", toString()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("lifecycleBase.alreadyDestroyed", toString())); } return; } if (!state.equals(LifecycleState.STOPPED) && !state.equals(LifecycleState.FAILED) && !state.equals(LifecycleState.NEW) && !state.equals(LifecycleState.INITIALIZED)) { invalidTransition(Lifecycle.BEFORE_DESTROY_EVENT); } setStateInternal(LifecycleState.DESTROYING, null, false); try { destroyInternal(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); } setStateInternal(LifecycleState.DESTROYED, null, false); }
// in java/org/apache/catalina/util/LifecycleBase.java
protected synchronized void setState(LifecycleState state) throws LifecycleException { setStateInternal(state, null, true); }
// in java/org/apache/catalina/util/LifecycleBase.java
protected synchronized void setState(LifecycleState state, Object data) throws LifecycleException { setStateInternal(state, data, true); }
// in java/org/apache/catalina/util/LifecycleBase.java
private synchronized void setStateInternal(LifecycleState state, Object data, boolean check) throws LifecycleException { if (log.isDebugEnabled()) { log.debug(sm.getString("lifecycleBase.setState", this, state)); } if (check) { // Must have been triggered by one of the abstract methods (assume // code in this class is correct) // null is never a valid state if (state == null) { invalidTransition("null"); // Unreachable code - here to stop eclipse complaining about // a possible NPE further down the method return; } // Any method can transition to failed // startInternal() permits STARTING_PREP to STARTING // stopInternal() permits STOPPING_PREP to STOPPING and FAILED to // STOPPING if (!(state == LifecycleState.FAILED || (this.state == LifecycleState.STARTING_PREP && state == LifecycleState.STARTING) || (this.state == LifecycleState.STOPPING_PREP && state == LifecycleState.STOPPING) || (this.state == LifecycleState.FAILED && state == LifecycleState.STOPPING))) { // No other transition permitted invalidTransition(state.name()); } } this.state = state; String lifecycleEvent = state.getLifecycleEvent(); if (lifecycleEvent != null) { fireLifecycleEvent(lifecycleEvent, data); } }
// in java/org/apache/catalina/util/LifecycleBase.java
private void invalidTransition(String type) throws LifecycleException { String msg = sm.getString("lifecycleBase.invalidTransition", type, toString(), state); throw new LifecycleException(msg); }
35
            
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { log.error("Catalina.stop: ", e); }
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) { throw new java.lang.Error(e); } else { log.error("Catalina.start", e); } }
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { log.error("Catalina.start: ", e); }
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { log.error("Catalina.stop", e); }
// in java/org/apache/catalina/realm/CombinedRealm.java
catch (LifecycleException e) { // If realm doesn't start can't authenticate against it iter.remove(); log.error(sm.getString("combinedRealm.realmStartFail", realm.getClass().getName()), e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (LifecycleException e){ throw new MBeanException(e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setLoader: stop: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setLoader: start: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setManager: stop: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setManager: start: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setCluster: stop: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setCluster: start: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setRealm: stop: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.setRealm: start: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.addChild: start: ", e); throw new IllegalStateException ("ContainerBase.addChild: start: " + e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.removeChild: stop: ", e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.removeChild: destroy: ", e); }
// in java/org/apache/catalina/core/StandardServer.java
catch (LifecycleException e) { // Ignore }
// in java/org/apache/catalina/core/StandardServer.java
catch (LifecycleException e) { // Ignore }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException e) { // Ignore }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException e) { // Ignore }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException e) { log.error(sm.getString( "standardService.connector.startFailed", connector), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException e) { log.error(sm.getString( "standardService.connector.stopFailed", connectors[j]), e); }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException x) { log.error("Executor.start", x); }
// in java/org/apache/catalina/core/StandardService.java
catch (LifecycleException e) { log.error("Executor.stop", e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.warn("standardContext.namingResource.destroy.fail", e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.warn("standardContext.namingResource.init.fail", e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.error( sm.getString("standardContext.stoppingContext", getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (LifecycleException e) { log.error( sm.getString("standardContext.startingContext", getName()), e); }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (LifecycleException e) { log.error("StandardPipeline.setBasic: stop", e); }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (LifecycleException e) { log.error("StandardPipeline.setBasic: start", e); return; }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (LifecycleException e) { log.error("StandardPipeline.addValve: start: ", e); }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (LifecycleException e) { log.error("StandardPipeline.removeValve: stop: ", e); }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (LifecycleException e) { log.error("StandardPipeline.removeValve: destroy: ", e); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (LifecycleException e) { // Just log. Still want to destroy. log.warn(sm.getString("lifecycleBase.destroyStopFail"), e); }
3
            
// in java/org/apache/catalina/startup/Catalina.java
catch (LifecycleException e) { if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) { throw new java.lang.Error(e); } else { log.error("Catalina.start", e); } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (LifecycleException e){ throw new MBeanException(e); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (LifecycleException e) { log.error("ContainerBase.addChild: start: ", e); throw new IllegalStateException ("ContainerBase.addChild: start: " + e); }
1
runtime (Domain) LogConfigurationException
public class LogConfigurationException extends RuntimeException {


    private static final long serialVersionUID = 1L;


    /**
     * Construct a new exception with <code>null</code> as its detail message.
     */
    public LogConfigurationException() {
        super();
    }


    /**
     * Construct a new exception with the specified detail message.
     *
     * @param message The detail message
     */
    public LogConfigurationException(String message) {
        super(message);
    }


    /**
     * Construct a new exception with the specified cause and a derived
     * detail message.
     *
     * @param cause The underlying cause
     */
    public LogConfigurationException(Throwable cause) {
        this( ((cause == null) ? null : cause.toString()), cause);
    }


    /**
     * Construct a new exception with the specified detail message and cause.
     *
     * @param message The detail message
     * @param cause The underlying cause
     */
    public LogConfigurationException(String message, Throwable cause) {
        super(message, cause);
    }
}
0 0 5
            
// in java/org/apache/juli/logging/LogFactory.java
public Log getInstance(String name) throws LogConfigurationException { return DirectJDKLog.getInstance(name); }
// in java/org/apache/juli/logging/LogFactory.java
public Log getInstance(Class<?> clazz) throws LogConfigurationException { return getInstance( clazz.getName()); }
// in java/org/apache/juli/logging/LogFactory.java
public static LogFactory getFactory() throws LogConfigurationException { return singleton; }
// in java/org/apache/juli/logging/LogFactory.java
public static Log getLog(Class<?> clazz) throws LogConfigurationException { return (getFactory().getInstance(clazz)); }
// in java/org/apache/juli/logging/LogFactory.java
public static Log getLog(String name) throws LogConfigurationException { return (getFactory().getInstance(name)); }
0 0 0
unknown (Lib) LoginException 4
            
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
Override public boolean login() throws LoginException { // Set up our CallbackHandler requests if (callbackHandler == null) throw new LoginException("No CallbackHandler specified"); Callback callbacks[] = new Callback[9]; callbacks[0] = new NameCallback("Username: "); callbacks[1] = new PasswordCallback("Password: ", false); callbacks[2] = new TextInputCallback("nonce"); callbacks[3] = new TextInputCallback("nc"); callbacks[4] = new TextInputCallback("cnonce"); callbacks[5] = new TextInputCallback("qop"); callbacks[6] = new TextInputCallback("realmName"); callbacks[7] = new TextInputCallback("md5a2"); callbacks[8] = new TextInputCallback("authMethod"); // Interact with the user to retrieve the username and password String username = null; String password = null; String nonce = null; String nc = null; String cnonce = null; String qop = null; String realmName = null; String md5a2 = null; String authMethod = null; try { callbackHandler.handle(callbacks); username = ((NameCallback) callbacks[0]).getName(); password = new String(((PasswordCallback) callbacks[1]).getPassword()); nonce = ((TextInputCallback) callbacks[2]).getText(); nc = ((TextInputCallback) callbacks[3]).getText(); cnonce = ((TextInputCallback) callbacks[4]).getText(); qop = ((TextInputCallback) callbacks[5]).getText(); realmName = ((TextInputCallback) callbacks[6]).getText(); md5a2 = ((TextInputCallback) callbacks[7]).getText(); authMethod = ((TextInputCallback) callbacks[8]).getText(); } catch (IOException e) { throw new LoginException(e.toString()); } catch (UnsupportedCallbackException e) { throw new LoginException(e.toString()); } // Validate the username and password we have received if (authMethod == null) { // BASIC or FORM principal = super.authenticate(username, password); } else if (authMethod.equals(HttpServletRequest.DIGEST_AUTH)) { principal = super.authenticate(username, password, nonce, nc, cnonce, qop, realmName, md5a2); } else if (authMethod.equals(HttpServletRequest.CLIENT_CERT_AUTH)) { principal = super.getPrincipal(username); } else { throw new LoginException("Unknown authentication method"); } log.debug("login " + username + " " + principal); // Report results based on success or failure if (principal != null) { return (true); } else { throw new FailedLoginException("Username or password is incorrect"); } }
2
            
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (IOException e) { throw new LoginException(e.toString()); }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (UnsupportedCallbackException e) { throw new LoginException(e.toString()); }
4
            
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
Override public boolean abort() throws LoginException { // If our authentication was not successful, just return false if (principal == null) return (false); // Clean up if overall authentication failed if (committed) logout(); else { committed = false; principal = null; } log.debug("Abort"); return (true); }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
Override public boolean commit() throws LoginException { log.debug("commit " + principal); // If authentication was not successful, just return false if (principal == null) return (false); // Add our Principal to the Subject if needed if (!subject.getPrincipals().contains(principal)) { subject.getPrincipals().add(principal); // Add the roles as additional subjects as per the contract with the // JAASRealm if (principal instanceof GenericPrincipal) { String roles[] = ((GenericPrincipal) principal).getRoles(); for (int i = 0; i < roles.length; i++) { subject.getPrincipals().add( new GenericPrincipal(null, roles[i], null)); } } } committed = true; return (true); }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
Override public boolean login() throws LoginException { // Set up our CallbackHandler requests if (callbackHandler == null) throw new LoginException("No CallbackHandler specified"); Callback callbacks[] = new Callback[9]; callbacks[0] = new NameCallback("Username: "); callbacks[1] = new PasswordCallback("Password: ", false); callbacks[2] = new TextInputCallback("nonce"); callbacks[3] = new TextInputCallback("nc"); callbacks[4] = new TextInputCallback("cnonce"); callbacks[5] = new TextInputCallback("qop"); callbacks[6] = new TextInputCallback("realmName"); callbacks[7] = new TextInputCallback("md5a2"); callbacks[8] = new TextInputCallback("authMethod"); // Interact with the user to retrieve the username and password String username = null; String password = null; String nonce = null; String nc = null; String cnonce = null; String qop = null; String realmName = null; String md5a2 = null; String authMethod = null; try { callbackHandler.handle(callbacks); username = ((NameCallback) callbacks[0]).getName(); password = new String(((PasswordCallback) callbacks[1]).getPassword()); nonce = ((TextInputCallback) callbacks[2]).getText(); nc = ((TextInputCallback) callbacks[3]).getText(); cnonce = ((TextInputCallback) callbacks[4]).getText(); qop = ((TextInputCallback) callbacks[5]).getText(); realmName = ((TextInputCallback) callbacks[6]).getText(); md5a2 = ((TextInputCallback) callbacks[7]).getText(); authMethod = ((TextInputCallback) callbacks[8]).getText(); } catch (IOException e) { throw new LoginException(e.toString()); } catch (UnsupportedCallbackException e) { throw new LoginException(e.toString()); } // Validate the username and password we have received if (authMethod == null) { // BASIC or FORM principal = super.authenticate(username, password); } else if (authMethod.equals(HttpServletRequest.DIGEST_AUTH)) { principal = super.authenticate(username, password, nonce, nc, cnonce, qop, realmName, md5a2); } else if (authMethod.equals(HttpServletRequest.CLIENT_CERT_AUTH)) { principal = super.getPrincipal(username); } else { throw new LoginException("Unknown authentication method"); } log.debug("login " + username + " " + principal); // Report results based on success or failure if (principal != null) { return (true); } else { throw new FailedLoginException("Username or password is incorrect"); } }
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
Override public boolean logout() throws LoginException { subject.getPrincipals().remove(principal); committed = false; principal = null; return (true); }
3
            
// in java/org/apache/catalina/realm/JAASRealm.java
catch (LoginException e) { log.warn(sm.getString("jaasRealm.loginException", username), e); return (null); }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (LoginException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (LoginException e) { // Ignore }
0 0
runtime (Domain) LookaheadSuccess
static private final class LookaheadSuccess extends java.lang.Error { }
0 0 0 4
            
// in java/org/apache/el/parser/ELParser.java
catch(LookaheadSuccess ls) { return true; }
// in java/org/apache/el/parser/ELParser.java
catch(LookaheadSuccess ls) { return true; }
// in java/org/apache/el/parser/ELParser.java
catch(LookaheadSuccess ls) { return true; }
// in java/org/apache/el/parser/ELParser.java
catch(LookaheadSuccess ls) { }
0 0
unknown (Lib) MBeanException 109
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public DynamicMBean createMBean(Object instance) throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { BaseModelMBean mbean = null; // Load the ModelMBean implementation class if(getClassName().equals(BASE_MBEAN)) { // Skip introspection mbean = new BaseModelMBean(); } else { Class<?> clazz = null; Exception ex = null; try { clazz = Class.forName(getClassName()); } catch (Exception e) { } if( clazz==null ) { try { ClassLoader cl= Thread.currentThread().getContextClassLoader(); if ( cl != null) clazz= cl.loadClass(getClassName()); } catch (Exception e) { ex=e; } } if( clazz==null) { throw new MBeanException (ex, "Cannot load ModelMBean class " + getClassName()); } try { // Stupid - this will set the default minfo first.... mbean = (BaseModelMBean) clazz.newInstance(); } catch (RuntimeOperationsException e) { throw e; } catch (Exception e) { throw new MBeanException (e, "Cannot instantiate ModelMBean of class " + getClassName()); } } mbean.setManagedBean(this); // Set the managed resource (if any) try { if (instance != null) mbean.setManagedResource(instance, "ObjectReference"); } catch (InstanceNotFoundException e) { throw e; } return (mbean); }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getInvoke(String aname, Object[] params, String[] signature, BaseModelMBean bean, Object resource) throws MBeanException, ReflectionException { Method method = null; if (params == null) params = new Object[0]; if (signature == null) signature = new String[0]; if (params.length != signature.length) throw new RuntimeOperationsException( new IllegalArgumentException( "Inconsistent arguments and signature"), "Inconsistent arguments and signature"); // Acquire the ModelMBeanOperationInfo information for // the requested operation OperationInfo opInfo = operations.get(aname); if (opInfo == null) throw new MBeanException(new ServiceNotFoundException( "Cannot find operation " + aname), "Cannot find operation " + aname); // Prepare the signature required by Java reflection APIs // FIXME - should we use the signature from opInfo? Class<?> types[] = new Class[signature.length]; for (int i = 0; i < signature.length; i++) { types[i] = BaseModelMBean.getAttributeClass(signature[i]); } // Locate the method to be invoked, either in this MBean itself // or in the corresponding managed resource // FIXME - Accessible methods in superinterfaces? Object object = null; Exception exception = null; try { object = bean; method = object.getClass().getMethod(aname, types); } catch (NoSuchMethodException e) { exception = e; } try { if ((method == null) && (resource != null)) { object = resource; method = object.getClass().getMethod(aname, types); } } catch (NoSuchMethodException e) { exception = e; } if (method == null) { throw new ReflectionException(exception, "Cannot find method " + aname + " with this signature"); } return method; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).getAttribute(name); } Method m=managedBean.getGetter(name, this, resource); Object result = null; try { Class<?> declaring = m.getDeclaringClass(); // workaround for catalina weird mbeans - the declaring class is BaseModelMBean. // but this is the catalina class. if( declaring.isAssignableFrom(this.getClass()) ) { result = m.invoke(this, NO_ARGS_PARAM ); } else { result = m.invoke(resource, NO_ARGS_PARAM ); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object invoke(String name, Object params[], String signature[]) throws MBeanException, ReflectionException { if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).invoke(name, params, signature); } // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Method name is null"), "Method name is null"); if( log.isDebugEnabled()) log.debug("Invoke " + name); Method method= managedBean.getInvoke(name, params, signature, this, resource); // Invoke the selected method on the appropriate object Object result = null; try { if( method.getDeclaringClass().isAssignableFrom( this.getClass()) ) { result = method.invoke(this, params ); } else { result = method.invoke(resource, params); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if( log.isDebugEnabled() ) log.debug("Setting attribute " + this + " " + attribute ); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { try { ((DynamicMBean)resource).setAttribute(attribute); } catch (InvalidAttributeValueException e) { throw new MBeanException(e); } return; } // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); Object oldValue=null; //if( getAttMap.get(name) != null ) // oldValue=getAttribute( name ); Method m=managedBean.getSetter(name,this,resource); try { if( m.getDeclaringClass().isAssignableFrom( this.getClass()) ) { m.invoke(this, new Object[] { value }); } else { m.invoke(resource, new Object[] { value }); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } try { sendAttributeChangeNotification(new Attribute( name, oldValue), attribute); } catch(Exception ex) { log.error("Error sending notification " + name, ex); } //attributes.put( name, value ); // if( source != null ) { // // this mbean is associated with a source - maybe we want to persist // source.updateField(oname, name, value); // } }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public void addConnector(String address, int port, boolean isAjp, boolean isSSL) throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Connector connector = new Connector(); if ((address!=null) && (address.length()>0)) { connector.setProperty("address", address); } connector.setPort(port); connector.setProtocol(isAjp ? "AJP/1.3" : "HTTP/1.1"); connector.setSecure(isSSL); connector.setScheme(isSSL ? "https" : "http"); service.addConnector(connector); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public void addExecutor(String type) throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Executor executor; try { executor = (Executor)Class.forName(type).newInstance(); } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } service.addExecutor(executor); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public String[] findConnectors() throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Connector[] connectors = service.findConnectors(); String[] str = new String[connectors.length]; for(int i=0; i< connectors.length; i++){ str[i] = connectors[i].toString(); } return str; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public String[] findExecutors() throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Executor[] executors = service.findExecutors(); String[] str = new String[executors.length]; for(int i=0; i< executors.length; i++){ str[i] = executors[i].toString(); } return str; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public String getExecutor(String name) throws MBeanException{ Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Executor executor = service.getExecutor(name); return executor.toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findApplicationParameters() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ApplicationParameter[] params = context.findApplicationParameters(); String[] stringParams = new String[params.length]; for(int counter=0; counter < params.length; counter++){ stringParams[counter]=params[counter].toString(); } return stringParams; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findConstraints() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } SecurityConstraint[] constraints = context.findConstraints(); String[] stringConstraints = new String[constraints.length]; for(int counter=0; counter < constraints.length; counter++){ stringConstraints[counter]=constraints[counter].toString(); } return stringConstraints; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String findErrorPage(int errorCode) throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return context.findErrorPage(errorCode).toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String findErrorPage(String exceptionType) throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return context.findErrorPage(exceptionType).toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findErrorPages() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ErrorPage[] pages = context.findErrorPages(); String[] stringPages = new String[pages.length]; for(int counter=0; counter < pages.length; counter++){ stringPages[counter]=pages[counter].toString(); } return stringPages; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String findFilterDef(String name) throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } FilterDef filterDef = context.findFilterDef(name); return filterDef.toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findFilterDefs() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } FilterDef[] filterDefs = context.findFilterDefs(); String[] stringFilters = new String[filterDefs.length]; for(int counter=0; counter < filterDefs.length; counter++){ stringFilters[counter]=filterDefs[counter].toString(); } return stringFilters; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findFilterMaps() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } FilterMap[] maps = context.findFilterMaps(); String[] stringMaps = new String[maps.length]; for(int counter=0; counter < maps.length; counter++){ stringMaps[counter]=maps[counter].toString(); } return stringMaps; }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); Object result = null; try { Connector connector = (Connector) getManagedResource(); result = IntrospectionUtils.getProperty(connector, name); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return result; }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); try { Connector connector = (Connector) getManagedResource(); IntrospectionUtils.setProperty(connector, name, String.valueOf(value)); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("auth".equals(name)) { return (cr.getAuth()); } else if ("description".equals(name)) { return (cr.getDescription()); } else if ("name".equals(name)) { return (cr.getName()); } else if ("scope".equals(name)) { return (cr.getScope()); } else if ("type".equals(name)) { return (cr.getType()); } else { value = (String) cr.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("auth".equals(name)) { cr.setAuth((String)value); } else if ("description".equals(name)) { cr.setDescription((String)value); } else if ("name".equals(name)) { cr.setName((String)value); } else if ("scope".equals(name)) { cr.setScope((String)value); } else if ("type".equals(name)) { cr.setType((String)value); } else { cr.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = cr.getNamingResources(); nr.removeResource(cr.getName()); nr.addResource(cr); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void addChild(String type, String name) throws MBeanException{ Container contained = null; try { contained = (Container)Class.forName(type).newInstance(); contained.setName(name); if(contained instanceof StandardHost){ HostConfig config = new HostConfig(); contained.addLifecycleListener(config); } else if(contained instanceof StandardContext){ ContextConfig config = new ContextConfig(); contained.addLifecycleListener(config); } } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } boolean oldValue= true; ContainerBase container = null; try { container = (ContainerBase)getManagedResource(); oldValue = container.getStartChildren(); container.setStartChildren(false); container.addChild(contained); contained.init(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } catch (LifecycleException e){ throw new MBeanException(e); } finally { if(container != null) { container.setStartChildren(oldValue); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void removeChild(String name) throws MBeanException{ if(name != null){ try { Container container = (Container)getManagedResource(); Container contained = container.findChild(name); container.removeChild(contained); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public String addValve(String valveType) throws MBeanException{ Valve valve = null; try { valve = (Valve)Class.forName(valveType).newInstance(); } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } if (valve == null) { return null; } try { Container container = (Container)getManagedResource(); container.getPipeline().addValve(valve); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if (valve instanceof JmxEnabled) { return ((JmxEnabled)valve).getObjectName().toString(); } else { return null; } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void removeValve(String valveName) throws MBeanException{ Container container=null; try { container = (Container)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ObjectName oname; try { oname = new ObjectName(valveName); } catch (MalformedObjectNameException e) { throw new MBeanException(e); } catch (NullPointerException e) { throw new MBeanException(e); } if(container != null){ Valve[] valves = container.getPipeline().getValves(); for (int i = 0; i < valves.length; i++) { if (valves[i] instanceof JmxEnabled) { ObjectName voname = ((JmxEnabled) valves[i]).getObjectName(); if (voname.equals(oname)) { container.getPipeline().removeValve(valves[i]); } } } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void addLifeCycleListener(String type) throws MBeanException{ LifecycleListener listener = null; try { listener = (LifecycleListener)Class.forName(type).newInstance(); } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } if(listener != null){ try { Container container = (Container)getManagedResource(); container.addLifecycleListener(listener); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void removeLifeCycleListeners(String type) throws MBeanException{ Container container=null; try { container = (Container)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } LifecycleListener[] listeners = container.findLifecycleListeners(); for(LifecycleListener listener: listeners){ if(listener.getClass().getName().equals(type)){ container.removeLifecycleListener(listener); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public String[] findLifecycleListenerNames() throws MBeanException { Container container = null; List<String> result = new ArrayList<String>(); try { container = (Container) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } LifecycleListener[] listeners = container.findLifecycleListeners(); for(LifecycleListener listener: listeners){ result.add(listener.getClass().getName()); } return result.toArray(new String[result.size()]); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public String[] findContainerListenerNames() throws MBeanException { Container container = null; List<String> result = new ArrayList<String>(); try { container = (Container) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ContainerListener[] listeners = container.findContainerListeners(); for(ContainerListener listener: listeners){ result.add(listener.getClass().getName()); } return result.toArray(new String[result.size()]); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink cl = null; try { cl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("global".equals(name)) { return (cl.getGlobal()); } else if ("description".equals(name)) { return (cl.getDescription()); } else if ("name".equals(name)) { return (cl.getName()); } else if ("type".equals(name)) { return (cl.getType()); } else { value = (String) cl.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink crl = null; try { crl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("global".equals(name)) { crl.setGlobal((String)value); } else if ("description".equals(name)) { crl.setDescription((String)value); } else if ("name".equals(name)) { crl.setName((String)value); } else if ("type".equals(name)) { crl.setType((String)value); } else { crl.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = crl.getNamingResources(); nr.removeResourceLink(crl.getName()); nr.addResourceLink(crl); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static DynamicMBean createMBean(ContextEnvironment environment) throws Exception { String mname = createManagedName(environment); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(environment); ObjectName oname = createObjectName(domain, environment); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static DynamicMBean createMBean(ContextResource resource) throws Exception { String mname = createManagedName(resource); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(resource); ObjectName oname = createObjectName(domain, resource); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static DynamicMBean createMBean(ContextResourceLink resourceLink) throws Exception { String mname = createManagedName(resourceLink); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(resourceLink); ObjectName oname = createObjectName(domain, resourceLink); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(Group group) throws Exception { String mname = createManagedName(group); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(group); ObjectName oname = createObjectName(domain, group); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(Role role) throws Exception { String mname = createManagedName(role); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(role); ObjectName oname = createObjectName(domain, role); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(User user) throws Exception { String mname = createManagedName(user); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(user); ObjectName oname = createObjectName(domain, user); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static DynamicMBean createMBean(UserDatabase userDatabase) throws Exception { String mname = createManagedName(userDatabase); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(userDatabase); ObjectName oname = createObjectName(domain, userDatabase); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { super.setAttribute(attribute); ContextEnvironment ce = null; try { ce = (ContextEnvironment) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = ce.getNamingResources(); nr.removeEnvironment(ce.getName()); nr.addEnvironment(ce); }
100
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (Exception e) { throw new MBeanException (e, "Cannot instantiate ModelMBean of class " + getClassName()); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvalidAttributeValueException e) { throw new MBeanException(e); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (LifecycleException e){ throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (MalformedObjectNameException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (NullPointerException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstantiationException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (IllegalAccessException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (ClassNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
catch (InstanceNotFoundException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); }
54
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public DynamicMBean createMBean() throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { return (createMBean(null)); }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public DynamicMBean createMBean(Object instance) throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { BaseModelMBean mbean = null; // Load the ModelMBean implementation class if(getClassName().equals(BASE_MBEAN)) { // Skip introspection mbean = new BaseModelMBean(); } else { Class<?> clazz = null; Exception ex = null; try { clazz = Class.forName(getClassName()); } catch (Exception e) { } if( clazz==null ) { try { ClassLoader cl= Thread.currentThread().getContextClassLoader(); if ( cl != null) clazz= cl.loadClass(getClassName()); } catch (Exception e) { ex=e; } } if( clazz==null) { throw new MBeanException (ex, "Cannot load ModelMBean class " + getClassName()); } try { // Stupid - this will set the default minfo first.... mbean = (BaseModelMBean) clazz.newInstance(); } catch (RuntimeOperationsException e) { throw e; } catch (Exception e) { throw new MBeanException (e, "Cannot instantiate ModelMBean of class " + getClassName()); } } mbean.setManagedBean(this); // Set the managed resource (if any) try { if (instance != null) mbean.setManagedResource(instance, "ObjectReference"); } catch (InstanceNotFoundException e) { throw e; } return (mbean); }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getInvoke(String aname, Object[] params, String[] signature, BaseModelMBean bean, Object resource) throws MBeanException, ReflectionException { Method method = null; if (params == null) params = new Object[0]; if (signature == null) signature = new String[0]; if (params.length != signature.length) throw new RuntimeOperationsException( new IllegalArgumentException( "Inconsistent arguments and signature"), "Inconsistent arguments and signature"); // Acquire the ModelMBeanOperationInfo information for // the requested operation OperationInfo opInfo = operations.get(aname); if (opInfo == null) throw new MBeanException(new ServiceNotFoundException( "Cannot find operation " + aname), "Cannot find operation " + aname); // Prepare the signature required by Java reflection APIs // FIXME - should we use the signature from opInfo? Class<?> types[] = new Class[signature.length]; for (int i = 0; i < signature.length; i++) { types[i] = BaseModelMBean.getAttributeClass(signature[i]); } // Locate the method to be invoked, either in this MBean itself // or in the corresponding managed resource // FIXME - Accessible methods in superinterfaces? Object object = null; Exception exception = null; try { object = bean; method = object.getClass().getMethod(aname, types); } catch (NoSuchMethodException e) { exception = e; } try { if ((method == null) && (resource != null)) { object = resource; method = object.getClass().getMethod(aname, types); } } catch (NoSuchMethodException e) { exception = e; } if (method == null) { throw new ReflectionException(exception, "Cannot find method " + aname + " with this signature"); } return method; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).getAttribute(name); } Method m=managedBean.getGetter(name, this, resource); Object result = null; try { Class<?> declaring = m.getDeclaringClass(); // workaround for catalina weird mbeans - the declaring class is BaseModelMBean. // but this is the catalina class. if( declaring.isAssignableFrom(this.getClass()) ) { result = m.invoke(this, NO_ARGS_PARAM ); } else { result = m.invoke(resource, NO_ARGS_PARAM ); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object invoke(String name, Object params[], String signature[]) throws MBeanException, ReflectionException { if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).invoke(name, params, signature); } // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Method name is null"), "Method name is null"); if( log.isDebugEnabled()) log.debug("Invoke " + name); Method method= managedBean.getInvoke(name, params, signature, this, resource); // Invoke the selected method on the appropriate object Object result = null; try { if( method.getDeclaringClass().isAssignableFrom( this.getClass()) ) { result = method.invoke(this, params ); } else { result = method.invoke(resource, params); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if( log.isDebugEnabled() ) log.debug("Setting attribute " + this + " " + attribute ); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { try { ((DynamicMBean)resource).setAttribute(attribute); } catch (InvalidAttributeValueException e) { throw new MBeanException(e); } return; } // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); Object oldValue=null; //if( getAttMap.get(name) != null ) // oldValue=getAttribute( name ); Method m=managedBean.getSetter(name,this,resource); try { if( m.getDeclaringClass().isAssignableFrom( this.getClass()) ) { m.invoke(this, new Object[] { value }); } else { m.invoke(resource, new Object[] { value }); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } try { sendAttributeChangeNotification(new Attribute( name, oldValue), attribute); } catch(Exception ex) { log.error("Error sending notification " + name, ex); } //attributes.put( name, value ); // if( source != null ) { // // this mbean is associated with a source - maybe we want to persist // source.updateField(oname, name, value); // } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
public Object getManagedResource() throws InstanceNotFoundException, InvalidTargetObjectTypeException, MBeanException, RuntimeOperationsException { if (resource == null) throw new RuntimeOperationsException (new IllegalArgumentException("Managed resource is null"), "Managed resource is null"); return resource; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
public void setManagedResource(Object resource, String type) throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { if (resource == null) throw new RuntimeOperationsException (new IllegalArgumentException("Managed resource is null"), "Managed resource is null"); // if (!"objectreference".equalsIgnoreCase(type)) // throw new InvalidTargetObjectTypeException(type); this.resource = resource; this.resourceType = resource.getClass().getName(); // // Make the resource aware of the model mbean. // try { // Method m=resource.getClass().getMethod("setModelMBean", // new Class[] {ModelMBean.class}); // if( m!= null ) { // m.invoke(resource, new Object[] {this}); // } // } catch( NoSuchMethodException t ) { // // ignore // } catch( Throwable t ) { // log.error( "Can't set model mbean ", t ); // } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendAttributeChangeNotification (AttributeChangeNotification notification) throws MBeanException, RuntimeOperationsException { if (notification == null) throw new RuntimeOperationsException (new IllegalArgumentException("Notification is null"), "Notification is null"); if (attributeBroadcaster == null) return; // This means there are no registered listeners if( log.isDebugEnabled() ) log.debug( "AttributeChangeNotification " + notification ); attributeBroadcaster.sendNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendAttributeChangeNotification (Attribute oldValue, Attribute newValue) throws MBeanException, RuntimeOperationsException { // Calculate the class name for the change notification String type = null; if (newValue.getValue() != null) type = newValue.getValue().getClass().getName(); else if (oldValue.getValue() != null) type = oldValue.getValue().getClass().getName(); else return; // Old and new are both null == no change AttributeChangeNotification notification = new AttributeChangeNotification (this, 1, System.currentTimeMillis(), "Attribute value has changed", oldValue.getName(), type, oldValue.getValue(), newValue.getValue()); sendAttributeChangeNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendNotification(Notification notification) throws MBeanException, RuntimeOperationsException { if (notification == null) throw new RuntimeOperationsException (new IllegalArgumentException("Notification is null"), "Notification is null"); if (generalBroadcaster == null) return; // This means there are no registered listeners generalBroadcaster.sendNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendNotification(String message) throws MBeanException, RuntimeOperationsException { if (message == null) throw new RuntimeOperationsException (new IllegalArgumentException("Message is null"), "Message is null"); Notification notification = new Notification ("jmx.modelmbean.generic", this, 1, message); sendNotification(notification); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public void addConnector(String address, int port, boolean isAjp, boolean isSSL) throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Connector connector = new Connector(); if ((address!=null) && (address.length()>0)) { connector.setProperty("address", address); } connector.setPort(port); connector.setProtocol(isAjp ? "AJP/1.3" : "HTTP/1.1"); connector.setSecure(isSSL); connector.setScheme(isSSL ? "https" : "http"); service.addConnector(connector); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public void addExecutor(String type) throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Executor executor; try { executor = (Executor)Class.forName(type).newInstance(); } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } service.addExecutor(executor); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public String[] findConnectors() throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Connector[] connectors = service.findConnectors(); String[] str = new String[connectors.length]; for(int i=0; i< connectors.length; i++){ str[i] = connectors[i].toString(); } return str; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public String[] findExecutors() throws MBeanException { Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Executor[] executors = service.findExecutors(); String[] str = new String[executors.length]; for(int i=0; i< executors.length; i++){ str[i] = executors[i].toString(); } return str; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
public String getExecutor(String name) throws MBeanException{ Service service; try { service = (Service)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } Executor executor = service.getExecutor(name); return executor.toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findApplicationParameters() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ApplicationParameter[] params = context.findApplicationParameters(); String[] stringParams = new String[params.length]; for(int counter=0; counter < params.length; counter++){ stringParams[counter]=params[counter].toString(); } return stringParams; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findConstraints() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } SecurityConstraint[] constraints = context.findConstraints(); String[] stringConstraints = new String[constraints.length]; for(int counter=0; counter < constraints.length; counter++){ stringConstraints[counter]=constraints[counter].toString(); } return stringConstraints; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String findErrorPage(int errorCode) throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return context.findErrorPage(errorCode).toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String findErrorPage(String exceptionType) throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return context.findErrorPage(exceptionType).toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findErrorPages() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ErrorPage[] pages = context.findErrorPages(); String[] stringPages = new String[pages.length]; for(int counter=0; counter < pages.length; counter++){ stringPages[counter]=pages[counter].toString(); } return stringPages; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String findFilterDef(String name) throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } FilterDef filterDef = context.findFilterDef(name); return filterDef.toString(); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findFilterDefs() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } FilterDef[] filterDefs = context.findFilterDefs(); String[] stringFilters = new String[filterDefs.length]; for(int counter=0; counter < filterDefs.length; counter++){ stringFilters[counter]=filterDefs[counter].toString(); } return stringFilters; }
// in java/org/apache/catalina/mbeans/ContextMBean.java
public String[] findFilterMaps() throws MBeanException { Context context; try { context = (Context)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } FilterMap[] maps = context.findFilterMaps(); String[] stringMaps = new String[maps.length]; for(int counter=0; counter < maps.length; counter++){ stringMaps[counter]=maps[counter].toString(); } return stringMaps; }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); Object result = null; try { Connector connector = (Connector) getManagedResource(); result = IntrospectionUtils.getProperty(connector, name); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return result; }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); try { Connector connector = (Connector) getManagedResource(); IntrospectionUtils.setProperty(connector, name, String.valueOf(value)); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("auth".equals(name)) { return (cr.getAuth()); } else if ("description".equals(name)) { return (cr.getDescription()); } else if ("name".equals(name)) { return (cr.getName()); } else if ("scope".equals(name)) { return (cr.getScope()); } else if ("type".equals(name)) { return (cr.getType()); } else { value = (String) cr.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("auth".equals(name)) { cr.setAuth((String)value); } else if ("description".equals(name)) { cr.setDescription((String)value); } else if ("name".equals(name)) { cr.setName((String)value); } else if ("scope".equals(name)) { cr.setScope((String)value); } else if ("type".equals(name)) { cr.setType((String)value); } else { cr.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = cr.getNamingResources(); nr.removeResource(cr.getName()); nr.addResource(cr); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void addChild(String type, String name) throws MBeanException{ Container contained = null; try { contained = (Container)Class.forName(type).newInstance(); contained.setName(name); if(contained instanceof StandardHost){ HostConfig config = new HostConfig(); contained.addLifecycleListener(config); } else if(contained instanceof StandardContext){ ContextConfig config = new ContextConfig(); contained.addLifecycleListener(config); } } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } boolean oldValue= true; ContainerBase container = null; try { container = (ContainerBase)getManagedResource(); oldValue = container.getStartChildren(); container.setStartChildren(false); container.addChild(contained); contained.init(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } catch (LifecycleException e){ throw new MBeanException(e); } finally { if(container != null) { container.setStartChildren(oldValue); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void removeChild(String name) throws MBeanException{ if(name != null){ try { Container container = (Container)getManagedResource(); Container contained = container.findChild(name); container.removeChild(contained); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public String addValve(String valveType) throws MBeanException{ Valve valve = null; try { valve = (Valve)Class.forName(valveType).newInstance(); } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } if (valve == null) { return null; } try { Container container = (Container)getManagedResource(); container.getPipeline().addValve(valve); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if (valve instanceof JmxEnabled) { return ((JmxEnabled)valve).getObjectName().toString(); } else { return null; } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void removeValve(String valveName) throws MBeanException{ Container container=null; try { container = (Container)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ObjectName oname; try { oname = new ObjectName(valveName); } catch (MalformedObjectNameException e) { throw new MBeanException(e); } catch (NullPointerException e) { throw new MBeanException(e); } if(container != null){ Valve[] valves = container.getPipeline().getValves(); for (int i = 0; i < valves.length; i++) { if (valves[i] instanceof JmxEnabled) { ObjectName voname = ((JmxEnabled) valves[i]).getObjectName(); if (voname.equals(oname)) { container.getPipeline().removeValve(valves[i]); } } } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void addLifeCycleListener(String type) throws MBeanException{ LifecycleListener listener = null; try { listener = (LifecycleListener)Class.forName(type).newInstance(); } catch (InstantiationException e) { throw new MBeanException(e); } catch (IllegalAccessException e) { throw new MBeanException(e); } catch (ClassNotFoundException e) { throw new MBeanException(e); } if(listener != null){ try { Container container = (Container)getManagedResource(); container.addLifecycleListener(listener); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public void removeLifeCycleListeners(String type) throws MBeanException{ Container container=null; try { container = (Container)getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } LifecycleListener[] listeners = container.findLifecycleListeners(); for(LifecycleListener listener: listeners){ if(listener.getClass().getName().equals(type)){ container.removeLifecycleListener(listener); } } }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public String[] findLifecycleListenerNames() throws MBeanException { Container container = null; List<String> result = new ArrayList<String>(); try { container = (Container) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } LifecycleListener[] listeners = container.findLifecycleListeners(); for(LifecycleListener listener: listeners){ result.add(listener.getClass().getName()); } return result.toArray(new String[result.size()]); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
public String[] findContainerListenerNames() throws MBeanException { Container container = null; List<String> result = new ArrayList<String>(); try { container = (Container) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (RuntimeOperationsException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } ContainerListener[] listeners = container.findContainerListeners(); for(ContainerListener listener: listeners){ result.add(listener.getClass().getName()); } return result.toArray(new String[result.size()]); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink cl = null; try { cl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("global".equals(name)) { return (cl.getGlobal()); } else if ("description".equals(name)) { return (cl.getDescription()); } else if ("name".equals(name)) { return (cl.getName()); } else if ("type".equals(name)) { return (cl.getType()); } else { value = (String) cl.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink crl = null; try { crl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("global".equals(name)) { crl.setGlobal((String)value); } else if ("description".equals(name)) { crl.setDescription((String)value); } else if ("name".equals(name)) { crl.setName((String)value); } else if ("type".equals(name)) { crl.setType((String)value); } else { crl.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = crl.getNamingResources(); nr.removeResourceLink(crl.getName()); nr.addResourceLink(crl); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { super.setAttribute(attribute); ContextEnvironment ce = null; try { ce = (ContextEnvironment) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = ce.getNamingResources(); nr.removeEnvironment(ce.getName()); nr.addEnvironment(ce); }
0 0 0
unknown (Lib) MBeanRegistrationException 0 0 0 1
            
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (MBeanRegistrationException e) { log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", on), e); }
0 0
unknown (Lib) MalformedInputException 0 0 0 1
            
// in java/org/apache/catalina/websocket/StreamInbound.java
catch (MalformedInputException mie) { // Invalid UTF-8 closeOutboundConnection(Constants.STATUS_BAD_DATA, null); return SocketState.CLOSED; }
0 0
unknown (Lib) MalformedObjectNameException 0 0 13
            
// in java/org/apache/coyote/AbstractProtocol.java
private ObjectName createObjectName() throws MalformedObjectNameException { // Use the same domain as the connector domain = adapter.getDomain(); if (domain == null) { return null; } StringBuilder name = new StringBuilder(getDomain()); name.append(":type=ProtocolHandler,port="); int port = getPort(); if (port > 0) { name.append(getPort()); } else { name.append("auto-"); name.append(getNameIndex()); } InetAddress address = getAddress(); if (address != null) { name.append(",address="); name.append(ObjectName.quote(address.getHostAddress())); } return new ObjectName(name.toString()); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static ObjectName createObjectName(String domain, ContextEnvironment environment) throws MalformedObjectNameException { ObjectName name = null; Object container = environment.getNamingResources().getContainer(); if (container instanceof Server) { name = new ObjectName(domain + ":type=Environment" + ",resourcetype=Global,name=" + environment.getName()); } else if (container instanceof Context) { Context context = ((Context)container); ContextName cn = new ContextName(context.getName()); Container host = context.getParent(); name = new ObjectName(domain + ":type=Environment" + ",resourcetype=Context,context=" + cn.getDisplayName() + ",host=" + host.getName() + ",name=" + environment.getName()); } return (name); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static ObjectName createObjectName(String domain, ContextResource resource) throws MalformedObjectNameException { ObjectName name = null; String quotedResourceName = ObjectName.quote(resource.getName()); Object container = resource.getNamingResources().getContainer(); if (container instanceof Server) { name = new ObjectName(domain + ":type=Resource" + ",resourcetype=Global,class=" + resource.getType() + ",name=" + quotedResourceName); } else if (container instanceof Context) { Context context = ((Context)container); ContextName cn = new ContextName(context.getName()); Container host = context.getParent(); name = new ObjectName(domain + ":type=Resource" + ",resourcetype=Context,context=" + cn.getDisplayName() + ",host=" + host.getName() + ",class=" + resource.getType() + ",name=" + quotedResourceName); } return (name); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
public static ObjectName createObjectName(String domain, ContextResourceLink resourceLink) throws MalformedObjectNameException { ObjectName name = null; String quotedResourceLinkName = ObjectName.quote(resourceLink.getName()); Object container = resourceLink.getNamingResources().getContainer(); if (container instanceof Server) { name = new ObjectName(domain + ":type=ResourceLink" + ",resourcetype=Global" + ",name=" + quotedResourceLinkName); } else if (container instanceof Context) { Context context = ((Context)container); ContextName cn = new ContextName(context.getName()); Container host = context.getParent(); name = new ObjectName(domain + ":type=ResourceLink" + ",resourcetype=Context,context=" + cn.getDisplayName() + ",host=" + host.getName() + ",name=" + quotedResourceLinkName); } return (name); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static ObjectName createObjectName(String domain, Group group) throws MalformedObjectNameException { ObjectName name = null; name = new ObjectName(domain + ":type=Group,groupname=" + ObjectName.quote(group.getGroupname()) + ",database=" + group.getUserDatabase().getId()); return (name); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static ObjectName createObjectName(String domain, Loader loader) throws MalformedObjectNameException { ObjectName name = null; Container container = loader.getContainer(); if (container instanceof Engine) { name = new ObjectName(domain + ":type=Loader"); } else if (container instanceof Host) { name = new ObjectName(domain + ":type=Loader,host=" + container.getName()); } else if (container instanceof Context) { Context context = ((Context)container); ContextName cn = new ContextName(context.getName()); Container host = context.getParent(); name = new ObjectName(domain + ":type=Loader,context=" + cn.getDisplayName() + ",host=" + host.getName()); } return (name); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static ObjectName createObjectName(String domain, Role role) throws MalformedObjectNameException { ObjectName name = null; name = new ObjectName(domain + ":type=Role,rolename=" + role.getRolename() + ",database=" + role.getUserDatabase().getId()); return (name); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static ObjectName createObjectName(String domain, User user) throws MalformedObjectNameException { ObjectName name = null; name = new ObjectName(domain + ":type=User,username=" + ObjectName.quote(user.getUsername()) + ",database=" + user.getUserDatabase().getId()); return (name); }
// in java/org/apache/catalina/mbeans/MBeanUtils.java
static ObjectName createObjectName(String domain, UserDatabase userDatabase) throws MalformedObjectNameException { ObjectName name = null; name = new ObjectName(domain + ":type=UserDatabase,database=" + userDatabase.getId()); return (name); }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
public String addEnvironment(String envName, String type, String value) throws MalformedObjectNameException { NamingResources nresources = (NamingResources) this.resource; if (nresources == null) { return null; } ContextEnvironment env = nresources.findEnvironment(envName); if (env != null) { throw new IllegalArgumentException ("Invalid environment name - already exists '" + envName + "'"); } env = new ContextEnvironment(); env.setName(envName); env.setType(type); env.setValue(value); nresources.addEnvironment(env); // Return the corresponding MBean name ManagedBean managed = registry.findManagedBean("ContextEnvironment"); ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), env); return (oname.toString()); }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
public String addResource(String resourceName, String type) throws MalformedObjectNameException { NamingResources nresources = (NamingResources) this.resource; if (nresources == null) { return null; } ContextResource resource = nresources.findResource(resourceName); if (resource != null) { throw new IllegalArgumentException ("Invalid resource name - already exists'" + resourceName + "'"); } resource = new ContextResource(); resource.setName(resourceName); resource.setType(type); nresources.addResource(resource); // Return the corresponding MBean name ManagedBean managed = registry.findManagedBean("ContextResource"); ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), resource); return (oname.toString()); }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
public String addResourceLink(String resourceLinkName, String type) throws MalformedObjectNameException { NamingResources nresources = (NamingResources) this.resource; if (nresources == null) { return null; } ContextResourceLink resourceLink = nresources.findResourceLink(resourceLinkName); if (resourceLink != null) { throw new IllegalArgumentException ("Invalid resource link name - already exists'" + resourceLinkName + "'"); } resourceLink = new ContextResourceLink(); resourceLink.setName(resourceLinkName); resourceLink.setType(type); nresources.addResourceLink(resourceLink); // Return the corresponding MBean name ManagedBean managed = registry.findManagedBean("ContextResourceLink"); ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), resourceLink); return (oname.toString()); }
// in java/org/apache/catalina/core/NamingContextListener.java
protected ObjectName createObjectName(ContextResource resource) throws MalformedObjectNameException { String domain = null; if (container instanceof StandardServer) { domain = ((StandardServer) container).getDomain(); } else if (container instanceof ContainerBase) { domain = ((ContainerBase) container).getDomain(); } if (domain == null) { domain = "Catalina"; } ObjectName name = null; String quotedResourceName = ObjectName.quote(resource.getName()); if (container instanceof Server) { name = new ObjectName(domain + ":type=DataSource" + ",class=" + resource.getType() + ",name=" + quotedResourceName); } else if (container instanceof Context) { String contextName = ((Context)container).getName(); if (!contextName.startsWith("/")) contextName = "/" + contextName; Host host = (Host) ((Context)container).getParent(); name = new ObjectName(domain + ":type=DataSource" + ",context=" + contextName + ",host=" + host.getName() + ",class=" + resource.getType() + ",name=" + quotedResourceName); } return (name); }
15
            
// in java/org/apache/tomcat/util/modeler/Registry.java
catch (MalformedObjectNameException e) { log.info("Error creating object name " + e ); }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch (MalformedObjectNameException e) { return null; }
// in java/org/apache/catalina/mbeans/UserMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for group " + group); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/UserMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role " + role); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (MalformedObjectNameException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for group [" + groupname + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role [" + rolename + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for user [" + username + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/GroupMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role " + role); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/GroupMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for user " + user); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for environment " + envs[i]); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for resource " + resources[i]); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for resource " + resourceLinks[i]); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (MalformedObjectNameException e) { if (isEcho()) handleErrorOutput("Unable to convert to ObjectName:" + value); }
// in java/org/apache/catalina/util/LifecycleMBeanBase.java
catch (MalformedObjectNameException e) { log.warn(sm.getString("lifecycleMBeanBase.registerFail", obj, name), e); }
11
            
// in java/org/apache/catalina/mbeans/UserMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for group " + group); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/UserMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role " + role); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (MalformedObjectNameException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for group [" + groupname + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role [" + rolename + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/MemoryUserDatabaseMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for user [" + username + "]"); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/GroupMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role " + role); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/GroupMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for user " + user); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for environment " + envs[i]); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for resource " + resources[i]); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/mbeans/NamingResourcesMBean.java
catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for resource " + resourceLinks[i]); iae.initCause(e); throw iae; }
0
checked (Domain) MalformedStreamException
public static class MalformedStreamException
            extends IOException {

        private static final long serialVersionUID = 1L;

        /**
         * Constructs a <code>MalformedStreamException</code> with no
         * detail message.
         */
        public MalformedStreamException() {
            super();
        }

        /**
         * Constructs an <code>MalformedStreamException</code> with
         * the specified detail message.
         *
         * @param message The detail message.
         */
        public MalformedStreamException(String message) {
            super(message);
        }
    }
5
            
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public boolean readBoundary() throws MalformedStreamException { byte[] marker = new byte[2]; boolean nextChunk = false; head += boundaryLength; try { marker[0] = readByte(); if (marker[0] == LF) { // Work around IE5 Mac bug with input type=image. // Because the boundary delimiter, not including the trailing // CRLF, must not appear within any file (RFC 2046, section // 5.1.1), we know the missing CR is due to a buggy browser // rather than a file containing something similar to a // boundary. return true; } marker[1] = readByte(); if (arrayequals(marker, STREAM_TERMINATOR, 2)) { nextChunk = false; } else if (arrayequals(marker, FIELD_SEPARATOR, 2)) { nextChunk = true; } else { throw new MalformedStreamException( "Unexpected characters follow a boundary"); } } catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); } return nextChunk; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public String readHeaders() throws MalformedStreamException { int i = 0; byte b; // to support multi-byte characters ByteArrayOutputStream baos = new ByteArrayOutputStream(); int size = 0; while (i < HEADER_SEPARATOR.length) { try { b = readByte(); } catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); } if (++size > HEADER_PART_SIZE_MAX) { throw new MalformedStreamException( "Header section has more than " + HEADER_PART_SIZE_MAX + " bytes (maybe it is not properly terminated)"); } if (b == HEADER_SEPARATOR[i]) { i++; } else { i = 0; } baos.write(b); } String headers = null; if (headerEncoding != null) { try { headers = baos.toString(headerEncoding); } catch (UnsupportedEncodingException e) { // Fall back to platform default if specified encoding is not // supported. headers = baos.toString(); } } else { headers = baos.toString(); } return headers; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
private int makeAvailable() throws IOException { if (pos != -1) { return 0; } // Move the data to the beginning of the buffer. total += tail - head - pad; System.arraycopy(buffer, tail - pad, buffer, 0, pad); // Refill buffer with new data. head = 0; tail = pad; for (;;) { int bytesRead = input.read(buffer, tail, bufSize - tail); if (bytesRead == -1) { // The last pad amount is left in the buffer. // Boundary can't be in there so signal an error // condition. final String msg = "Stream ended unexpectedly"; throw new MalformedStreamException(msg); } if (notifier != null) { notifier.noteBytesRead(bytesRead); } tail += bytesRead; findSeparator(); int av = available(); if (av > 0 || pos != -1) { return av; } } }
2
            
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); }
4
            
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public boolean readBoundary() throws MalformedStreamException { byte[] marker = new byte[2]; boolean nextChunk = false; head += boundaryLength; try { marker[0] = readByte(); if (marker[0] == LF) { // Work around IE5 Mac bug with input type=image. // Because the boundary delimiter, not including the trailing // CRLF, must not appear within any file (RFC 2046, section // 5.1.1), we know the missing CR is due to a buggy browser // rather than a file containing something similar to a // boundary. return true; } marker[1] = readByte(); if (arrayequals(marker, STREAM_TERMINATOR, 2)) { nextChunk = false; } else if (arrayequals(marker, FIELD_SEPARATOR, 2)) { nextChunk = true; } else { throw new MalformedStreamException( "Unexpected characters follow a boundary"); } } catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); } return nextChunk; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public String readHeaders() throws MalformedStreamException { int i = 0; byte b; // to support multi-byte characters ByteArrayOutputStream baos = new ByteArrayOutputStream(); int size = 0; while (i < HEADER_SEPARATOR.length) { try { b = readByte(); } catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); } if (++size > HEADER_PART_SIZE_MAX) { throw new MalformedStreamException( "Header section has more than " + HEADER_PART_SIZE_MAX + " bytes (maybe it is not properly terminated)"); } if (b == HEADER_SEPARATOR[i]) { i++; } else { i = 0; } baos.write(b); } String headers = null; if (headerEncoding != null) { try { headers = baos.toString(headerEncoding); } catch (UnsupportedEncodingException e) { // Fall back to platform default if specified encoding is not // supported. headers = baos.toString(); } } else { headers = baos.toString(); } return headers; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public int readBodyData(OutputStream output) throws MalformedStreamException, IOException { final InputStream istream = newInputStream(); return (int) Streams.copy(istream, output, false); }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
public int discardBodyData() throws MalformedStreamException, IOException { return readBodyData(null); }
1
            
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (MalformedStreamException e) { return false; }
0 0
unknown (Lib) MalformedURLException 9
            
// in java/org/apache/jasper/servlet/JspCServletContext.java
Override public URL getResource(String path) throws MalformedURLException { if (!path.startsWith("/")) throw new MalformedURLException("Path '" + path + "' does not start with '/'"); URL url = new URL(myResourceBaseURL, path.substring(1)); InputStream is = null; try { is = url.openStream(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); url = null; } finally { if (is != null) { try { is.close(); } catch (Throwable t2) { ExceptionUtils.handleThrowable(t2); } } } return url; }
// in java/org/apache/tomcat/util/net/URL.java
public void normalize() throws MalformedURLException { // Special case for null path if (path == null) { if (query != null) file = "?" + query; else file = ""; return; } // Create a place for the normalized path String normalized = path; if (normalized.equals("/.")) { path = "/"; if (query != null) file = path + "?" + query; else file = path; return; } // Normalize the slashes and add leading slash if necessary if (normalized.indexOf('\\') >= 0) normalized = normalized.replace('\\', '/'); if (!normalized.startsWith("/")) normalized = "/" + normalized; // Resolve occurrences of "//" in the normalized path while (true) { int index = normalized.indexOf("//"); if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 1); } // Resolve occurrences of "/./" in the normalized path while (true) { int index = normalized.indexOf("/./"); if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 2); } // Resolve occurrences of "/../" in the normalized path while (true) { int index = normalized.indexOf("/../"); if (index < 0) break; if (index == 0) throw new MalformedURLException ("Invalid relative URL reference"); int index2 = normalized.lastIndexOf('/', index - 1); normalized = normalized.substring(0, index2) + normalized.substring(index + 3); } // Resolve occurrences of "/." at the end of the normalized path if (normalized.endsWith("/.")) normalized = normalized.substring(0, normalized.length() - 1); // Resolve occurrences of "/.." at the end of the normalized path if (normalized.endsWith("/..")) { int index = normalized.length() - 3; int index2 = normalized.lastIndexOf('/', index - 1); if (index2 < 0) throw new MalformedURLException ("Invalid relative URL reference"); normalized = normalized.substring(0, index2 + 1); } // Return the normalized path that we have completed path = normalized; if (query != null) file = path + "?" + query; else file = path; }
// in java/org/apache/tomcat/util/net/URL.java
private void parse(String spec, int start, int limit) throws MalformedURLException { // Trim the query string (if any) off the tail end int question = spec.lastIndexOf('?', limit - 1); if ((question >= 0) && (question < limit)) { query = spec.substring(question + 1, limit); limit = question; } else { query = null; } // Parse the authority section if (spec.indexOf("//", start) == start) { int pathStart = spec.indexOf("/", start + 2); if ((pathStart >= 0) && (pathStart < limit)) { authority = spec.substring(start + 2, pathStart); start = pathStart; } else { authority = spec.substring(start + 2, limit); start = limit; } if (authority.length() > 0) { int at = authority.indexOf('@'); if( at >= 0 ) { userInfo = authority.substring(0,at); } int ipv6 = authority.indexOf('[',at+1); int hStart = at+1; if( ipv6 >= 0 ) { hStart = ipv6; ipv6 = authority.indexOf(']', ipv6); if( ipv6 < 0 ) { throw new MalformedURLException( "Closing ']' not found in IPV6 address: " + authority); } else { at = ipv6-1; } } int colon = authority.indexOf(':', at+1); if (colon >= 0) { try { port = Integer.parseInt(authority.substring(colon + 1)); } catch (NumberFormatException e) { throw new MalformedURLException(e.toString()); } host = authority.substring(hStart, colon); } else { host = authority.substring(hStart); port = -1; } } } // Parse the path section if (spec.indexOf("/", start) == start) { // Absolute path path = spec.substring(start, limit); if (query != null) file = path + "?" + query; else file = path; return; } // Resolve relative path against our context's file if (path == null) { if (query != null) file = "?" + query; else file = null; return; } if (!path.startsWith("/")) throw new MalformedURLException ("Base path does not start with '/'"); if (!path.endsWith("/")) path += "/../"; path += spec.substring(start, limit); if (query != null) file = path + "?" + query; else file = path; return; }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public URL getResource(String path) throws MalformedURLException { if (path == null || !path.startsWith("/") && GET_RESOURCE_REQUIRE_SLASH) throw new MalformedURLException(sm.getString( "applicationContext.requestDispatcher.iae", path)); String normPath = RequestUtil.normalize(path); if (normPath == null) return (null); DirContext resources = context.getResources(); if (resources != null) { String fullPath = context.getPath() + normPath; String hostName = context.getParent().getName(); try { resources.lookup(normPath); return new URL ("jndi", "", 0, getJNDIUri(hostName, fullPath), new DirContextURLStreamHandler(resources)); } catch (NamingException e) { // Ignore } catch (Exception e) { // Unexpected log(sm.getString("applicationContext.lookup.error", path, getContextPath()), e); } } return (null); }
2
            
// in java/org/apache/tomcat/util/net/URL.java
catch (Exception e) { throw new MalformedURLException(e.toString()); }
// in java/org/apache/tomcat/util/net/URL.java
catch (NumberFormatException e) { throw new MalformedURLException(e.toString()); }
17
            
// in java/org/apache/jasper/compiler/Mark.java
public URL getURL() throws MalformedURLException { return ctxt.getResource(getFile()); }
// in java/org/apache/jasper/servlet/JspCServletContext.java
Override public URL getResource(String path) throws MalformedURLException { if (!path.startsWith("/")) throw new MalformedURLException("Path '" + path + "' does not start with '/'"); URL url = new URL(myResourceBaseURL, path.substring(1)); InputStream is = null; try { is = url.openStream(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); url = null; } finally { if (is != null) { try { is.close(); } catch (Throwable t2) { ExceptionUtils.handleThrowable(t2); } } } return url; }
// in java/org/apache/jasper/JspCompilationContext.java
public URL getResource(String res) throws MalformedURLException { URL result = null; if (res.startsWith("/META-INF/")) { // This is a tag file packaged in a jar that is being compiled JarResource jarResource = tagFileJarUrls.get(res); if (jarResource == null) { jarResource = tagJarResource; } if (jarResource != null) { result = jarResource.getEntry(res.substring(1)); } else { // May not be in a JAR in some IDE environments result = context.getResource(canonicalURI(res)); } } else if (res.startsWith("jar:jndi:")) { // This is a tag file packaged in a jar that is being checked // for a dependency result = new URL(res); } else { result = context.getResource(canonicalURI(res)); } return result; }
// in java/org/apache/tomcat/util/net/URL.java
public void normalize() throws MalformedURLException { // Special case for null path if (path == null) { if (query != null) file = "?" + query; else file = ""; return; } // Create a place for the normalized path String normalized = path; if (normalized.equals("/.")) { path = "/"; if (query != null) file = path + "?" + query; else file = path; return; } // Normalize the slashes and add leading slash if necessary if (normalized.indexOf('\\') >= 0) normalized = normalized.replace('\\', '/'); if (!normalized.startsWith("/")) normalized = "/" + normalized; // Resolve occurrences of "//" in the normalized path while (true) { int index = normalized.indexOf("//"); if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 1); } // Resolve occurrences of "/./" in the normalized path while (true) { int index = normalized.indexOf("/./"); if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 2); } // Resolve occurrences of "/../" in the normalized path while (true) { int index = normalized.indexOf("/../"); if (index < 0) break; if (index == 0) throw new MalformedURLException ("Invalid relative URL reference"); int index2 = normalized.lastIndexOf('/', index - 1); normalized = normalized.substring(0, index2) + normalized.substring(index + 3); } // Resolve occurrences of "/." at the end of the normalized path if (normalized.endsWith("/.")) normalized = normalized.substring(0, normalized.length() - 1); // Resolve occurrences of "/.." at the end of the normalized path if (normalized.endsWith("/..")) { int index = normalized.length() - 3; int index2 = normalized.lastIndexOf('/', index - 1); if (index2 < 0) throw new MalformedURLException ("Invalid relative URL reference"); normalized = normalized.substring(0, index2 + 1); } // Return the normalized path that we have completed path = normalized; if (query != null) file = path + "?" + query; else file = path; }
// in java/org/apache/tomcat/util/net/URL.java
private void parse(String spec, int start, int limit) throws MalformedURLException { // Trim the query string (if any) off the tail end int question = spec.lastIndexOf('?', limit - 1); if ((question >= 0) && (question < limit)) { query = spec.substring(question + 1, limit); limit = question; } else { query = null; } // Parse the authority section if (spec.indexOf("//", start) == start) { int pathStart = spec.indexOf("/", start + 2); if ((pathStart >= 0) && (pathStart < limit)) { authority = spec.substring(start + 2, pathStart); start = pathStart; } else { authority = spec.substring(start + 2, limit); start = limit; } if (authority.length() > 0) { int at = authority.indexOf('@'); if( at >= 0 ) { userInfo = authority.substring(0,at); } int ipv6 = authority.indexOf('[',at+1); int hStart = at+1; if( ipv6 >= 0 ) { hStart = ipv6; ipv6 = authority.indexOf(']', ipv6); if( ipv6 < 0 ) { throw new MalformedURLException( "Closing ']' not found in IPV6 address: " + authority); } else { at = ipv6-1; } } int colon = authority.indexOf(':', at+1); if (colon >= 0) { try { port = Integer.parseInt(authority.substring(colon + 1)); } catch (NumberFormatException e) { throw new MalformedURLException(e.toString()); } host = authority.substring(hStart, colon); } else { host = authority.substring(hStart); port = -1; } } } // Parse the path section if (spec.indexOf("/", start) == start) { // Absolute path path = spec.substring(start, limit); if (query != null) file = path + "?" + query; else file = path; return; } // Resolve relative path against our context's file if (path == null) { if (query != null) file = "?" + query; else file = null; return; } if (!path.startsWith("/")) throw new MalformedURLException ("Base path does not start with '/'"); if (!path.endsWith("/")) path += "/../"; path += spec.substring(start, limit); if (query != null) file = path + "?" + query; else file = path; return; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
protected URL getURL(File file, boolean encoded) throws MalformedURLException { File realFile = file; try { realFile = realFile.getCanonicalFile(); } catch (IOException e) { // Ignore } if(encoded) { return getURI(realFile); } return realFile.toURI().toURL(); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
protected URL getURI(File file) throws MalformedURLException { File realFile = file; try { realFile = realFile.getCanonicalFile(); } catch (IOException e) { // Ignore } return realFile.toURI().toURL(); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
public static MBeanServerConnection createJMXConnection(String url, String host, String port, String username, String password) throws MalformedURLException, IOException { String urlForJMX; if (url != null) urlForJMX = url; else urlForJMX = JMX_SERVICE_PREFIX + host + ":" + port + JMX_SERVICE_SUFFIX; Map<String, String[]> environment = null; if (username != null && password != null) { String[] credentials = new String[2]; credentials[0] = username; credentials[1] = password; environment = new HashMap<String, String[]>(); environment.put(JMXConnector.CREDENTIALS, credentials); } return JMXConnectorFactory.connect(new JMXServiceURL(urlForJMX), environment).getMBeanServerConnection(); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
protected MBeanServerConnection getJMXConnection() throws MalformedURLException, IOException { MBeanServerConnection jmxServerConnection = null; if (isUseRef()) { Object pref = null ; if(getProject() != null) { pref = getProject().getReference(getRef()); if (pref != null) { try { jmxServerConnection = (MBeanServerConnection) pref; } catch (ClassCastException cce) { getProject().log( "Wrong object reference " + getRef() + " - " + pref.getClass()); return null; } } } if (jmxServerConnection == null) { jmxServerConnection = accessJMXConnection(getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), getRef()); } } else { jmxServerConnection = accessJMXConnection(getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), null); } return jmxServerConnection; }
// in java/org/apache/catalina/ant/jmx/JMXAccessorEqualsCondition.java
protected MBeanServerConnection getJMXConnection() throws MalformedURLException, IOException { return JMXAccessorTask.accessJMXConnection( getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), ref); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorCondition.java
protected MBeanServerConnection getJMXConnection() throws MalformedURLException, IOException { return JMXAccessorTask.accessJMXConnection( getProject(), getUrl(), getHost(), getPort(), getUsername(), getPassword(), ref); }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public URL getResource(String path) throws MalformedURLException { if (path == null || !path.startsWith("/") && GET_RESOURCE_REQUIRE_SLASH) throw new MalformedURLException(sm.getString( "applicationContext.requestDispatcher.iae", path)); String normPath = RequestUtil.normalize(path); if (normPath == null) return (null); DirContext resources = context.getResources(); if (resources != null) { String fullPath = context.getPath() + normPath; String hostName = context.getParent().getName(); try { resources.lookup(normPath); return new URL ("jndi", "", 0, getJNDIUri(hostName, fullPath), new DirContextURLStreamHandler(resources)); } catch (NamingException e) { // Ignore } catch (Exception e) { // Unexpected log(sm.getString("applicationContext.lookup.error", path, getContextPath()), e); } } return (null); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
Override public URL getResource(String path) throws MalformedURLException { if (Globals.IS_SECURITY_ENABLED) { try { return (URL) invokeMethod(context, "getResource", new Object[]{path}); } catch(Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof MalformedURLException){ throw (MalformedURLException)t; } return null; } } else { return context.getResource(path); } }
31
            
// in java/org/apache/jasper/compiler/WebXml.java
catch (MalformedURLException e) { log.warn(Localizer.getMessage( "jsp.error.internal.filenotfound", altDDName)); }
// in java/org/apache/jasper/compiler/JarURLResource.java
catch (MalformedURLException e) { throw new RuntimeException("", e); }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
catch (MalformedURLException me) { // Fallback to using context-relative path file = where.getFile(); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (MalformedURLException e) { throw new ServletException("Can not locate jsp file", e); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (MalformedURLException e) { throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"), e); }
// in java/org/apache/jasper/JspC.java
catch (MalformedURLException me) { System.out.println("**" + me); }
// in java/org/apache/tomcat/util/net/URL.java
catch (MalformedURLException e) { throw e; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.badUrl", defaultContextFile), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.badUrl", hostContextFile), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.webinfClassesUrl", resource), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { globalTimeStamp = -1; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { hostTimeStamp = -1; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString("contextConfig.applicationUrl")); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (MalformedURLException e) { log.error(sm.getString("contextConfig.applicationUrl")); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (MalformedURLException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { IllegalArgumentException iae = new IllegalArgumentException ("Invalid repository: " + repository); iae.initCause(e); throw iae; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { repositoryURLs = new URL[0]; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { return null; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { return null; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (MalformedURLException e) { // Ignore }
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (MalformedURLException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.invalidURL", serverName, url.toString()), e); return null; }
// in java/org/apache/catalina/connector/Response.java
catch (MalformedURLException e) { return (false); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { // Ignore and carry on }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { // Ignore and carry on }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { logger.error(sm.getString("naming.wsdlFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { // Ignore and carry on }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { // Ignore and carry on }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (MalformedURLException e) { logger.error(sm.getString("naming.wsdlFailed", e)); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (MalformedURLException e) { log.error(sm.getString( "jreLeakListener.jarUrlConnCacheFail"), e); }
5
            
// in java/org/apache/jasper/compiler/JarURLResource.java
catch (MalformedURLException e) { throw new RuntimeException("", e); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (MalformedURLException e) { throw new ServletException("Can not locate jsp file", e); }
// in java/org/apache/jasper/JspCompilationContext.java
catch (MalformedURLException e) { throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"), e); }
// in java/org/apache/tomcat/util/net/URL.java
catch (MalformedURLException e) { throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (MalformedURLException e) { IllegalArgumentException iae = new IllegalArgumentException ("Invalid repository: " + repository); iae.initCause(e); throw iae; }
2
runtime (Domain) MethodNotFoundException
public class MethodNotFoundException extends ELException {

    private static final long serialVersionUID = -3631968116081480328L;

    /**
     *
     */
    public MethodNotFoundException() {
        super();
    }

    /**
     * @param message
     */
    public MethodNotFoundException(String message) {
        super(message);
    }

    /**
     * @param message
     * @param cause
     */
    public MethodNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * @param cause
     */
    public MethodNotFoundException(Throwable cause) {
        super(cause);
    }
}
6
            
// in java/org/apache/el/parser/AstIdentifier.java
private final MethodExpression getMethodExpression(EvaluationContext ctx) throws ELException { Object obj = null; // case A: ValueExpression exists, getValue which must // be a MethodExpression VariableMapper varMapper = ctx.getVariableMapper(); ValueExpression ve = null; if (varMapper != null) { ve = varMapper.resolveVariable(this.image); if (ve != null) { obj = ve.getValue(ctx); } } // case B: evaluate the identity against the ELResolver, again, must be // a MethodExpression to be able to invoke if (ve == null) { ctx.setPropertyResolved(false); obj = ctx.getELResolver().getValue(ctx, null, this.image); } // finally provide helpful hints if (obj instanceof MethodExpression) { return (MethodExpression) obj; } else if (obj == null) { throw new MethodNotFoundException("Identity '" + this.image + "' was null and was unable to invoke"); } else { throw new ELException( "Identity '" + this.image + "' does not reference a MethodExpression instance, returned type: " + obj.getClass().getName()); } }
// in java/javax/el/BeanELResolver.java
Override public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { if (context == null) { throw new NullPointerException(); } if (base == null || method == null) { return null; } ExpressionFactory factory = ExpressionFactory.newInstance(); String methodName = (String) factory.coerceToType(method, String.class); // Find the matching method Method matchingMethod = null; Class<?> clazz = base.getClass(); if (paramTypes != null) { try { matchingMethod = getMethod(clazz, clazz.getMethod(methodName, paramTypes)); } catch (NoSuchMethodException e) { throw new MethodNotFoundException(e); } } else { int paramCount = 0; if (params != null) { paramCount = params.length; } Method[] methods = clazz.getMethods(); for (Method m : methods) { if (methodName.equals(m.getName())) { if (m.getParameterTypes().length == paramCount) { // Same number of parameters - use the first match matchingMethod = getMethod(clazz, m); break; } if (m.isVarArgs() && paramCount > m.getParameterTypes().length - 2) { matchingMethod = getMethod(clazz, m); } } } if (matchingMethod == null) { throw new MethodNotFoundException( "Unable to find method [" + methodName + "] with [" + paramCount + "] parameters"); } } Class<?>[] parameterTypes = matchingMethod.getParameterTypes(); Object[] parameters = null; if (parameterTypes.length > 0) { parameters = new Object[parameterTypes.length]; @SuppressWarnings("null") // params.length >= parameterTypes.length int paramCount = params.length; if (matchingMethod.isVarArgs()) { int varArgIndex = parameterTypes.length - 1; // First argCount-1 parameters are standard for (int i = 0; (i < varArgIndex); i++) { parameters[i] = factory.coerceToType(params[i], parameterTypes[i]); } // Last parameter is the varargs Class<?> varArgClass = parameterTypes[varArgIndex].getComponentType(); final Object varargs = Array.newInstance( varArgClass, (paramCount - varArgIndex)); for (int i = (varArgIndex); i < paramCount; i++) { Array.set(varargs, i - varArgIndex, factory.coerceToType(params[i], varArgClass)); } parameters[varArgIndex] = varargs; } else { parameters = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { parameters[i] = factory.coerceToType(params[i], parameterTypes[i]); } } }
1
            
// in java/javax/el/BeanELResolver.java
catch (NoSuchMethodException e) { throw new MethodNotFoundException(e); }
4
            
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public MethodInfo getMethodInfo(ELContext context) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.getMethodInfo(context); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public Object invoke(ELContext context, Object[] params) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.invoke(context, params); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/el/MethodExpressionImpl.java
Override public MethodInfo getMethodInfo(ELContext context) throws PropertyNotFoundException, MethodNotFoundException, ELException { Node n = this.getNode(); EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return n.getMethodInfo(ctx, this.paramTypes); }
// in java/org/apache/el/MethodExpressionImpl.java
Override public Object invoke(ELContext context, Object[] params) throws PropertyNotFoundException, MethodNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return this.getNode().invoke(ctx, this.paramTypes, params); }
2
            
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
4
            
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); }
2
unknown (Lib) MissingResourceException 0 0 0 13
            
// in java/org/apache/jasper/compiler/Localizer.java
catch (MissingResourceException e) { }
// in java/org/apache/jasper/compiler/Localizer.java
catch (MissingResourceException e) { }
// in java/org/apache/naming/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { tempBundle = ResourceBundle.getBundle( bundleName, Locale.getDefault(), cl); } catch(MissingResourceException ex2) { // Ignore } } }
// in java/org/apache/naming/StringManager.java
catch(MissingResourceException ex2) { // Ignore }
// in java/org/apache/naming/StringManager.java
catch(MissingResourceException mre) { //bad: shouldn't mask an exception the following way: // str = "[cannot find message associated with key '" + key + "' due to " + mre + "]"; // because it hides the fact that the String was missing // from the calling code. //good: could just throw the exception (or wrap it in another) // but that would probably cause much havoc on existing // code. //better: consistent with container pattern to // simply return null. Calling code can then do // a null check. str = null; }
// in java/org/apache/tomcat/util/res/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { bnd = ResourceBundle.getBundle(bundleName, locale, cl); } catch(MissingResourceException ex2) { // Ignore } } }
// in java/org/apache/tomcat/util/res/StringManager.java
catch(MissingResourceException ex2) { // Ignore }
// in java/org/apache/tomcat/util/res/StringManager.java
catch(MissingResourceException mre) { //bad: shouldn't mask an exception the following way: // str = "[cannot find message associated with key '" + key + // "' due to " + mre + "]"; // because it hides the fact that the String was missing // from the calling code. //good: could just throw the exception (or wrap it in another) // but that would probably cause much havoc on existing // code. //better: consistent with container pattern to // simply return null. Calling code can then do // a null check. str = null; }
// in java/org/apache/catalina/tribes/util/StringManager.java
catch( MissingResourceException ex ) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { bundle = ResourceBundle.getBundle( bundleName, Locale.getDefault(), cl); } catch(MissingResourceException ex2) { // Ignore } } }
// in java/org/apache/catalina/tribes/util/StringManager.java
catch(MissingResourceException ex2) { // Ignore }
// in java/org/apache/catalina/tribes/util/StringManager.java
catch(MissingResourceException mre) { //bad: shouldn't mask an exception the following way: // str = "[cannot find message associated with key '" + key + "' due to " + mre + "]"; // because it hides the fact that the String was missing // from the calling code. //good: could just throw the exception (or wrap it in another) // but that would probably cause much havoc on existing // code. //better: consistent with container pattern to // simply return null. Calling code can then do // a null check. str = null; }
// in java/javax/el/ResourceBundleELResolver.java
catch (MissingResourceException mre) { return "???" + property.toString() + "???"; }
// in java/javax/el/ELResolver.java
catch (MissingResourceException e) { return "Missing Resource: '" + name + "' for Locale " + locale.getDisplayName(); }
0 0
unknown (Lib) NameAlreadyBoundException 3
            
// in java/org/apache/naming/NamingContext.java
protected void bind(Name name, Object obj, boolean rebind) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (name.size() > 1) { if (entry == null) { throw new NameNotFoundException(sm.getString( "namingContext.nameNotBound", name, name.get(0))); } if (entry.type == NamingEntry.CONTEXT) { if (rebind) { ((Context) entry.value).rebind(name.getSuffix(1), obj); } else { ((Context) entry.value).bind(name.getSuffix(1), obj); } } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if ((!rebind) && (entry != null)) { throw new NameAlreadyBoundException (sm.getString("namingContext.alreadyBound", name.get(0))); } else { // Getting the type of the object and wrapping it within a new // NamingEntry Object toBind = NamingManager.getStateToBind(obj, name, this, env); if (toBind instanceof Context) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.CONTEXT); } else if (toBind instanceof LinkRef) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.LINK_REF); } else if (toBind instanceof Reference) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else if (toBind instanceof Referenceable) { toBind = ((Referenceable) toBind).getReference(); entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else { entry = new NamingEntry(name.get(0), toBind, NamingEntry.ENTRY); } bindings.put(name.get(0), entry); } } }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void bind(String name, Object obj, Attributes attrs) throws NamingException { // Note: No custom attributes allowed File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException (sm.getString("resources.alreadyBound", name)); rebind(name, obj, attrs); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException (sm.getString("resources.alreadyBound", name)); if (!file.mkdir()) throw new NamingException (sm.getString("resources.bindFailed", name)); return (DirContext) lookup(name); }
0 0 1
            
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NameAlreadyBoundException e) { // Ignore because UserTransaction was obviously // added via ResourceLink }
0 0
unknown (Lib) NameNotFoundException 13
            
// in java/org/apache/naming/NamingContext.java
Override public void unbind(Name name) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).unbind(name.getSuffix(1)); } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { bindings.remove(name.get(0)); } }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { return new NamingContextEnumeration(bindings.values().iterator()); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).list(name.getSuffix(1)); }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { return new NamingContextBindingsEnumeration(bindings.values().iterator(), this); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).listBindings(name.getSuffix(1)); }
// in java/org/apache/naming/NamingContext.java
Override public void destroySubcontext(Name name) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).destroySubcontext(name.getSuffix(1)); } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).close(); bindings.remove(name.get(0)); } else { throw new NotContextException (sm.getString("namingContext.contextExpected")); } } }
// in java/org/apache/naming/NamingContext.java
protected Object lookup(Name name, boolean resolveLinks) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { // If name is empty, a newly allocated naming context is returned return new NamingContext(env, this.name, bindings); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { // If the size of the name is greater that 1, then we go through a // number of subcontexts. if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).lookup(name.getSuffix(1)); } else { if ((resolveLinks) && (entry.type == NamingEntry.LINK_REF)) { String link = ((LinkRef) entry.value).getLinkName(); if (link.startsWith(".")) { // Link relative to this context return lookup(link.substring(1)); } else { return (new InitialContext(env)).lookup(link); } } else if (entry.type == NamingEntry.REFERENCE) { try { Object obj = NamingManager.getObjectInstance (entry.value, name, this, env); if(entry.value instanceof ResourceRef) { boolean singleton = Boolean.parseBoolean( (String) ((ResourceRef) entry.value).get( "singleton").getContent()); if (singleton) { entry.type = NamingEntry.ENTRY; entry.value = obj; } } return obj; } catch (NamingException e) { throw e; } catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); } } else { return entry.value; } } }
// in java/org/apache/naming/NamingContext.java
protected void bind(Name name, Object obj, boolean rebind) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (name.size() > 1) { if (entry == null) { throw new NameNotFoundException(sm.getString( "namingContext.nameNotBound", name, name.get(0))); } if (entry.type == NamingEntry.CONTEXT) { if (rebind) { ((Context) entry.value).rebind(name.getSuffix(1), obj); } else { ((Context) entry.value).bind(name.getSuffix(1), obj); } } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if ((!rebind) && (entry != null)) { throw new NameAlreadyBoundException (sm.getString("namingContext.alreadyBound", name.get(0))); } else { // Getting the type of the object and wrapping it within a new // NamingEntry Object toBind = NamingManager.getStateToBind(obj, name, this, env); if (toBind instanceof Context) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.CONTEXT); } else if (toBind instanceof LinkRef) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.LINK_REF); } else if (toBind instanceof Reference) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else if (toBind instanceof Referenceable) { toBind = ((Referenceable) toBind).getReference(); entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else { entry = new NamingEntry(name.get(0), toBind, NamingEntry.ENTRY); } bindings.put(name.get(0), entry); } } }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { if (name.isEmpty()) return new NamingContextEnumeration(list(entries).iterator()); Entry entry = treeLookup(name); if (entry == null) throw new NameNotFoundException (sm.getString("resources.notFound", name)); return new NamingContextEnumeration(list(entry).iterator()); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void unbind(String name) throws NamingException { File file = file(name); if (file == null) throw new NameNotFoundException( sm.getString("resources.notFound", name)); if (!file.delete()) throw new NamingException (sm.getString("resources.unbindFailed", name)); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void rename(String oldName, String newName) throws NamingException { File file = file(oldName); if (file == null) throw new NameNotFoundException (sm.getString("resources.notFound", oldName)); File newFile = new File(base, newName); if (!file.renameTo(newFile)) { throw new NamingException(sm.getString("resources.renameFail", oldName, newName)); } }
// in java/org/apache/naming/resources/FileDirContext.java
Override public NamingEnumeration<NameClassPair> list(String name) throws NamingException { File file = file(name); if (file == null) throw new NameNotFoundException (sm.getString("resources.notFound", name)); return new NamingContextEnumeration(list(file).iterator()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final Object lookup(String name) throws NamingException { // First check for aliases if (!aliases.isEmpty()) { AliasResult result = findAlias(name); if (result.dirContext != null) { return result.dirContext.lookup(result.aliasName); } } // Next do a standard lookup Object obj = doLookup(name); if (obj != null) return obj; // Check the alternate locations for (DirContext altDirContext : altDirContexts) { try { obj = altDirContext.lookup("/META-INF/resources" + name); if (obj != null) return obj; } catch ( NamingException ex) { // ignore } } // Really not found throw new NameNotFoundException( sm.getString("resources.notFound", name)); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final NamingEnumeration<Binding> listBindings(String name) throws NamingException { if (!aliases.isEmpty()) { AliasResult result = findAlias(name); if (result.dirContext != null) { return result.dirContext.listBindings(result.aliasName); } } // Next do a standard lookup List<NamingEntry> bindings = doListBindings(name); // Check the alternate locations List<NamingEntry> altBindings = null; for (DirContext altDirContext : altDirContexts) { if (altDirContext instanceof BaseDirContext) { altBindings = ((BaseDirContext) altDirContext).doListBindings( "/META-INF/resources" + name); } if (altBindings != null) { if (bindings == null) { bindings = altBindings; } else { bindings.addAll(altBindings); } } } if (bindings != null) { return new NamingContextBindingsEnumeration(bindings.iterator(), this); } // Really not found throw new NameNotFoundException( sm.getString("resources.notFound", name)); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final Attributes getAttributes(String name, String[] attrIds) throws NamingException { // First check for aliases if (!aliases.isEmpty()) { AliasResult result = findAlias(name); if (result.dirContext != null) { return result.dirContext.getAttributes( result.aliasName, attrIds); } } // Next do a standard lookup Attributes attrs = doGetAttributes(name, attrIds); if (attrs != null) return attrs; // Check the alternate locations for (DirContext altDirContext : altDirContexts) { if (altDirContext instanceof BaseDirContext) attrs = ((BaseDirContext) altDirContext).doGetAttributes( "/META-INF/resources" + name, attrIds); else { try { attrs = altDirContext.getAttributes(name, attrIds); } catch (NamingException ne) { // Ignore } } if (attrs != null) return attrs; } // Really not found throw new NameNotFoundException( sm.getString("resources.notFound", name)); }
0 0 3
            
// in java/org/apache/catalina/startup/ContextConfig.java
catch (NameNotFoundException ignore) { // Safe to ignore }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NameNotFoundException e) { return (null); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NameNotFoundException e) { return (null); }
0 0
unknown (Lib) NamingException 36
            
// in java/org/apache/naming/factory/ResourceEnvFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof ResourceEnvRef) { Reference ref = (Reference) obj; ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } } // Note: No defaults here if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/factory/BeanFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws NamingException { if (obj instanceof ResourceRef) { try { Reference ref = (Reference) obj; String beanClassName = ref.getClassName(); Class<?> beanClass = null; ClassLoader tcl = Thread.currentThread().getContextClassLoader(); if (tcl != null) { try { beanClass = tcl.loadClass(beanClassName); } catch(ClassNotFoundException e) { } } else { try { beanClass = Class.forName(beanClassName); } catch(ClassNotFoundException e) { e.printStackTrace(); } } if (beanClass == null) { throw new NamingException ("Class not found: " + beanClassName); } BeanInfo bi = Introspector.getBeanInfo(beanClass); PropertyDescriptor[] pda = bi.getPropertyDescriptors(); Object bean = beanClass.newInstance(); Enumeration<RefAddr> e = ref.getAll(); while (e.hasMoreElements()) { RefAddr ra = e.nextElement(); String propName = ra.getType(); if (propName.equals(Constants.FACTORY) || propName.equals("scope") || propName.equals("auth") || propName.equals("singleton")) { continue; } String value = (String)ra.getContent(); Object[] valueArray = new Object[1]; int i = 0; for (i = 0; i<pda.length; i++) { if (pda[i].getName().equals(propName)) { Class<?> propType = pda[i].getPropertyType(); if (propType.equals(String.class)) { valueArray[0] = value; } else if (propType.equals(Character.class) || propType.equals(char.class)) { valueArray[0] = Character.valueOf(value.charAt(0)); } else if (propType.equals(Byte.class) || propType.equals(byte.class)) { valueArray[0] = new Byte(value); } else if (propType.equals(Short.class) || propType.equals(short.class)) { valueArray[0] = new Short(value); } else if (propType.equals(Integer.class) || propType.equals(int.class)) { valueArray[0] = new Integer(value); } else if (propType.equals(Long.class) || propType.equals(long.class)) { valueArray[0] = new Long(value); } else if (propType.equals(Float.class) || propType.equals(float.class)) { valueArray[0] = new Float(value); } else if (propType.equals(Double.class) || propType.equals(double.class)) { valueArray[0] = new Double(value); } else if (propType.equals(Boolean.class) || propType.equals(boolean.class)) { valueArray[0] = Boolean.valueOf(value); } else { throw new NamingException ("String conversion for property type '" + propType.getName() + "' not available"); } Method setProp = pda[i].getWriteMethod(); if (setProp != null) { setProp.invoke(bean, valueArray); } else { throw new NamingException ("Write not allowed for property: " + propName); } break; } } if (i == pda.length) { throw new NamingException ("No set method found for property: " + propName); } } return bean; } catch (java.beans.IntrospectionException ie) { NamingException ne = new NamingException(ie.getMessage()); ne.setRootCause(ie); throw ne; } catch (java.lang.IllegalAccessException iae) { NamingException ne = new NamingException(iae.getMessage()); ne.setRootCause(iae); throw ne; } catch (java.lang.InstantiationException ie2) { NamingException ne = new NamingException(ie2.getMessage()); ne.setRootCause(ie2); throw ne; } catch (java.lang.reflect.InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } NamingException ne = new NamingException(ite.getMessage()); ne.setRootCause(ite); throw ne; } } else { return null; } }
// in java/org/apache/naming/factory/webservices/ServiceRefFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof ServiceRef) { Reference ref = (Reference) obj; // ClassLoader ClassLoader tcl = Thread.currentThread().getContextClassLoader(); if (tcl == null) tcl = this.getClass().getClassLoader(); ServiceFactory factory = ServiceFactory.newInstance(); javax.xml.rpc.Service service = null; // Service Interface RefAddr tmp = ref.get(ServiceRef.SERVICE_INTERFACE); String serviceInterface = null; if (tmp != null) serviceInterface = (String) tmp.getContent(); // WSDL tmp = ref.get(ServiceRef.WSDL); String wsdlRefAddr = null; if (tmp != null) wsdlRefAddr = (String) tmp.getContent(); // PortComponent Hashtable<String,QName> portComponentRef = new Hashtable<String,QName>(); // Create QName object QName serviceQname = null; tmp = ref.get(ServiceRef.SERVICE_LOCAL_PART); if (tmp != null) { String serviceLocalPart = (String) tmp.getContent(); tmp = ref.get(ServiceRef.SERVICE_NAMESPACE); if (tmp == null) { serviceQname = new QName(serviceLocalPart); } else { String serviceNamespace = (String) tmp.getContent(); serviceQname = new QName(serviceNamespace, serviceLocalPart); } } Class<?> serviceInterfaceClass = null; // Create service object if (serviceInterface == null) { if (serviceQname == null) { throw new NamingException ("Could not create service-ref instance"); } try { if (wsdlRefAddr == null) { service = factory.createService( serviceQname ); } else { service = factory.createService( new URL(wsdlRefAddr), serviceQname ); } } catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; } } else { // Loading service Interface try { serviceInterfaceClass = tcl.loadClass(serviceInterface); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load service Interface"); ex.initCause(e); throw ex; } if (serviceInterfaceClass == null) { throw new NamingException ("Could not load service Interface"); } try { if (wsdlRefAddr == null) { if (!Service.class.isAssignableFrom(serviceInterfaceClass)) { throw new NamingException ("service Interface should extend javax.xml.rpc.Service"); } service = factory.loadService( serviceInterfaceClass ); } else { service = factory.loadService( new URL(wsdlRefAddr), serviceInterfaceClass, new Properties() ); } } catch (Exception e) { NamingException ex = new NamingException ("Could not create service"); ex.initCause(e); throw ex; } } if (service == null) { throw new NamingException ("Cannot create service object"); } serviceQname = service.getServiceName(); serviceInterfaceClass = service.getClass(); if (wsdlRefAddr != null) { try { WSDLFactory wsdlfactory = WSDLFactory.newInstance(); WSDLReader reader = wsdlfactory.newWSDLReader(); reader.setFeature("javax.wsdl.importDocuments", true); Definition def = reader.readWSDL((new URL(wsdlRefAddr)).toExternalForm()); javax.wsdl.Service wsdlservice = def.getService(serviceQname); @SuppressWarnings("unchecked") // Can't change the API Map<String,?> ports = wsdlservice.getPorts(); Method m = serviceInterfaceClass.getMethod("setEndpointAddress", new Class[] { java.lang.String.class, java.lang.String.class }); for (Iterator<String> i = ports.keySet().iterator(); i.hasNext();) { String portName = i.next(); Port port = wsdlservice.getPort(portName); String endpoint = getSOAPLocation(port); m.invoke(service, new Object[] {port.getName(), endpoint }); portComponentRef.put(endpoint, new QName(port.getName())); } } catch (Exception e) { if (e instanceof InvocationTargetException) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } } NamingException ex = new NamingException ("Error while reading Wsdl File"); ex.initCause(e); throw ex; } } ServiceProxy proxy = new ServiceProxy(service); // Use port-component-ref for (int i = 0; i < ref.size(); i++) if (ServiceRef.SERVICEENDPOINTINTERFACE.equals(ref.get(i).getType())) { String serviceendpoint = ""; String portlink = ""; serviceendpoint = (String) ref.get(i).getContent(); if (ServiceRef.PORTCOMPONENTLINK.equals(ref.get(i + 1).getType())) { i++; portlink = (String) ref.get(i).getContent(); } portComponentRef.put(serviceendpoint, new QName(portlink)); } proxy.setPortComponentRef(portComponentRef); // Instantiate service with proxy class Class<?>[] interfaces = null; Class<?>[] serviceInterfaces = serviceInterfaceClass.getInterfaces(); interfaces = new Class[serviceInterfaces.length + 1]; for (int i = 0; i < serviceInterfaces.length; i++) { interfaces[i] = serviceInterfaces[i]; } interfaces[interfaces.length - 1] = javax.xml.rpc.Service.class; Object proxyInstance = null; try { proxyInstance = Proxy.newProxyInstance(tcl, interfaces, proxy); } catch (IllegalArgumentException e) { proxyInstance = Proxy.newProxyInstance(tcl, serviceInterfaces, proxy); } // Use handler if (((ServiceRef) ref).getHandlersSize() > 0) { HandlerRegistry handlerRegistry = service.getHandlerRegistry(); ArrayList<String> soaproles = new ArrayList<String>(); while (((ServiceRef) ref).getHandlersSize() > 0) { HandlerRef handlerRef = ((ServiceRef) ref).getHandler(); HandlerInfo handlerInfo = new HandlerInfo(); // Loading handler Class tmp = handlerRef.get(HandlerRef.HANDLER_CLASS); if ((tmp == null) || (tmp.getContent() == null)) break; Class<?> handlerClass = null; try { handlerClass = tcl.loadClass((String) tmp.getContent()); } catch(ClassNotFoundException e) { break; } // Load all datas relative to the handler : SOAPHeaders, config init element, // portNames to be set on ArrayList<QName> headers = new ArrayList<QName>(); Hashtable<String,String> config = new Hashtable<String,String>(); ArrayList<String> portNames = new ArrayList<String>(); for (int i = 0; i < handlerRef.size(); i++) if (HandlerRef.HANDLER_LOCALPART.equals(handlerRef.get(i).getType())) { String localpart = ""; String namespace = ""; localpart = (String) handlerRef.get(i).getContent(); if (HandlerRef.HANDLER_NAMESPACE.equals(handlerRef.get(i + 1).getType())) { i++; namespace = (String) handlerRef.get(i).getContent(); } QName header = new QName(namespace, localpart); headers.add(header); } else if (HandlerRef.HANDLER_PARAMNAME.equals(handlerRef.get(i).getType())) { String paramName = ""; String paramValue = ""; paramName = (String) handlerRef.get(i).getContent(); if (HandlerRef.HANDLER_PARAMVALUE.equals(handlerRef.get(i + 1).getType())) { i++; paramValue = (String) handlerRef.get(i).getContent(); } config.put(paramName, paramValue); } else if (HandlerRef.HANDLER_SOAPROLE.equals(handlerRef.get(i).getType())) { String soaprole = ""; soaprole = (String) handlerRef.get(i).getContent(); soaproles.add(soaprole); } else if (HandlerRef.HANDLER_PORTNAME.equals(handlerRef.get(i).getType())) { String portName = ""; portName = (String) handlerRef.get(i).getContent(); portNames.add(portName); } // Set the handlers informations handlerInfo.setHandlerClass(handlerClass); handlerInfo.setHeaders(headers.toArray(new QName[headers.size()])); handlerInfo.setHandlerConfig(config); if (!portNames.isEmpty()) { Iterator<String> iter = portNames.iterator(); while (iter.hasNext()) initHandlerChain(new QName(iter.next()), handlerRegistry, handlerInfo, soaproles); } else { Enumeration<QName> e = portComponentRef.elements(); while(e.hasMoreElements()) initHandlerChain(e.nextElement(), handlerRegistry, handlerInfo, soaproles); } } } return proxyInstance; } return null; }
// in java/org/apache/naming/factory/ResourceFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof ResourceRef) { Reference ref = (Reference) obj; ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch (Exception e) { if (e instanceof NamingException) throw (NamingException) e; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; } } } else { if (ref.getClassName().equals("javax.sql.DataSource")) { String javaxSqlDataSourceFactoryClassName = System.getProperty("javax.sql.DataSource.Factory", Constants.DBCP_DATASOURCE_FACTORY); try { factory = (ObjectFactory) Class.forName(javaxSqlDataSourceFactoryClassName) .newInstance(); } catch (Exception e) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(e); throw ex; } } else if (ref.getClassName().equals("javax.mail.Session")) { String javaxMailSessionFactoryClassName = System.getProperty("javax.mail.Session.Factory", "org.apache.naming.factory.MailSessionFactory"); try { factory = (ObjectFactory) Class.forName(javaxMailSessionFactoryClassName) .newInstance(); } catch(Throwable t) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } } if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/factory/EjbFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof EjbRef) { Reference ref = (Reference) obj; // If ejb-link has been specified, resolving the link using JNDI RefAddr linkRefAddr = ref.get(EjbRef.LINK); if (linkRefAddr != null) { // Retrieving the EJB link String ejbLink = linkRefAddr.getContent().toString(); Object beanObj = (new InitialContext()).lookup(ejbLink); return beanObj; } ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch(Throwable t) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(t); throw ex; } } } else { String javaxEjbFactoryClassName = System.getProperty("javax.ejb.Factory", Constants.OPENEJB_EJB_FACTORY); try { factory = (ObjectFactory) Class.forName(javaxEjbFactoryClassName).newInstance(); } catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/factory/TransactionFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception { if (obj instanceof TransactionRef) { Reference ref = (Reference) obj; ObjectFactory factory = null; RefAddr factoryRefAddr = ref.get(Constants.FACTORY); if (factoryRefAddr != null) { // Using the specified factory String factoryClassName = factoryRefAddr.getContent().toString(); // Loading factory ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Class<?> factoryClass = null; if (tcl != null) { try { factoryClass = tcl.loadClass(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } else { try { factoryClass = Class.forName(factoryClassName); } catch(ClassNotFoundException e) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(e); throw ex; } } if (factoryClass != null) { try { factory = (ObjectFactory) factoryClass.newInstance(); } catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; } } } if (factory != null) { return factory.getObjectInstance (obj, name, nameCtx, environment); } else { throw new NamingException ("Cannot create resource instance"); } } return null; }
// in java/org/apache/naming/ContextBindings.java
public static void bindThread(Object name, Object token) throws NamingException { if (ContextAccessController.checkSecurityToken(name, token)) { Context context = contextNameBindings.get(name); if (context == null) throw new NamingException (sm.getString("contextBindings.unknownContext", name)); threadBindings.put(Thread.currentThread(), context); threadNameBindings.put(Thread.currentThread(), name); } }
// in java/org/apache/naming/ContextBindings.java
public static Context getThread() throws NamingException { Context context = threadBindings.get(Thread.currentThread()); if (context == null) throw new NamingException (sm.getString("contextBindings.noContextBoundToThread")); return context; }
// in java/org/apache/naming/ContextBindings.java
static Object getThreadName() throws NamingException { Object name = threadNameBindings.get(Thread.currentThread()); if (name == null) throw new NamingException (sm.getString("contextBindings.noContextBoundToThread")); return name; }
// in java/org/apache/naming/ContextBindings.java
public static void bindClassLoader(Object name, Object token, ClassLoader classLoader) throws NamingException { if (ContextAccessController.checkSecurityToken(name, token)) { Context context = contextNameBindings.get(name); if (context == null) throw new NamingException (sm.getString("contextBindings.unknownContext", name)); clBindings.put(classLoader, context); clNameBindings.put(classLoader, name); } }
// in java/org/apache/naming/ContextBindings.java
public static Context getClassLoader() throws NamingException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Context context = null; do { context = clBindings.get(cl); if (context != null) { return context; } } while ((cl = cl.getParent()) != null); throw new NamingException (sm.getString("contextBindings.noContextBoundToCL")); }
// in java/org/apache/naming/ContextBindings.java
static Object getClassLoaderName() throws NamingException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Object name = null; do { name = clNameBindings.get(cl); if (name != null) { return name; } } while ((cl = cl.getParent()) != null); throw new NamingException (sm.getString("contextBindings.noContextBoundToCL")); }
// in java/org/apache/naming/SelectorContext.java
protected String parseName(String name) throws NamingException { if ((!initialContext) && (name.startsWith(prefix))) { return (name.substring(prefixLength)); } else { if (initialContext) { return (name); } else { throw new NamingException (sm.getString("selectorContext.noJavaUrl")); } } }
// in java/org/apache/naming/SelectorContext.java
protected Name parseName(Name name) throws NamingException { if (!initialContext && !name.isEmpty() && name.get(0).startsWith(prefix)) { if (name.get(0).equals(prefix)) { return name.getSuffix(1); } else { Name result = name.getSuffix(1); result.add(0, name.get(0).substring(prefixLength)); return result; } } else { if (initialContext) { return name; } else { throw new NamingException( sm.getString("selectorContext.noJavaUrl")); } } }
// in java/org/apache/naming/NamingContext.java
Override public void unbind(Name name) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).unbind(name.getSuffix(1)); } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { bindings.remove(name.get(0)); } }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { return new NamingContextEnumeration(bindings.values().iterator()); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).list(name.getSuffix(1)); }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { return new NamingContextBindingsEnumeration(bindings.values().iterator(), this); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).listBindings(name.getSuffix(1)); }
// in java/org/apache/naming/NamingContext.java
Override public void destroySubcontext(Name name) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).destroySubcontext(name.getSuffix(1)); } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).close(); bindings.remove(name.get(0)); } else { throw new NotContextException (sm.getString("namingContext.contextExpected")); } } }
// in java/org/apache/naming/NamingContext.java
protected Object lookup(Name name, boolean resolveLinks) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { // If name is empty, a newly allocated naming context is returned return new NamingContext(env, this.name, bindings); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { // If the size of the name is greater that 1, then we go through a // number of subcontexts. if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).lookup(name.getSuffix(1)); } else { if ((resolveLinks) && (entry.type == NamingEntry.LINK_REF)) { String link = ((LinkRef) entry.value).getLinkName(); if (link.startsWith(".")) { // Link relative to this context return lookup(link.substring(1)); } else { return (new InitialContext(env)).lookup(link); } } else if (entry.type == NamingEntry.REFERENCE) { try { Object obj = NamingManager.getObjectInstance (entry.value, name, this, env); if(entry.value instanceof ResourceRef) { boolean singleton = Boolean.parseBoolean( (String) ((ResourceRef) entry.value).get( "singleton").getContent()); if (singleton) { entry.type = NamingEntry.ENTRY; entry.value = obj; } } return obj; } catch (NamingException e) { throw e; } catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); } } else { return entry.value; } } }
// in java/org/apache/naming/NamingContext.java
protected void bind(Name name, Object obj, boolean rebind) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (name.size() > 1) { if (entry == null) { throw new NameNotFoundException(sm.getString( "namingContext.nameNotBound", name, name.get(0))); } if (entry.type == NamingEntry.CONTEXT) { if (rebind) { ((Context) entry.value).rebind(name.getSuffix(1), obj); } else { ((Context) entry.value).bind(name.getSuffix(1), obj); } } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if ((!rebind) && (entry != null)) { throw new NameAlreadyBoundException (sm.getString("namingContext.alreadyBound", name.get(0))); } else { // Getting the type of the object and wrapping it within a new // NamingEntry Object toBind = NamingManager.getStateToBind(obj, name, this, env); if (toBind instanceof Context) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.CONTEXT); } else if (toBind instanceof LinkRef) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.LINK_REF); } else if (toBind instanceof Reference) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else if (toBind instanceof Referenceable) { toBind = ((Referenceable) toBind).getReference(); entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else { entry = new NamingEntry(name.get(0), toBind, NamingEntry.ENTRY); } bindings.put(name.get(0), entry); } } }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void unbind(String name) throws NamingException { File file = file(name); if (file == null) throw new NameNotFoundException( sm.getString("resources.notFound", name)); if (!file.delete()) throw new NamingException (sm.getString("resources.unbindFailed", name)); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void rename(String oldName, String newName) throws NamingException { File file = file(oldName); if (file == null) throw new NameNotFoundException (sm.getString("resources.notFound", oldName)); File newFile = new File(base, newName); if (!file.renameTo(newFile)) { throw new NamingException(sm.getString("resources.renameFail", oldName, newName)); } }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void rebind(String name, Object obj, Attributes attrs) throws NamingException { // Note: No custom attributes allowed // Check obj type File file = new File(base, name); InputStream is = null; if (obj instanceof Resource) { try { is = ((Resource) obj).streamContent(); } catch (IOException e) { // Ignore } } else if (obj instanceof InputStream) { is = (InputStream) obj; } else if (obj instanceof DirContext) { if (file.exists()) { if (!file.delete()) throw new NamingException (sm.getString("resources.bindFailed", name)); } if (!file.mkdir()) throw new NamingException (sm.getString("resources.bindFailed", name)); } if (is == null) throw new NamingException (sm.getString("resources.bindFailed", name)); // Open os try { FileOutputStream os = null; byte buffer[] = new byte[BUFFER_SIZE]; int len = -1; try { os = new FileOutputStream(file); while (true) { len = is.read(buffer); if (len == -1) break; os.write(buffer, 0, len); } } finally { if (os != null) os.close(); is.close(); } } catch (IOException e) { NamingException ne = new NamingException (sm.getString("resources.bindFailed", e)); ne.initCause(e); throw ne; } }
// in java/org/apache/naming/resources/FileDirContext.java
Override public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException (sm.getString("resources.alreadyBound", name)); if (!file.mkdir()) throw new NamingException (sm.getString("resources.bindFailed", name)); return (DirContext) lookup(name); }
1
            
// in java/org/apache/naming/NamingContext.java
catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); }
256
            
// in java/org/apache/naming/factory/BeanFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws NamingException { if (obj instanceof ResourceRef) { try { Reference ref = (Reference) obj; String beanClassName = ref.getClassName(); Class<?> beanClass = null; ClassLoader tcl = Thread.currentThread().getContextClassLoader(); if (tcl != null) { try { beanClass = tcl.loadClass(beanClassName); } catch(ClassNotFoundException e) { } } else { try { beanClass = Class.forName(beanClassName); } catch(ClassNotFoundException e) { e.printStackTrace(); } } if (beanClass == null) { throw new NamingException ("Class not found: " + beanClassName); } BeanInfo bi = Introspector.getBeanInfo(beanClass); PropertyDescriptor[] pda = bi.getPropertyDescriptors(); Object bean = beanClass.newInstance(); Enumeration<RefAddr> e = ref.getAll(); while (e.hasMoreElements()) { RefAddr ra = e.nextElement(); String propName = ra.getType(); if (propName.equals(Constants.FACTORY) || propName.equals("scope") || propName.equals("auth") || propName.equals("singleton")) { continue; } String value = (String)ra.getContent(); Object[] valueArray = new Object[1]; int i = 0; for (i = 0; i<pda.length; i++) { if (pda[i].getName().equals(propName)) { Class<?> propType = pda[i].getPropertyType(); if (propType.equals(String.class)) { valueArray[0] = value; } else if (propType.equals(Character.class) || propType.equals(char.class)) { valueArray[0] = Character.valueOf(value.charAt(0)); } else if (propType.equals(Byte.class) || propType.equals(byte.class)) { valueArray[0] = new Byte(value); } else if (propType.equals(Short.class) || propType.equals(short.class)) { valueArray[0] = new Short(value); } else if (propType.equals(Integer.class) || propType.equals(int.class)) { valueArray[0] = new Integer(value); } else if (propType.equals(Long.class) || propType.equals(long.class)) { valueArray[0] = new Long(value); } else if (propType.equals(Float.class) || propType.equals(float.class)) { valueArray[0] = new Float(value); } else if (propType.equals(Double.class) || propType.equals(double.class)) { valueArray[0] = new Double(value); } else if (propType.equals(Boolean.class) || propType.equals(boolean.class)) { valueArray[0] = Boolean.valueOf(value); } else { throw new NamingException ("String conversion for property type '" + propType.getName() + "' not available"); } Method setProp = pda[i].getWriteMethod(); if (setProp != null) { setProp.invoke(bean, valueArray); } else { throw new NamingException ("Write not allowed for property: " + propName); } break; } } if (i == pda.length) { throw new NamingException ("No set method found for property: " + propName); } } return bean; } catch (java.beans.IntrospectionException ie) { NamingException ne = new NamingException(ie.getMessage()); ne.setRootCause(ie); throw ne; } catch (java.lang.IllegalAccessException iae) { NamingException ne = new NamingException(iae.getMessage()); ne.setRootCause(iae); throw ne; } catch (java.lang.InstantiationException ie2) { NamingException ne = new NamingException(ie2.getMessage()); ne.setRootCause(ie2); throw ne; } catch (java.lang.reflect.InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } NamingException ne = new NamingException(ite.getMessage()); ne.setRootCause(ite); throw ne; } } else { return null; } }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws NamingException { Object result = super.getObjectInstance(obj, name, nameCtx, environment); // Can we process this request? if (result!=null) { Reference ref = (Reference) obj; RefAddr userAttr = ref.get("username"); RefAddr passAttr = ref.get("password"); if (userAttr.getContent()!=null && passAttr.getContent()!=null) { result = wrapDataSource(result,userAttr.getContent().toString(), passAttr.getContent().toString()); } } return result; }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
protected Object wrapDataSource(Object datasource, String username, String password) throws NamingException { try { Class<?> proxyClass = Proxy.getProxyClass(datasource.getClass().getClassLoader(), datasource.getClass().getInterfaces()); Constructor<?> proxyConstructor = proxyClass.getConstructor(new Class[] { InvocationHandler.class }); DataSourceHandler handler = new DataSourceHandler((DataSource)datasource, username, password); return proxyConstructor.newInstance(handler); }catch (Exception x) { if (x instanceof InvocationTargetException) { Throwable cause = x.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } if (cause instanceof Exception) { x = (Exception) cause; } } if (x instanceof NamingException) throw (NamingException)x; else { NamingException nx = new NamingException(x.getMessage()); nx.initCause(x); throw nx; } } }
// in java/org/apache/naming/factory/ResourceLinkFactory.java
Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws NamingException { if (!(obj instanceof ResourceLinkRef)) return null; // Can we process this request? Reference ref = (Reference) obj; // Read the global ref addr String globalName = null; RefAddr refAddr = ref.get(ResourceLinkRef.GLOBALNAME); if (refAddr != null) { globalName = refAddr.getContent().toString(); Object result = null; result = globalContext.lookup(globalName); // FIXME: Check type return result; } return (null); }
// in java/org/apache/naming/ContextBindings.java
public static void bindThread(Object name, Object token) throws NamingException { if (ContextAccessController.checkSecurityToken(name, token)) { Context context = contextNameBindings.get(name); if (context == null) throw new NamingException (sm.getString("contextBindings.unknownContext", name)); threadBindings.put(Thread.currentThread(), context); threadNameBindings.put(Thread.currentThread(), name); } }
// in java/org/apache/naming/ContextBindings.java
public static Context getThread() throws NamingException { Context context = threadBindings.get(Thread.currentThread()); if (context == null) throw new NamingException (sm.getString("contextBindings.noContextBoundToThread")); return context; }
// in java/org/apache/naming/ContextBindings.java
static Object getThreadName() throws NamingException { Object name = threadNameBindings.get(Thread.currentThread()); if (name == null) throw new NamingException (sm.getString("contextBindings.noContextBoundToThread")); return name; }
// in java/org/apache/naming/ContextBindings.java
public static void bindClassLoader(Object name, Object token, ClassLoader classLoader) throws NamingException { if (ContextAccessController.checkSecurityToken(name, token)) { Context context = contextNameBindings.get(name); if (context == null) throw new NamingException (sm.getString("contextBindings.unknownContext", name)); clBindings.put(classLoader, context); clNameBindings.put(classLoader, name); } }
// in java/org/apache/naming/ContextBindings.java
public static Context getClassLoader() throws NamingException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Context context = null; do { context = clBindings.get(cl); if (context != null) { return context; } } while ((cl = cl.getParent()) != null); throw new NamingException (sm.getString("contextBindings.noContextBoundToCL")); }
// in java/org/apache/naming/ContextBindings.java
static Object getClassLoaderName() throws NamingException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Object name = null; do { name = clNameBindings.get(cl); if (name != null) { return name; } } while ((cl = cl.getParent()) != null); throw new NamingException (sm.getString("contextBindings.noContextBoundToCL")); }
// in java/org/apache/naming/SelectorContext.java
Override public Object lookup(Name name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingName", "lookup", name)); } // Strip the URL header // Find the appropriate NamingContext according to the current bindings // Execute the lookup on that context return getBoundContext().lookup(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public Object lookup(String name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingString", "lookup", name)); } // Strip the URL header // Find the appropriate NamingContext according to the current bindings // Execute the lookup on that context return getBoundContext().lookup(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public void bind(Name name, Object obj) throws NamingException { getBoundContext().bind(parseName(name), obj); }
// in java/org/apache/naming/SelectorContext.java
Override public void bind(String name, Object obj) throws NamingException { getBoundContext().bind(parseName(name), obj); }
// in java/org/apache/naming/SelectorContext.java
Override public void rebind(Name name, Object obj) throws NamingException { getBoundContext().rebind(parseName(name), obj); }
// in java/org/apache/naming/SelectorContext.java
Override public void rebind(String name, Object obj) throws NamingException { getBoundContext().rebind(parseName(name), obj); }
// in java/org/apache/naming/SelectorContext.java
Override public void unbind(Name name) throws NamingException { getBoundContext().unbind(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public void unbind(String name) throws NamingException { getBoundContext().unbind(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public void rename(Name oldName, Name newName) throws NamingException { getBoundContext().rename(parseName(oldName), parseName(newName)); }
// in java/org/apache/naming/SelectorContext.java
Override public void rename(String oldName, String newName) throws NamingException { getBoundContext().rename(parseName(oldName), parseName(newName)); }
// in java/org/apache/naming/SelectorContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingName", "list", name)); } return getBoundContext().list(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public NamingEnumeration<NameClassPair> list(String name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingString", "list", name)); } return getBoundContext().list(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingName", "listBindings", name)); } return getBoundContext().listBindings(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public NamingEnumeration<Binding> listBindings(String name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingString", "listBindings", name)); } return getBoundContext().listBindings(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public void destroySubcontext(Name name) throws NamingException { getBoundContext().destroySubcontext(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public void destroySubcontext(String name) throws NamingException { getBoundContext().destroySubcontext(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public Context createSubcontext(Name name) throws NamingException { return getBoundContext().createSubcontext(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public Context createSubcontext(String name) throws NamingException { return getBoundContext().createSubcontext(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public Object lookupLink(Name name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingName", "lookupLink", name)); } return getBoundContext().lookupLink(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public Object lookupLink(String name) throws NamingException { if (log.isDebugEnabled()) { log.debug(sm.getString("selectorContext.methodUsingString", "lookupLink", name)); } return getBoundContext().lookupLink(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public NameParser getNameParser(Name name) throws NamingException { return getBoundContext().getNameParser(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public NameParser getNameParser(String name) throws NamingException { return getBoundContext().getNameParser(parseName(name)); }
// in java/org/apache/naming/SelectorContext.java
Override public Name composeName(Name name, Name prefix) throws NamingException { Name prefixClone = (Name) prefix.clone(); return prefixClone.addAll(name); }
// in java/org/apache/naming/SelectorContext.java
Override public String composeName(String name, String prefix) throws NamingException { return prefix + "/" + name; }
// in java/org/apache/naming/SelectorContext.java
Override public Object addToEnvironment(String propName, Object propVal) throws NamingException { return getBoundContext().addToEnvironment(propName, propVal); }
// in java/org/apache/naming/SelectorContext.java
Override public Object removeFromEnvironment(String propName) throws NamingException { return getBoundContext().removeFromEnvironment(propName); }
// in java/org/apache/naming/SelectorContext.java
Override public Hashtable<?,?> getEnvironment() throws NamingException { return getBoundContext().getEnvironment(); }
// in java/org/apache/naming/SelectorContext.java
Override public void close() throws NamingException { getBoundContext().close(); }
// in java/org/apache/naming/SelectorContext.java
Override public String getNameInNamespace() throws NamingException { return prefix; }
// in java/org/apache/naming/SelectorContext.java
protected Context getBoundContext() throws NamingException { if (initialContext) { String ICName = IC_PREFIX; if (ContextBindings.isThreadBound()) { ICName += ContextBindings.getThreadName(); } else if (ContextBindings.isClassLoaderBound()) { ICName += ContextBindings.getClassLoaderName(); } Context initialContext = ContextBindings.getContext(ICName); if (initialContext == null) { // Allocating a new context and binding it to the appropriate // name initialContext = new NamingContext(env, ICName); ContextBindings.bindContext(ICName, initialContext); } return initialContext; } else { if (ContextBindings.isThreadBound()) { return ContextBindings.getThread(); } else { return ContextBindings.getClassLoader(); } } }
// in java/org/apache/naming/SelectorContext.java
protected String parseName(String name) throws NamingException { if ((!initialContext) && (name.startsWith(prefix))) { return (name.substring(prefixLength)); } else { if (initialContext) { return (name); } else { throw new NamingException (sm.getString("selectorContext.noJavaUrl")); } } }
// in java/org/apache/naming/SelectorContext.java
protected Name parseName(Name name) throws NamingException { if (!initialContext && !name.isEmpty() && name.get(0).startsWith(prefix)) { if (name.get(0).equals(prefix)) { return name.getSuffix(1); } else { Name result = name.getSuffix(1); result.add(0, name.get(0).substring(prefixLength)); return result; } } else { if (initialContext) { return name; } else { throw new NamingException( sm.getString("selectorContext.noJavaUrl")); } } }
// in java/org/apache/naming/NameParserImpl.java
Override public Name parse(String name) throws NamingException { return new CompositeName(name); }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
Override public Binding next() throws NamingException { return nextElementInternal(); }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
Override public boolean hasMore() throws NamingException { return iterator.hasNext(); }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
Override public void close() throws NamingException { }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
private Binding nextElementInternal() throws NamingException { NamingEntry entry = iterator.next(); Object value; // If the entry is a reference, resolve it if (entry.type == NamingEntry.REFERENCE || entry.type == NamingEntry.LINK_REF) { try { value = ctx.lookup(new CompositeName(entry.name)); } catch (NamingException e) { throw e; } catch (Exception e) { NamingException ne = new NamingException(e.getMessage()); ne.initCause(e); throw ne; } } else { value = entry.value; } return new Binding(entry.name, value.getClass().getName(), value, true); }
// in java/org/apache/naming/NamingContextEnumeration.java
Override public NameClassPair next() throws NamingException { return nextElement(); }
// in java/org/apache/naming/NamingContextEnumeration.java
Override public boolean hasMore() throws NamingException { return iterator.hasNext(); }
// in java/org/apache/naming/NamingContextEnumeration.java
Override public void close() throws NamingException { }
// in java/org/apache/naming/NamingContext.java
Override public Object lookup(Name name) throws NamingException { return lookup(name, true); }
// in java/org/apache/naming/NamingContext.java
Override public Object lookup(String name) throws NamingException { return lookup(new CompositeName(name), true); }
// in java/org/apache/naming/NamingContext.java
Override public void bind(Name name, Object obj) throws NamingException { bind(name, obj, false); }
// in java/org/apache/naming/NamingContext.java
Override public void bind(String name, Object obj) throws NamingException { bind(new CompositeName(name), obj); }
// in java/org/apache/naming/NamingContext.java
Override public void rebind(Name name, Object obj) throws NamingException { bind(name, obj, true); }
// in java/org/apache/naming/NamingContext.java
Override public void rebind(String name, Object obj) throws NamingException { rebind(new CompositeName(name), obj); }
// in java/org/apache/naming/NamingContext.java
Override public void unbind(Name name) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).unbind(name.getSuffix(1)); } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { bindings.remove(name.get(0)); } }
// in java/org/apache/naming/NamingContext.java
Override public void unbind(String name) throws NamingException { unbind(new CompositeName(name)); }
// in java/org/apache/naming/NamingContext.java
Override public void rename(Name oldName, Name newName) throws NamingException { Object value = lookup(oldName); bind(newName, value); unbind(oldName); }
// in java/org/apache/naming/NamingContext.java
Override public void rename(String oldName, String newName) throws NamingException { rename(new CompositeName(oldName), new CompositeName(newName)); }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { return new NamingContextEnumeration(bindings.values().iterator()); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).list(name.getSuffix(1)); }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<NameClassPair> list(String name) throws NamingException { return list(new CompositeName(name)); }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { return new NamingContextBindingsEnumeration(bindings.values().iterator(), this); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).listBindings(name.getSuffix(1)); }
// in java/org/apache/naming/NamingContext.java
Override public NamingEnumeration<Binding> listBindings(String name) throws NamingException { return listBindings(new CompositeName(name)); }
// in java/org/apache/naming/NamingContext.java
Override public void destroySubcontext(Name name) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).destroySubcontext(name.getSuffix(1)); } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).close(); bindings.remove(name.get(0)); } else { throw new NotContextException (sm.getString("namingContext.contextExpected")); } } }
// in java/org/apache/naming/NamingContext.java
Override public void destroySubcontext(String name) throws NamingException { destroySubcontext(new CompositeName(name)); }
// in java/org/apache/naming/NamingContext.java
Override public Context createSubcontext(Name name) throws NamingException { if (!checkWritable()) { return null; } NamingContext newContext = new NamingContext(env, this.name); bind(name, newContext); newContext.setExceptionOnFailedWrite(getExceptionOnFailedWrite()); return newContext; }
// in java/org/apache/naming/NamingContext.java
Override public Context createSubcontext(String name) throws NamingException { return createSubcontext(new CompositeName(name)); }
// in java/org/apache/naming/NamingContext.java
Override public Object lookupLink(Name name) throws NamingException { return lookup(name, false); }
// in java/org/apache/naming/NamingContext.java
Override public Object lookupLink(String name) throws NamingException { return lookup(new CompositeName(name), false); }
// in java/org/apache/naming/NamingContext.java
Override public NameParser getNameParser(Name name) throws NamingException { while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) return nameParser; if (name.size() > 1) { Object obj = bindings.get(name.get(0)); if (obj instanceof Context) { return ((Context) obj).getNameParser(name.getSuffix(1)); } else { throw new NotContextException (sm.getString("namingContext.contextExpected")); } } return nameParser; }
// in java/org/apache/naming/NamingContext.java
Override public NameParser getNameParser(String name) throws NamingException { return getNameParser(new CompositeName(name)); }
// in java/org/apache/naming/NamingContext.java
Override public Name composeName(Name name, Name prefix) throws NamingException { prefix = (Name) prefix.clone(); return prefix.addAll(name); }
// in java/org/apache/naming/NamingContext.java
Override public String composeName(String name, String prefix) throws NamingException { return prefix + "/" + name; }
// in java/org/apache/naming/NamingContext.java
Override public Object addToEnvironment(String propName, Object propVal) throws NamingException { return env.put(propName, propVal); }
// in java/org/apache/naming/NamingContext.java
Override public Object removeFromEnvironment(String propName) throws NamingException { return env.remove(propName); }
// in java/org/apache/naming/NamingContext.java
Override public Hashtable<?,?> getEnvironment() throws NamingException { return env; }
// in java/org/apache/naming/NamingContext.java
Override public void close() throws NamingException { if (!checkWritable()) { return; } env.clear(); }
// in java/org/apache/naming/NamingContext.java
Override public String getNameInNamespace() throws NamingException { throw new OperationNotSupportedException (sm.getString("namingContext.noAbsoluteName")); //FIXME ? }
// in java/org/apache/naming/NamingContext.java
protected Object lookup(Name name, boolean resolveLinks) throws NamingException { // Removing empty parts while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) { // If name is empty, a newly allocated naming context is returned return new NamingContext(env, this.name, bindings); } NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { // If the size of the name is greater that 1, then we go through a // number of subcontexts. if (entry.type != NamingEntry.CONTEXT) { throw new NamingException (sm.getString("namingContext.contextExpected")); } return ((Context) entry.value).lookup(name.getSuffix(1)); } else { if ((resolveLinks) && (entry.type == NamingEntry.LINK_REF)) { String link = ((LinkRef) entry.value).getLinkName(); if (link.startsWith(".")) { // Link relative to this context return lookup(link.substring(1)); } else { return (new InitialContext(env)).lookup(link); } } else if (entry.type == NamingEntry.REFERENCE) { try { Object obj = NamingManager.getObjectInstance (entry.value, name, this, env); if(entry.value instanceof ResourceRef) { boolean singleton = Boolean.parseBoolean( (String) ((ResourceRef) entry.value).get( "singleton").getContent()); if (singleton) { entry.type = NamingEntry.ENTRY; entry.value = obj; } } return obj; } catch (NamingException e) { throw e; } catch (Exception e) { log.warn(sm.getString ("namingContext.failResolvingReference"), e); throw new NamingException(e.getMessage()); } } else { return entry.value; } } }
// in java/org/apache/naming/NamingContext.java
protected void bind(Name name, Object obj, boolean rebind) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (name.size() > 1) { if (entry == null) { throw new NameNotFoundException(sm.getString( "namingContext.nameNotBound", name, name.get(0))); } if (entry.type == NamingEntry.CONTEXT) { if (rebind) { ((Context) entry.value).rebind(name.getSuffix(1), obj); } else { ((Context) entry.value).bind(name.getSuffix(1), obj); } } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if ((!rebind) && (entry != null)) { throw new NameAlreadyBoundException (sm.getString("namingContext.alreadyBound", name.get(0))); } else { // Getting the type of the object and wrapping it within a new // NamingEntry Object toBind = NamingManager.getStateToBind(obj, name, this, env); if (toBind instanceof Context) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.CONTEXT); } else if (toBind instanceof LinkRef) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.LINK_REF); } else if (toBind instanceof Reference) { entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else if (toBind instanceof Referenceable) { toBind = ((Referenceable) toBind).getReference(); entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE); } else { entry = new NamingEntry(name.get(0), toBind, NamingEntry.ENTRY); } bindings.put(name.get(0), entry); } } }
// in java/org/apache/naming/NamingContext.java
protected boolean checkWritable() throws NamingException { if (isWritable()) { return true; } else { if (exceptionOnFailedWrite) { throw new javax.naming.OperationNotSupportedException( sm.getString("namingContext.readOnly")); } } return false; }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void unbind(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void rename(String oldName, String newName) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<NameClassPair> list(String name) throws NamingException { return list(getEscapedJndiName(name)); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { if (name.isEmpty()) return new NamingContextEnumeration(list(entries).iterator()); Entry entry = treeLookup(name); if (entry == null) throw new NameNotFoundException (sm.getString("resources.notFound", name)); return new NamingContextEnumeration(list(entry).iterator()); }
// in java/org/apache/naming/resources/WARDirContext.java
Override protected List<NamingEntry> doListBindings(String strName) throws NamingException { Name name = getEscapedJndiName(strName); if (name.isEmpty()) return list(entries); Entry entry = treeLookup(name); if (entry == null) return null; return list(entry); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void destroySubcontext(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public Object lookupLink(String name) throws NamingException { // Note : Links are not supported return lookup(name); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public String getNameInNamespace() throws NamingException { return docBase; }
// in java/org/apache/naming/resources/WARDirContext.java
Override protected Attributes doGetAttributes(String name, String[] attrIds) throws NamingException { return getAttributes(getEscapedJndiName(name), attrIds); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { Entry entry = null; if (name.isEmpty()) entry = entries; else entry = treeLookup(name); if (entry == null) return null; ZipEntry zipEntry = entry.getEntry(); ResourceAttributes attrs = new ResourceAttributes(); attrs.setCreationDate(new Date(zipEntry.getTime())); attrs.setName(entry.getName()); if (!zipEntry.isDirectory()) attrs.setResourceType(""); else attrs.setCollection(true); attrs.setContentLength(zipEntry.getSize()); attrs.setLastModified(zipEntry.getTime()); return attrs; }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void bind(String name, Object obj, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void rebind(String name, Object obj, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public DirContext getSchema(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public DirContext getSchemaClassDefinition(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void unbind(String name) throws NamingException { File file = file(name); if (file == null) throw new NameNotFoundException( sm.getString("resources.notFound", name)); if (!file.delete()) throw new NamingException (sm.getString("resources.unbindFailed", name)); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void rename(String oldName, String newName) throws NamingException { File file = file(oldName); if (file == null) throw new NameNotFoundException (sm.getString("resources.notFound", oldName)); File newFile = new File(base, newName); if (!file.renameTo(newFile)) { throw new NamingException(sm.getString("resources.renameFail", oldName, newName)); } }
// in java/org/apache/naming/resources/FileDirContext.java
Override public NamingEnumeration<NameClassPair> list(String name) throws NamingException { File file = file(name); if (file == null) throw new NameNotFoundException (sm.getString("resources.notFound", name)); return new NamingContextEnumeration(list(file).iterator()); }
// in java/org/apache/naming/resources/FileDirContext.java
Override protected List<NamingEntry> doListBindings(String name) throws NamingException { File file = file(name); if (file == null) return null; return list(file); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void destroySubcontext(String name) throws NamingException { unbind(name); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public Object lookupLink(String name) throws NamingException { // Note : Links are not supported return lookup(name); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public String getNameInNamespace() throws NamingException { return docBase; }
// in java/org/apache/naming/resources/FileDirContext.java
Override protected Attributes doGetAttributes(String name, String[] attrIds) throws NamingException { // Building attribute list File file = file(name); if (file == null) return null; return new FileResourceAttributes(file); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void bind(String name, Object obj, Attributes attrs) throws NamingException { // Note: No custom attributes allowed File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException (sm.getString("resources.alreadyBound", name)); rebind(name, obj, attrs); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void rebind(String name, Object obj, Attributes attrs) throws NamingException { // Note: No custom attributes allowed // Check obj type File file = new File(base, name); InputStream is = null; if (obj instanceof Resource) { try { is = ((Resource) obj).streamContent(); } catch (IOException e) { // Ignore } } else if (obj instanceof InputStream) { is = (InputStream) obj; } else if (obj instanceof DirContext) { if (file.exists()) { if (!file.delete()) throw new NamingException (sm.getString("resources.bindFailed", name)); } if (!file.mkdir()) throw new NamingException (sm.getString("resources.bindFailed", name)); } if (is == null) throw new NamingException (sm.getString("resources.bindFailed", name)); // Open os try { FileOutputStream os = null; byte buffer[] = new byte[BUFFER_SIZE]; int len = -1; try { os = new FileOutputStream(file); while (true) { len = is.read(buffer); if (len == -1) break; os.write(buffer, 0, len); } } finally { if (os != null) os.close(); is.close(); } } catch (IOException e) { NamingException ne = new NamingException (sm.getString("resources.bindFailed", e)); ne.initCause(e); throw ne; } }
// in java/org/apache/naming/resources/FileDirContext.java
Override public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException (sm.getString("resources.alreadyBound", name)); if (!file.mkdir()) throw new NamingException (sm.getString("resources.bindFailed", name)); return (DirContext) lookup(name); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public DirContext getSchema(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public DirContext getSchemaClassDefinition(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { return null; }
// in java/org/apache/naming/resources/FileDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { return null; }
// in java/org/apache/naming/resources/FileDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException { return null; }
// in java/org/apache/naming/resources/FileDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { return null; }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final Object lookup(Name name) throws NamingException { return lookup(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final Object lookup(String name) throws NamingException { // First check for aliases if (!aliases.isEmpty()) { AliasResult result = findAlias(name); if (result.dirContext != null) { return result.dirContext.lookup(result.aliasName); } } // Next do a standard lookup Object obj = doLookup(name); if (obj != null) return obj; // Check the alternate locations for (DirContext altDirContext : altDirContexts) { try { obj = altDirContext.lookup("/META-INF/resources" + name); if (obj != null) return obj; } catch ( NamingException ex) { // ignore } } // Really not found throw new NameNotFoundException( sm.getString("resources.notFound", name)); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void bind(Name name, Object obj) throws NamingException { bind(name.toString(), obj); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void bind(String name, Object obj) throws NamingException { bind(name, obj, null); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void rebind(Name name, Object obj) throws NamingException { rebind(name.toString(), obj); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void rebind(String name, Object obj) throws NamingException { rebind(name, obj, null); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void unbind(Name name) throws NamingException { unbind(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void rename(Name oldName, Name newName) throws NamingException { rename(oldName.toString(), newName.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { return list(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final NamingEnumeration<Binding> listBindings(Name name) throws NamingException { return listBindings(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final NamingEnumeration<Binding> listBindings(String name) throws NamingException { if (!aliases.isEmpty()) { AliasResult result = findAlias(name); if (result.dirContext != null) { return result.dirContext.listBindings(result.aliasName); } } // Next do a standard lookup List<NamingEntry> bindings = doListBindings(name); // Check the alternate locations List<NamingEntry> altBindings = null; for (DirContext altDirContext : altDirContexts) { if (altDirContext instanceof BaseDirContext) { altBindings = ((BaseDirContext) altDirContext).doListBindings( "/META-INF/resources" + name); } if (altBindings != null) { if (bindings == null) { bindings = altBindings; } else { bindings.addAll(altBindings); } } } if (bindings != null) { return new NamingContextBindingsEnumeration(bindings.iterator(), this); } // Really not found throw new NameNotFoundException( sm.getString("resources.notFound", name)); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void destroySubcontext(Name name) throws NamingException { destroySubcontext(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Context createSubcontext(Name name) throws NamingException { return createSubcontext(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Context createSubcontext(String name) throws NamingException { return createSubcontext(name, null); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Object lookupLink(Name name) throws NamingException { return lookupLink(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public NameParser getNameParser(Name name) throws NamingException { return new NameParserImpl(); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public NameParser getNameParser(String name) throws NamingException { return new NameParserImpl(); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Name composeName(Name name, Name prefix) throws NamingException { Name clone = (Name) prefix.clone(); return clone.addAll(name); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public String composeName(String name, String prefix) throws NamingException { return prefix + "/" + name; }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Object addToEnvironment(String propName, Object propVal) throws NamingException { return env.put(propName, propVal); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Object removeFromEnvironment(String propName) throws NamingException { return env.remove(propName); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Hashtable<String,Object> getEnvironment() throws NamingException { return env; }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void close() throws NamingException { env.clear(); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Attributes getAttributes(Name name) throws NamingException { return getAttributes(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Attributes getAttributes(String name) throws NamingException { return getAttributes(name, null); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { return getAttributes(name.toString(), attrIds); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public final Attributes getAttributes(String name, String[] attrIds) throws NamingException { // First check for aliases if (!aliases.isEmpty()) { AliasResult result = findAlias(name); if (result.dirContext != null) { return result.dirContext.getAttributes( result.aliasName, attrIds); } } // Next do a standard lookup Attributes attrs = doGetAttributes(name, attrIds); if (attrs != null) return attrs; // Check the alternate locations for (DirContext altDirContext : altDirContexts) { if (altDirContext instanceof BaseDirContext) attrs = ((BaseDirContext) altDirContext).doGetAttributes( "/META-INF/resources" + name, attrIds); else { try { attrs = altDirContext.getAttributes(name, attrIds); } catch (NamingException ne) { // Ignore } } if (attrs != null) return attrs; } // Really not found throw new NameNotFoundException( sm.getString("resources.notFound", name)); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void modifyAttributes(Name name, int mod_op, Attributes attrs) throws NamingException { modifyAttributes(name.toString(), mod_op, attrs); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException { modifyAttributes(name.toString(), mods); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void bind(Name name, Object obj, Attributes attrs) throws NamingException { bind(name.toString(), obj, attrs); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public void rebind(Name name, Object obj, Attributes attrs) throws NamingException { rebind(name.toString(), obj, attrs); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException { return createSubcontext(name.toString(), attrs); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public DirContext getSchema(Name name) throws NamingException { return getSchema(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public DirContext getSchemaClassDefinition(Name name) throws NamingException { return getSchemaClassDefinition(name.toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { return search(name.toString(), matchingAttributes, attributesToReturn); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes) throws NamingException { return search(name.toString(), matchingAttributes); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public NamingEnumeration<SearchResult> search (Name name, String filter, SearchControls cons) throws NamingException { return search(name.toString(), filter, cons); }
// in java/org/apache/naming/resources/BaseDirContext.java
Override public NamingEnumeration<SearchResult> search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { return search(name.toString(), filterExpr, filterArgs, cons); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Object lookup(Name name) throws NamingException { CacheEntry entry = cacheLookup(name.toString()); if (entry != null) { if (!entry.exists) { throw NOT_FOUND_EXCEPTION; } if (entry.resource != null) { // Check content caching. return entry.resource; } else { return entry.context; } } Object object = dirContext.lookup(parseName(name)); if (object instanceof InputStream) return new Resource((InputStream) object); else return object; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Object lookup(String name) throws NamingException { CacheEntry entry = cacheLookup(name); if (entry != null) { if (!entry.exists) { throw NOT_FOUND_EXCEPTION; } if (entry.resource != null) { return entry.resource; } else { return entry.context; } } Object object = dirContext.lookup(parseName(name)); if (object instanceof InputStream) { return new Resource((InputStream) object); } else if (object instanceof DirContext) { return object; } else if (object instanceof Resource) { return object; } else { return new Resource(new ByteArrayInputStream (object.toString().getBytes(Constants.ISO_8859_1))); } }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void bind(Name name, Object obj) throws NamingException { dirContext.bind(parseName(name), obj); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void bind(String name, Object obj) throws NamingException { dirContext.bind(parseName(name), obj); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void rebind(Name name, Object obj) throws NamingException { dirContext.rebind(parseName(name), obj); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void rebind(String name, Object obj) throws NamingException { dirContext.rebind(parseName(name), obj); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void unbind(Name name) throws NamingException { dirContext.unbind(parseName(name)); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void unbind(String name) throws NamingException { dirContext.unbind(parseName(name)); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void rename(Name oldName, Name newName) throws NamingException { dirContext.rename(parseName(oldName), parseName(newName)); cacheUnload(oldName.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void rename(String oldName, String newName) throws NamingException { dirContext.rename(parseName(oldName), parseName(newName)); cacheUnload(oldName); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { return dirContext.list(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<NameClassPair> list(String name) throws NamingException { return dirContext.list(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { return dirContext.listBindings(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<Binding> listBindings(String name) throws NamingException { return dirContext.listBindings(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void destroySubcontext(Name name) throws NamingException { dirContext.destroySubcontext(parseName(name)); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void destroySubcontext(String name) throws NamingException { dirContext.destroySubcontext(parseName(name)); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Context createSubcontext(Name name) throws NamingException { Context context = dirContext.createSubcontext(parseName(name)); cacheUnload(name.toString()); return context; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Context createSubcontext(String name) throws NamingException { Context context = dirContext.createSubcontext(parseName(name)); cacheUnload(name); return context; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Object lookupLink(Name name) throws NamingException { return dirContext.lookupLink(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Object lookupLink(String name) throws NamingException { return dirContext.lookupLink(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NameParser getNameParser(Name name) throws NamingException { return dirContext.getNameParser(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NameParser getNameParser(String name) throws NamingException { return dirContext.getNameParser(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Name composeName(Name name, Name prefix) throws NamingException { Name prefixClone = (Name) prefix.clone(); return prefixClone.addAll(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public String composeName(String name, String prefix) throws NamingException { return prefix + "/" + name; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Object addToEnvironment(String propName, Object propVal) throws NamingException { return dirContext.addToEnvironment(propName, propVal); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Object removeFromEnvironment(String propName) throws NamingException { return dirContext.removeFromEnvironment(propName); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Hashtable<?,?> getEnvironment() throws NamingException { return dirContext.getEnvironment(); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void close() throws NamingException { dirContext.close(); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public String getNameInNamespace() throws NamingException { return dirContext.getNameInNamespace(); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Attributes getAttributes(Name name) throws NamingException { CacheEntry entry = cacheLookup(name.toString()); if (entry != null) { if (!entry.exists) { throw NOT_FOUND_EXCEPTION; } return entry.attributes; } Attributes attributes = dirContext.getAttributes(parseName(name)); if (!(attributes instanceof ResourceAttributes)) { attributes = new ResourceAttributes(attributes); } return attributes; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Attributes getAttributes(String name) throws NamingException { CacheEntry entry = cacheLookup(name); if (entry != null) { if (!entry.exists) { throw NOT_FOUND_EXCEPTION; } return entry.attributes; } Attributes attributes = dirContext.getAttributes(parseName(name)); if (!(attributes instanceof ResourceAttributes)) { attributes = new ResourceAttributes(attributes); } return attributes; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { Attributes attributes = dirContext.getAttributes(parseName(name), attrIds); if (!(attributes instanceof ResourceAttributes)) { attributes = new ResourceAttributes(attributes); } return attributes; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public Attributes getAttributes(String name, String[] attrIds) throws NamingException { Attributes attributes = dirContext.getAttributes(parseName(name), attrIds); if (!(attributes instanceof ResourceAttributes)) { attributes = new ResourceAttributes(attributes); } return attributes; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void modifyAttributes(Name name, int mod_op, Attributes attrs) throws NamingException { dirContext.modifyAttributes(parseName(name), mod_op, attrs); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { dirContext.modifyAttributes(parseName(name), mod_op, attrs); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException { dirContext.modifyAttributes(parseName(name), mods); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { dirContext.modifyAttributes(parseName(name), mods); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void bind(Name name, Object obj, Attributes attrs) throws NamingException { dirContext.bind(parseName(name), obj, attrs); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void bind(String name, Object obj, Attributes attrs) throws NamingException { dirContext.bind(parseName(name), obj, attrs); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void rebind(Name name, Object obj, Attributes attrs) throws NamingException { dirContext.rebind(parseName(name), obj, attrs); cacheUnload(name.toString()); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public void rebind(String name, Object obj, Attributes attrs) throws NamingException { dirContext.rebind(parseName(name), obj, attrs); cacheUnload(name); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException { DirContext context = dirContext.createSubcontext(parseName(name), attrs); cacheUnload(name.toString()); return context; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { DirContext context = dirContext.createSubcontext(parseName(name), attrs); cacheUnload(name); return context; }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public DirContext getSchema(Name name) throws NamingException { return dirContext.getSchema(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public DirContext getSchema(String name) throws NamingException { return dirContext.getSchema(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public DirContext getSchemaClassDefinition(Name name) throws NamingException { return dirContext.getSchemaClassDefinition(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public DirContext getSchemaClassDefinition(String name) throws NamingException { return dirContext.getSchemaClassDefinition(parseName(name)); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { return dirContext.search(parseName(name), matchingAttributes, attributesToReturn); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { return dirContext.search(parseName(name), matchingAttributes, attributesToReturn); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes) throws NamingException { return dirContext.search(parseName(name), matchingAttributes); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { return dirContext.search(parseName(name), matchingAttributes); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(Name name, String filter, SearchControls cons) throws NamingException { return dirContext.search(parseName(name), filter, cons); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException { return dirContext.search(parseName(name), filter, cons); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { return dirContext.search(parseName(name), filterExpr, filterArgs, cons); }
// in java/org/apache/naming/resources/ProxyDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { return dirContext.search(parseName(name), filterExpr, filterArgs, cons); }
// in java/org/apache/naming/resources/ProxyDirContext.java
protected String parseName(String name) throws NamingException { return name; }
// in java/org/apache/naming/resources/ProxyDirContext.java
protected Name parseName(Name name) throws NamingException { return name; }
// in java/org/apache/naming/resources/VirtualDirContext.java
Override public Attributes getAttributes(String name) throws NamingException { NamingException initialException; try { // first try the normal processing, if it fails try with extra // resources Attributes attributes = super.getAttributes(name); return attributes; } catch (NamingException exc) { initialException = exc; } if (mappedResourcePaths != null) { for (Map.Entry<String, List<String>> mapping : mappedResourcePaths.entrySet()) { String path = mapping.getKey(); List<String> dirList = mapping.getValue(); String resourcesDir = dirList.get(0); if (name.equals(path)) { File f = new File(resourcesDir); if (f.exists() && f.canRead()) { return new FileResourceAttributes(f); } } path += "/"; if (name.startsWith(path)) { String res = name.substring(path.length()); File f = new File(resourcesDir + "/" + res); if (f.exists() && f.canRead()) { return new FileResourceAttributes(f); } } } } throw initialException; }
// in java/org/apache/naming/resources/RecyclableNamingEnumeration.java
Override public E next() throws NamingException { return nextElement(); }
// in java/org/apache/naming/resources/RecyclableNamingEnumeration.java
Override public boolean hasMore() throws NamingException { return enumeration.hasMoreElements(); }
// in java/org/apache/naming/resources/RecyclableNamingEnumeration.java
Override public void close() throws NamingException { // NO-OP }
// in java/org/apache/catalina/realm/JNDIRealm.java
public synchronized Principal authenticate(DirContext context, String username, String credentials) throws NamingException { if (username == null || username.equals("") || credentials == null || credentials.equals("")) { if (containerLog.isDebugEnabled()) containerLog.debug("username null or empty: returning null principal."); return (null); } if (userPatternArray != null) { for (int curUserPattern = 0; curUserPattern < userPatternFormatArray.length; curUserPattern++) { // Retrieve user information User user = getUser(context, username, credentials, curUserPattern); if (user != null) { try { // Check the user's credentials if (checkCredentials(context, user, credentials)) { // Search for additional roles List<String> roles = getRoles(context, user); if (containerLog.isDebugEnabled()) { Iterator<String> it = roles.iterator(); // TODO: Use a single log message while (it.hasNext()) { containerLog.debug("Found role: " + it.next()); } } return (new GenericPrincipal(username, credentials, roles)); } } catch (InvalidNameException ine) { // Log the problem for posterity containerLog.warn(sm.getString("jndiRealm.exception"), ine); // ignore; this is probably due to a name not fitting // the search path format exactly, as in a fully- // qualified name being munged into a search path // that already contains cn= or vice-versa } } } return null; } else { // Retrieve user information User user = getUser(context, username, credentials); if (user == null) return (null); // Check the user's credentials if (!checkCredentials(context, user, credentials)) return (null); // Search for additional roles List<String> roles = getRoles(context, user); if (containerLog.isDebugEnabled()) { Iterator<String> it = roles.iterator(); // TODO: Use a single log message while (it.hasNext()) { containerLog.debug("Found role: " + it.next()); } } // Create and return a suitable Principal for this user return (new GenericPrincipal(username, credentials, roles)); } }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected User getUser(DirContext context, String username) throws NamingException { return getUser(context, username, null, -1); }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected User getUser(DirContext context, String username, String credentials) throws NamingException { return getUser(context, username, credentials, -1); }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected User getUser(DirContext context, String username, String credentials, int curUserPattern) throws NamingException { User user = null; // Get attributes to retrieve from user entry ArrayList<String> list = new ArrayList<String>(); if (userPassword != null) list.add(userPassword); if (userRoleName != null) list.add(userRoleName); String[] attrIds = new String[list.size()]; list.toArray(attrIds); // Use pattern or search for user entry if (userPatternFormatArray != null && curUserPattern >= 0) { user = getUserByPattern(context, username, credentials, attrIds, curUserPattern); } else { user = getUserBySearch(context, username, attrIds); } return user; }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected User getUserByPattern(DirContext context, String username, String[] attrIds, String dn) throws NamingException { // If no attributes are requested, no need to look for them if (attrIds == null || attrIds.length == 0) { return new User(username, dn, null, null); } // Get required attributes from user entry Attributes attrs = null; try { attrs = context.getAttributes(dn, attrIds); } catch (NameNotFoundException e) { return (null); } if (attrs == null) return (null); // Retrieve value of userPassword String password = null; if (userPassword != null) password = getAttributeValue(userPassword, attrs); // Retrieve values of userRoleName attribute ArrayList<String> roles = null; if (userRoleName != null) roles = addAttributeValues(userRoleName, attrs, roles); return new User(username, dn, password, roles); }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected User getUserByPattern(DirContext context, String username, String credentials, String[] attrIds, int curUserPattern) throws NamingException { User user = null; if (username == null || userPatternFormatArray[curUserPattern] == null) return (null); // Form the dn from the user pattern String dn = userPatternFormatArray[curUserPattern].format(new String[] { username }); try { user = getUserByPattern(context, username, attrIds, dn); } catch (NameNotFoundException e) { return (null); } catch (NamingException e) { // If the getUserByPattern() call fails, try it again with the // credentials of the user that we're searching for try { userCredentialsAdd(context, dn, credentials); user = getUserByPattern(context, username, attrIds, dn); } finally { userCredentialsRemove(context); } } return user; }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected User getUserBySearch(DirContext context, String username, String[] attrIds) throws NamingException { if (username == null || userSearchFormat == null) return (null); // Form the search filter String filter = userSearchFormat.format(new String[] { username }); // Set up the search controls SearchControls constraints = new SearchControls(); if (userSubtree) { constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); } else { constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); } constraints.setCountLimit(sizeLimit); constraints.setTimeLimit(timeLimit); // Specify the attributes to be retrieved if (attrIds == null) attrIds = new String[0]; constraints.setReturningAttributes(attrIds); NamingEnumeration<SearchResult> results = context.search(userBase, filter, constraints); // Fail if no entries found try { if (results == null || !results.hasMore()) { return (null); } } catch (PartialResultException ex) { if (!adCompat) throw ex; else return (null); } // Get result for the first entry found SearchResult result = results.next(); // Check no further entries were found try { if (results.hasMore()) { if(containerLog.isInfoEnabled()) containerLog.info("username " + username + " has multiple entries"); return (null); } } catch (PartialResultException ex) { if (!adCompat) throw ex; } String dn = getDistinguishedName(context, userBase, result); if (containerLog.isTraceEnabled()) containerLog.trace(" entry found for " + username + " with dn " + dn); // Get the entry's attributes Attributes attrs = result.getAttributes(); if (attrs == null) return null; // Retrieve value of userPassword String password = null; if (userPassword != null) password = getAttributeValue(userPassword, attrs); // Retrieve values of userRoleName attribute ArrayList<String> roles = null; if (userRoleName != null) roles = addAttributeValues(userRoleName, attrs, roles); return new User(username, dn, password, roles); }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected boolean checkCredentials(DirContext context, User user, String credentials) throws NamingException { boolean validated = false; if (userPassword == null) { validated = bindAsUser(context, user, credentials); } else { validated = compareCredentials(context, user, credentials); } if (containerLog.isTraceEnabled()) { if (validated) { containerLog.trace(sm.getString("jndiRealm.authenticateSuccess", user.getUserName())); } else { containerLog.trace(sm.getString("jndiRealm.authenticateFailure", user.getUserName())); } } return (validated); }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected boolean compareCredentials(DirContext context, User info, String credentials) throws NamingException { if (info == null || credentials == null) return (false); String password = info.getPassword(); if (password == null) return (false); // Validate the credentials specified by the user if (containerLog.isTraceEnabled()) containerLog.trace(" validating credentials"); boolean validated = false; if (hasMessageDigest()) { // Some directories prefix the password with the hash type // The string is in a format compatible with Base64.encode not // the Hex encoding of the parent class. if (password.startsWith("{MD5}") || password.startsWith("{SHA}")) { /* sync since super.digest() does this same thing */ synchronized (this) { password = password.substring(5); md.reset(); md.update(credentials.getBytes(B2CConverter.ISO_8859_1)); String digestedPassword = Base64.encode(md.digest()); validated = password.equals(digestedPassword); } } else if (password.startsWith("{SSHA}")) { // Bugzilla 32938 /* sync since super.digest() does this same thing */ synchronized (this) { password = password.substring(6); md.reset(); md.update(credentials.getBytes(B2CConverter.ISO_8859_1)); // Decode stored password. ByteChunk pwbc = new ByteChunk(password.length()); try { pwbc.append(password.getBytes(B2CConverter.ISO_8859_1), 0, password.length()); } catch (IOException e) { // Should never happen containerLog.error("Could not append password bytes to chunk: ", e); } CharChunk decoded = new CharChunk(); Base64.decode(pwbc, decoded); char[] pwarray = decoded.getBuffer(); // Split decoded password into hash and salt. final int saltpos = 20; byte[] hash = new byte[saltpos]; for (int i=0; i< hash.length; i++) { hash[i] = (byte) pwarray[i]; } byte[] salt = new byte[pwarray.length - saltpos]; for (int i=0; i< salt.length; i++) salt[i] = (byte)pwarray[i+saltpos]; md.update(salt); byte[] dp = md.digest(); validated = Arrays.equals(dp, hash); } // End synchronized(this) block } else { // Hex hashes should be compared case-insensitive validated = (digest(credentials).equalsIgnoreCase(password)); } } else validated = (digest(credentials).equals(password)); return (validated); }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected boolean bindAsUser(DirContext context, User user, String credentials) throws NamingException { if (credentials == null || user == null) return (false); String dn = user.getDN(); if (dn == null) return (false); // Validate the credentials specified by the user if (containerLog.isTraceEnabled()) { containerLog.trace(" validating credentials by binding as the user"); } userCredentialsAdd(context, dn, credentials); // Elicit an LDAP bind operation boolean validated = false; try { if (containerLog.isTraceEnabled()) { containerLog.trace(" binding as " + dn); } context.getAttributes("", null); validated = true; } catch (AuthenticationException e) { if (containerLog.isTraceEnabled()) { containerLog.trace(" bind attempt failed"); } } userCredentialsRemove(context); return (validated); }
// in java/org/apache/catalina/realm/JNDIRealm.java
private void userCredentialsAdd(DirContext context, String dn, String credentials) throws NamingException { // Set up security environment to bind as the user context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn); context.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
private void userCredentialsRemove(DirContext context) throws NamingException { // Restore the original security environment if (connectionName != null) { context.addToEnvironment(Context.SECURITY_PRINCIPAL, connectionName); } else { context.removeFromEnvironment(Context.SECURITY_PRINCIPAL); } if (connectionPassword != null) { context.addToEnvironment(Context.SECURITY_CREDENTIALS, connectionPassword); } else { context.removeFromEnvironment(Context.SECURITY_CREDENTIALS); } }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected List<String> getRoles(DirContext context, User user) throws NamingException { if (user == null) return (null); String dn = user.getDN(); String username = user.getUserName(); if (dn == null || username == null) return (null); if (containerLog.isTraceEnabled()) containerLog.trace(" getRoles(" + dn + ")"); // Start with roles retrieved from the user entry List<String> list = new ArrayList<String>(); List<String> userRoles = user.getRoles(); if (userRoles != null) { list.addAll(userRoles); } if (commonRole != null) list.add(commonRole); if (containerLog.isTraceEnabled()) { containerLog.trace(" Found " + list.size() + " user internal roles"); for (int i=0; i<list.size(); i++) containerLog.trace( " Found user internal role " + list.get(i)); } // Are we configured to do role searches? if ((roleFormat == null) || (roleName == null)) return (list); // Set up parameters for an appropriate search String filter = roleFormat.format(new String[] { doRFC2254Encoding(dn), username }); SearchControls controls = new SearchControls(); if (roleSubtree) controls.setSearchScope(SearchControls.SUBTREE_SCOPE); else controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); controls.setReturningAttributes(new String[] {roleName}); String base = null; if (roleBaseFormat != null) { NameParser np = context.getNameParser(""); Name name = np.parse(dn); String nameParts[] = new String[name.size()]; for (int i = 0; i < name.size(); i++) { nameParts[i] = name.get(i); } base = roleBaseFormat.format(nameParts); } // Perform the configured search and process the results NamingEnumeration<SearchResult> results = null; try { if (roleSearchAsUser) { userCredentialsAdd(context, dn, user.getPassword()); } results = context.search(base, filter, controls); } finally { if (roleSearchAsUser) { userCredentialsRemove(context); } } if (results == null) return (list); // Should never happen, but just in case ... HashMap<String, String> groupMap = new HashMap<String, String>(); try { while (results.hasMore()) { SearchResult result = results.next(); Attributes attrs = result.getAttributes(); if (attrs == null) continue; String dname = getDistinguishedName(context, roleBase, result); String name = getAttributeValue(roleName, attrs); if (name != null && dname != null) { groupMap.put(dname, name); } } } catch (PartialResultException ex) { if (!adCompat) throw ex; } Set<String> keys = groupMap.keySet(); if (containerLog.isTraceEnabled()) { containerLog.trace(" Found " + keys.size() + " direct roles"); for (String key: keys) { containerLog.trace( " Found direct role " + key + " -> " + groupMap.get(key)); } } // if nested group search is enabled, perform searches for nested groups until no new group is found if (getRoleNested()) { // The following efficient algorithm is known as memberOf Algorithm, as described in "Practices in // Directory Groups". It avoids group slurping and handles cyclic group memberships as well. // See http://middleware.internet2.edu/dir/ for details Map<String, String> newGroups = new HashMap<String,String>(groupMap); while (!newGroups.isEmpty()) { Map<String, String> newThisRound = new HashMap<String, String>(); // Stores the groups we find in this iteration for (Entry<String, String> group : newGroups.entrySet()) { filter = roleFormat.format(new String[] { group.getKey(), group.getValue() }); if (containerLog.isTraceEnabled()) { containerLog.trace("Perform a nested group search with base "+ roleBase + " and filter " + filter); } results = context.search(roleBase, filter, controls); try { while (results.hasMore()) { SearchResult result = results.next(); Attributes attrs = result.getAttributes(); if (attrs == null) continue; String dname = getDistinguishedName(context, roleBase, result); String name = getAttributeValue(roleName, attrs); if (name != null && dname != null && !groupMap.keySet().contains(dname)) { groupMap.put(dname, name); newThisRound.put(dname, name); if (containerLog.isTraceEnabled()) { containerLog.trace(" Found nested role " + dname + " -> " + name); } } } } catch (PartialResultException ex) { if (!adCompat) throw ex; } } newGroups = newThisRound; } } list.addAll(groupMap.values()); return list; }
// in java/org/apache/catalina/realm/JNDIRealm.java
private String getAttributeValue(String attrId, Attributes attrs) throws NamingException { if (containerLog.isTraceEnabled()) containerLog.trace(" retrieving attribute " + attrId); if (attrId == null || attrs == null) return null; Attribute attr = attrs.get(attrId); if (attr == null) return (null); Object value = attr.get(); if (value == null) return (null); String valueString = null; if (value instanceof byte[]) valueString = new String((byte[]) value); else valueString = value.toString(); return valueString; }
// in java/org/apache/catalina/realm/JNDIRealm.java
private ArrayList<String> addAttributeValues(String attrId, Attributes attrs, ArrayList<String> values) throws NamingException{ if (containerLog.isTraceEnabled()) containerLog.trace(" retrieving values for attribute " + attrId); if (attrId == null || attrs == null) return values; if (values == null) values = new ArrayList<String>(); Attribute attr = attrs.get(attrId); if (attr == null) return (values); NamingEnumeration<?> e = attr.getAll(); try { while(e.hasMore()) { String value = (String)e.next(); values.add(value); } } catch (PartialResultException ex) { if (!adCompat) throw ex; } return values; }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected synchronized Principal getPrincipal(DirContext context, String username, GSSCredential gssCredential) throws NamingException { User user = null; List<String> roles = null; try { if (gssCredential != null && isUseDelegatedCredential()) { // Set up context context.addToEnvironment( Context.SECURITY_AUTHENTICATION, "GSSAPI"); context.addToEnvironment( "javax.security.sasl.server.authentication", "true"); context.addToEnvironment( "javax.security.sasl.qop", "auth-conf"); // Note: Subject already set in SPNEGO authenticator so no need // for Subject.doAs() here } user = getUser(context, username); if (user != null) { roles = getRoles(context, user); } } finally { try { context.removeFromEnvironment( Context.SECURITY_AUTHENTICATION); } catch (NamingException e) { // Ignore } try { context.removeFromEnvironment( "javax.security.sasl.server.authentication"); } catch (NamingException e) { // Ignore } try { context.removeFromEnvironment( "javax.security.sasl.qop"); } catch (NamingException e) { // Ignore } } if (user != null) { return new GenericPrincipal(user.getUserName(), user.getPassword(), roles, null, null, gssCredential); } return null; }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected DirContext open() throws NamingException { // Do nothing if there is a directory server connection already open if (context != null) return (context); try { // Ensure that we have a directory context available context = new InitialDirContext(getDirectoryContextEnvironment()); } catch (Exception e) { connectionAttempt = 1; // log the first exception. containerLog.warn(sm.getString("jndiRealm.exception"), e); // Try connecting to the alternate url. context = new InitialDirContext(getDirectoryContextEnvironment()); } finally { // reset it in case the connection times out. // the primary may come back. connectionAttempt = 0; } return (context); }
// in java/org/apache/catalina/realm/JNDIRealm.java
protected String getDistinguishedName(DirContext context, String base, SearchResult result) throws NamingException { // Get the entry's distinguished name. For relative results, this means // we need to composite a name with the base name, the context name, and // the result name. For non-relative names, use the returned name. if (result.isRelative()) { if (containerLog.isTraceEnabled()) { containerLog.trace(" search returned relative name: " + result.getName()); } NameParser parser = context.getNameParser(""); Name contextName = parser.parse(context.getNameInNamespace()); Name baseName = parser.parse(base); // Bugzilla 32269 Name entryName = parser.parse(new CompositeName(result.getName()).get(0)); Name name = contextName.addAll(baseName); name = name.addAll(entryName); return name.toString(); } else { String absoluteName = result.getName(); if (containerLog.isTraceEnabled()) containerLog.trace(" search returned absolute name: " + result.getName()); try { // Normalize the name by running it through the name parser. NameParser parser = context.getNameParser(""); URI userNameUri = new URI(absoluteName); String pathComponent = userNameUri.getPath(); // Should not ever have an empty path component, since that is /{DN} if (pathComponent.length() < 1 ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); } Name name = parser.parse(pathComponent.substring(1)); return name.toString(); } catch ( URISyntaxException e ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); } } }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
protected void createMBeans(String prefix, Context context) throws NamingException { if (log.isDebugEnabled()) { log.debug("Creating MBeans for Global JNDI Resources in Context '" + prefix + "'"); } try { NamingEnumeration<Binding> bindings = context.listBindings(""); while (bindings.hasMore()) { Binding binding = bindings.next(); String name = prefix + binding.getName(); Object value = context.lookup(binding.getName()); if (log.isDebugEnabled()) { log.debug("Checking resource " + name); } if (value instanceof Context) { createMBeans(name + "/", (Context) value); } else if (value instanceof UserDatabase) { try { createMBeans(name, (UserDatabase) value); } catch (Exception e) { log.error("Exception creating UserDatabase MBeans for " + name, e); } } } } catch( RuntimeException ex) { log.error("RuntimeException " + ex); } catch( OperationNotSupportedException ex) { log.error("Operation not supported " + ex); } }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
Filter getFilter() throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { // Return the existing filter instance, if any if (this.filter != null) return (this.filter); // Identify the class loader we will be using String filterClass = filterDef.getFilterClass(); this.filter = (Filter) getInstanceManager().newInstance(filterClass); initFilter(); return (this.filter); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
void setFilterDef(FilterDef filterDef) throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { this.filterDef = filterDef; if (filterDef == null) { // Release any previously allocated filter instance if (this.filter != null){ if (Globals.IS_SECURITY_ENABLED) { try{ SecurityUtil.doAsPrivilege("destroy", filter); } catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); } SecurityUtil.remove(filter); } else { filter.destroy(); } if (!context.getIgnoreAnnotations()) { try { ((StandardContext) context).getInstanceManager().destroyInstance(this.filter); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); } } } this.filter = null; } else { // Allocate a new filter instance if necessary if (filterDef.getFilter() == null) { getFilter(); } } }
// in java/org/apache/catalina/core/ApplicationContext.java
private static void listCollectionPaths(Set<String> set, DirContext resources, String path) throws NamingException { Enumeration<Binding> childPaths = resources.listBindings(path); while (childPaths.hasMoreElements()) { Binding binding = childPaths.nextElement(); String name = binding.getName(); StringBuilder childPath = new StringBuilder(path); if (!"/".equals(path) && !path.endsWith("/")) childPath.append("/"); childPath.append(name); Object object = binding.getObject(); if (object instanceof DirContext) { childPath.append("/"); } set.add(childPath.toString()); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { Class<?> clazz = loadClassMaybePrivileged(className, classLoader); return newInstance(clazz.newInstance(), clazz); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public Object newInstance(final String className, final ClassLoader classLoader) throws IllegalAccessException, NamingException, InvocationTargetException, InstantiationException, ClassNotFoundException { Class<?> clazz = classLoader.loadClass(className); return newInstance(clazz.newInstance(), clazz); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
Override public void newInstance(Object o) throws IllegalAccessException, InvocationTargetException, NamingException { newInstance(o, o.getClass()); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
private Object newInstance(Object instance, Class<?> clazz) throws IllegalAccessException, InvocationTargetException, NamingException { if (!ignoreAnnotations) { Map<String, String> injections = injectionMap.get(clazz.getName()); populateAnnotationsCache(clazz, injections); processAnnotations(instance, injections); postConstruct(instance, clazz); } return instance; }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected void populateAnnotationsCache(Class<?> clazz, Map<String, String> injections) throws IllegalAccessException, InvocationTargetException, NamingException { List<AnnotationCacheEntry> annotations = null; while (clazz != null) { AnnotationCacheEntry[] annotationsArray = null; synchronized (annotationCache) { annotationsArray = annotationCache.get(clazz); } if (annotationsArray == null) { if (annotations == null) { annotations = new ArrayList<AnnotationCacheEntry>(); } else { annotations.clear(); } if (context != null) { // Initialize fields annotations for resource injection if // JNDI is enabled Field[] fields = null; if (Globals.IS_SECURITY_ENABLED) { final Class<?> clazz2 = clazz; fields = AccessController.doPrivileged( new PrivilegedAction<Field[]>(){ @Override public Field[] run(){ return clazz2.getDeclaredFields(); } }); } else { fields = clazz.getDeclaredFields(); } for (Field field : fields) { if (injections != null && injections.containsKey(field.getName())) { annotations.add(new AnnotationCacheEntry( field.getName(), null, injections.get(field.getName()), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(Resource.class)) { Resource annotation = field.getAnnotation(Resource.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(EJB.class)) { EJB annotation = field.getAnnotation(EJB.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(WebServiceRef.class)) { WebServiceRef annotation = field.getAnnotation(WebServiceRef.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(PersistenceContext.class)) { PersistenceContext annotation = field.getAnnotation(PersistenceContext.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(PersistenceUnit.class)) { PersistenceUnit annotation = field.getAnnotation(PersistenceUnit.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } } } // Initialize methods annotations Method[] methods = null; if (Globals.IS_SECURITY_ENABLED) { final Class<?> clazz2 = clazz; methods = AccessController.doPrivileged( new PrivilegedAction<Method[]>(){ @Override public Method[] run(){ return clazz2.getDeclaredMethods(); } }); } else { methods = clazz.getDeclaredMethods(); } Method postConstruct = null; Method preDestroy = null; for (Method method : methods) { String methodName = method.getName(); if (context != null) { // Resource injection only if JNDI is enabled if (injections != null && methodName.startsWith("set") && methodName.length() > 3) { String fieldName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); if (injections.containsKey(fieldName)) { annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), injections.get(method.getName()), AnnotationCacheEntryType.SETTER)); break; } } if (method.isAnnotationPresent(Resource.class)) { Resource annotation = method.getAnnotation(Resource.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(EJB.class)) { EJB annotation = method.getAnnotation(EJB.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(WebServiceRef.class)) { WebServiceRef annotation = method.getAnnotation(WebServiceRef.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(PersistenceContext.class)) { PersistenceContext annotation = method.getAnnotation(PersistenceContext.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(PersistenceUnit.class)) { PersistenceUnit annotation = method.getAnnotation(PersistenceUnit.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } } if (method.isAnnotationPresent(PostConstruct.class)) { if ((postConstruct != null) || (method.getParameterTypes().length != 0) || (Modifier.isStatic(method.getModifiers())) || (method.getExceptionTypes().length > 0) || (!method.getReturnType().getName().equals("void"))) { throw new IllegalArgumentException( "Invalid PostConstruct annotation"); } postConstruct = method; } if (method.isAnnotationPresent(PreDestroy.class)) { if ((preDestroy != null || method.getParameterTypes().length != 0) || (Modifier.isStatic(method.getModifiers())) || (method.getExceptionTypes().length > 0) || (!method.getReturnType().getName().equals("void"))) { throw new IllegalArgumentException( "Invalid PreDestroy annotation"); } preDestroy = method; } } if (postConstruct != null) { annotations.add(new AnnotationCacheEntry( postConstruct.getName(), postConstruct.getParameterTypes(), null, AnnotationCacheEntryType.POST_CONSTRUCT)); } if (preDestroy != null) { annotations.add(new AnnotationCacheEntry( preDestroy.getName(), preDestroy.getParameterTypes(), null, AnnotationCacheEntryType.PRE_DESTROY)); } if (annotations.isEmpty()) { // Use common object to save memory annotationsArray = ANNOTATIONS_EMPTY; } else { annotationsArray = annotations.toArray( new AnnotationCacheEntry[annotations.size()]); } synchronized (annotationCache) { annotationCache.put(clazz, annotationsArray); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected void processAnnotations(Object instance, Map<String, String> injections) throws IllegalAccessException, InvocationTargetException, NamingException { if (context == null) { // No resource injection return; } Class<?> clazz = instance.getClass(); while (clazz != null) { AnnotationCacheEntry[] annotations; synchronized (annotationCache) { annotations = annotationCache.get(clazz); } for (AnnotationCacheEntry entry : annotations) { if (entry.getType() == AnnotationCacheEntryType.SETTER) { lookupMethodResource(context, instance, getMethod(clazz, entry), entry.getName(), clazz); } else if (entry.getType() == AnnotationCacheEntryType.FIELD) { lookupFieldResource(context, instance, getField(clazz, entry), entry.getName(), clazz); } } clazz = clazz.getSuperclass(); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected static void lookupFieldResource(Context context, Object instance, Field field, String name, Class<?> clazz) throws NamingException, IllegalAccessException { Object lookedupResource; boolean accessibility; String normalizedName = normalize(name); if ((normalizedName != null) && (normalizedName.length() > 0)) { lookedupResource = context.lookup(normalizedName); } else { lookedupResource = context.lookup(clazz.getName() + "/" + field.getName()); } synchronized (field) { accessibility = field.isAccessible(); field.setAccessible(true); field.set(instance, lookedupResource); field.setAccessible(accessibility); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected static void lookupMethodResource(Context context, Object instance, Method method, String name, Class<?> clazz) throws NamingException, IllegalAccessException, InvocationTargetException { if (!method.getName().startsWith("set") || method.getName().length() < 4 || method.getParameterTypes().length != 1 || !method.getReturnType().getName().equals("void")) { throw new IllegalArgumentException("Invalid method resource injection annotation"); } Object lookedupResource; boolean accessibility; String normalizedName = normalize(name); if ((normalizedName != null) && (normalizedName.length() > 0)) { lookedupResource = context.lookup(normalizedName); } else { lookedupResource = context.lookup( clazz.getName() + "/" + getName(method)); } synchronized (method) { accessibility = method.isAccessible(); method.setAccessible(true); method.invoke(instance, lookedupResource); method.setAccessible(accessibility); } }
// in java/org/apache/catalina/core/NamingContextListener.java
private void createNamingContext() throws NamingException { // Creating the comp subcontext if (container instanceof Server) { compCtx = namingContext; envCtx = namingContext; } else { compCtx = namingContext.createSubcontext("comp"); envCtx = compCtx.createSubcontext("env"); } int i; if (log.isDebugEnabled()) log.debug("Creating JNDI naming context"); if (namingResources == null) { namingResources = new NamingResources(); namingResources.setContainer(container); } // Resource links ContextResourceLink[] resourceLinks = namingResources.findResourceLinks(); for (i = 0; i < resourceLinks.length; i++) { addResourceLink(resourceLinks[i]); } // Resources ContextResource[] resources = namingResources.findResources(); for (i = 0; i < resources.length; i++) { addResource(resources[i]); } // Resources Env ContextResourceEnvRef[] resourceEnvRefs = namingResources.findResourceEnvRefs(); for (i = 0; i < resourceEnvRefs.length; i++) { addResourceEnvRef(resourceEnvRefs[i]); } // Environment entries ContextEnvironment[] contextEnvironments = namingResources.findEnvironments(); for (i = 0; i < contextEnvironments.length; i++) { addEnvironment(contextEnvironments[i]); } // EJB references ContextEjb[] ejbs = namingResources.findEjbs(); for (i = 0; i < ejbs.length; i++) { addEjb(ejbs[i]); } // WebServices references ContextService[] services = namingResources.findServices(); for (i = 0; i < services.length; i++) { addService(services[i]); } // Binding a User Transaction reference if (container instanceof Context) { try { Reference ref = new TransactionRef(); compCtx.bind("UserTransaction", ref); ContextTransaction transaction = namingResources.getTransaction(); if (transaction != null) { Iterator<String> params = transaction.listProperties(); while (params.hasNext()) { String paramName = params.next(); String paramValue = (String) transaction.getProperty(paramName); StringRefAddr refAddr = new StringRefAddr(paramName, paramValue); ref.add(refAddr); } } } catch (NameAlreadyBoundException e) { // Ignore because UserTransaction was obviously // added via ResourceLink } catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); } } // Binding the resources directory context if (container instanceof Context) { try { compCtx.bind("Resources", ((Container) container).getResources()); } catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); } } }
// in java/org/apache/catalina/core/NamingContextListener.java
private void createSubcontexts(javax.naming.Context ctx, String name) throws NamingException { javax.naming.Context currentContext = ctx; StringTokenizer tokenizer = new StringTokenizer(name, "/"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if ((!token.equals("")) && (tokenizer.hasMoreTokens())) { try { currentContext = currentContext.createSubcontext(token); } catch (NamingException e) { // Silent catch. Probably an object is already bound in // the context. currentContext = (javax.naming.Context) currentContext.lookup(token); } } } }
112
            
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (NamingException e) { throw new RuntimeException(e.getMessage(), e); }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (NamingException e) { throw e; }
// in java/org/apache/naming/NamingContext.java
catch (NamingException e) { throw e; }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException e) { // Object not found }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException ne) { // Shouldn't happen }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException ne) { // Shouldn't happen }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException e) { // Ignore }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException e) { // Unexpected exception throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); }
// in java/org/apache/naming/resources/BaseDirContext.java
catch ( NamingException ex) { // ignore }
// in java/org/apache/naming/resources/BaseDirContext.java
catch (NamingException ne) { // Ignore }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (NamingException e) { entry.exists = false; }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (NamingException e) { return false; }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (NamingException e) { exists = false; }
// in java/org/apache/naming/resources/ProxyDirContext.java
catch (NamingException e) { exists = false; }
// in java/org/apache/naming/resources/VirtualDirContext.java
catch (NamingException exc) { initialException = exc; }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { // No value for the attribute }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NamingException e) { return null; }
// in java/org/apache/tomcat/util/http/mapper/Mapper.java
catch(NamingException nex) { // Swallow not found, since this is normal }
// in java/org/apache/tomcat/util/http/mapper/Mapper.java
catch(NamingException nex) { // Swallow, since someone else handles the 404 }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (NamingException e) { log.error(sm.getString( "contextConfig.webinfClassesUrl", "/WEB-INF/classes"), e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (NamingException e) { //not found, ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NamingException e) { log.error(" Resource '" + paths[i] + "' is missing"); return (true); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NamingException e) { if (log.isDebugEnabled()) log.debug(" Failed tracking modifications of '" + getJarPath() + "'"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/loader/WebappLoader.java
catch(NamingException e) { // Silent catch: it's valid that no /WEB-INF/classes collection // exists }
// in java/org/apache/catalina/loader/WebappLoader.java
catch(NamingException e) { // Silent catch: it's valid that no /WEB-INF/lib collection // exists }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", libPath)); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", filename)); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { return false; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Log the problem for posterity containerLog.error(sm.getString("jndiRealm.exception"), e); // Close the connection so that it gets reopened next time if (context != null) close(context); // Return "not authenticated" for this request if (containerLog.isDebugEnabled()) containerLog.debug("Returning null principal."); return (null); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // If the getUserByPattern() call fails, try it again with the // credentials of the user that we're searching for try { userCredentialsAdd(context, dn, credentials); user = getUserByPattern(context, username, attrIds, dn); } finally { userCredentialsRemove(context); } }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { containerLog.error(sm.getString("jndiRealm.close"), e); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Log the problem for posterity containerLog.error(sm.getString("jndiRealm.exception"), e); // Close the connection so that it gets reopened next time if (context != null) close(context); // Return "not authenticated" for this request return (null); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { throw new LifecycleException(sm.getString("jndiRealm.open"), e); }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
catch (NamingException e) { log.error("No global naming context defined for server"); return; }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
catch (NamingException e) { log.error("Exception processing Global JNDI Resources", e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (NamingException e) { manager.getContainer().getLogger().error( sm.getString(getStoreName() + ".wrongDataSource", this.dataSourceName), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (NamingException e) { log.warn(sm.getString("namingResources.cleanupNoContext", container), e); return; }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (NamingException e) { log.warn(sm.getString( "namingResources.cleanupNoResource", cr.getName(), container), e); continue; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Failed throw new ServletException("No resources", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch(NamingException e) { result = false; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { result = false; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { if (debug > 10) log("readme '" + readmeFile + "' not found", e); return null; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { if (debug > 10) log("localXsltFile '" + localXsltFile + "' not found", e); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { continue; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { resp.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { result = false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put (dest, new Integer(WebdavStatus.SC_CONFLICT)); return false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put (dest, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR)); return false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { if (e.getCause() instanceof FileNotFoundException) { // We know the source exists so it must be the // destination dir that can't be found errorList.put(source, new Integer(WebdavStatus.SC_CONFLICT)); } else { errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR)); } return false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); return false; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put(path, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put(path, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); return; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { if (!(object instanceof DirContext)) { // If it's not a collection, then it's an unknown // error errorList.put (childName, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { errorList.put (childName, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NamingException e) { exists = false; }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { // Ignore }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { return (null); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (NamingException e) { ServletException se = new ServletException(e); throw se; }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { // Never happens }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error (sm.getString("naming.namingContextCreationFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.bindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { logger.error(sm.getString("naming.unbindFailed", e)); }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NamingException e) { // Silent catch. Probably an object is already bound in // the context. currentContext = (javax.naming.Context) currentContext.lookup(token); }
// in java/org/apache/catalina/core/StandardContext.java
catch (NamingException e) { // Doesn't exist - ignore and carry on }
// in java/org/apache/catalina/core/StandardContext.java
catch (NamingException e) { // Silent catch, as this is a normal case during the early // startup stages }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (NamingException nex) { // Application does not contain a MANIFEST.MF file }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (NamingException nex) { // Jump out of the check for this application because it // has no resources }
15
            
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (NamingException e) { throw new RuntimeException(e.getMessage(), e); }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (NamingException e) { throw e; }
// in java/org/apache/naming/NamingContext.java
catch (NamingException e) { throw e; }
// in java/org/apache/naming/resources/DirContextURLConnection.java
catch (NamingException e) { // Unexpected exception throw new FileNotFoundException( getURL() == null ? "null" : getURL().toString()); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", libPath)); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NamingException e) { IOException ioe = new IOException(sm.getString( "webappLoader.namingFailure", filename)); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NamingException e) { throw new LifecycleException(sm.getString("jndiRealm.open"), e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Failed throw new ServletException("No resources", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (NamingException e) { ServletException se = new ServletException(e); throw se; }
2
unknown (Lib) NoClassDefFoundError 0 0 0 3
            
// in java/org/apache/jasper/JspCompilationContext.java
catch (NoClassDefFoundError e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.error.compiler"), e); } }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (NoClassDefFoundError e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); return null; }
// in java/org/apache/catalina/startup/WebAnnotationSet.java
catch (NoClassDefFoundError e) { // We do nothing }
0 0
unknown (Lib) NoSuchAlgorithmException 0 0 0 9
            
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (NoSuchAlgorithmException e) { throw new IOException(e); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (NoSuchAlgorithmException e) { // Assume no RFC 5746 support }
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { throw new LifecycleException (sm.getString("realmBase.algorithm", digest), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { log.error("Couldn't get MD5 digest: ", e); throw new IllegalStateException(e.getMessage()); }
// in java/org/apache/catalina/websocket/WebSocketServlet.java
catch (NoSuchAlgorithmException e) { throw new ServletException(e); }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new IllegalStateException(); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NoSuchAlgorithmException e) { throw new UnavailableException("No MD5"); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (NoSuchAlgorithmException e) { log.error(sm.getString("sessionIdGenerator.randomAlgorithm", secureRandomAlgorithm), e); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (NoSuchAlgorithmException e) { log.error(sm.getString("sessionIdGenerator.randomAlgorithm", secureRandomAlgorithm), e); }
6
            
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (NoSuchAlgorithmException e) { throw new IOException(e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { throw new LifecycleException (sm.getString("realmBase.algorithm", digest), e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (NoSuchAlgorithmException e) { log.error("Couldn't get MD5 digest: ", e); throw new IllegalStateException(e.getMessage()); }
// in java/org/apache/catalina/websocket/WebSocketServlet.java
catch (NoSuchAlgorithmException e) { throw new ServletException(e); }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new IllegalStateException(); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NoSuchAlgorithmException e) { throw new UnavailableException("No MD5"); }
2
unknown (Lib) NoSuchElementException 3
            
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
Override public FileItemStream next() throws FileUploadException, IOException { if (eof || (!itemValid && !hasNext())) { throw new NoSuchElementException(); } itemValid = false; return currentItem; }
// in java/org/apache/catalina/core/ApplicationHttpRequest.java
Override public String nextElement() { if (pos != last) { for (int i = pos + 1; i <= last; i++) { if (getAttribute(specials[i]) != null) { pos = i; return (specials[i]); } } } String result = next; if (next != null) { next = findNext(); } else { throw new NoSuchElementException(); } return result; }
// in java/javax/el/CompositeELResolver.java
Override public FeatureDescriptor next() { if (!hasNext()) throw new NoSuchElementException(); FeatureDescriptor result = this.next; this.next = null; return result; }
0 0 8
            
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
catch (NoSuchElementException x ) { try { synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 s = Selector.open(); } } catch (IOException iox) { } }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "expiresFilter.startingPointNotFound", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException( sm.getString( "Duration unit not found after amount {} in directive '{}'", Integer.valueOf(amount), line)); }
// in java/org/apache/catalina/tribes/transport/RxTaskPool.java
catch (java.util.NoSuchElementException x) { //this means that there are no available workers worker = null; }
// in java/org/apache/catalina/ha/session/DeltaRequest.java
catch (java.util.NoSuchElementException x) { //do nothing, we wanted to remove it anyway }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (NoSuchElementException nse) { // Application does not contain a MANIFEST.MF file }
4
            
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "expiresFilter.startingPointNotFound", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException(sm.getString( "Duration not found in directive '{}'", line)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NoSuchElementException e) { throw new IllegalStateException( sm.getString( "Duration unit not found after amount {} in directive '{}'", Integer.valueOf(amount), line)); }
4
unknown (Lib) NoSuchFieldException 0 0 1
            
// in java/org/apache/catalina/loader/WebappClassLoader.java
private void checkThreadLocalMapForLeaks(Object map, Field internalTableField) throws IllegalAccessException, NoSuchFieldException { if (map != null) { Object[] table = (Object[]) internalTableField.get(map); if (table != null) { for (int j =0; j < table.length; j++) { if (table[j] != null) { boolean potentialLeak = false; // Check the key Object key = ((Reference<?>) table[j]).get(); if (this.equals(key) || loadedByThisOrChild(key)) { potentialLeak = true; } // Check the value Field valueField = table[j].getClass().getDeclaredField("value"); valueField.setAccessible(true); Object value = valueField.get(table[j]); if (this.equals(value) || loadedByThisOrChild(value)) { potentialLeak = true; } if (potentialLeak) { Object[] args = new Object[5]; args[0] = contextName; if (key != null) { args[1] = getPrettyClassName(key.getClass()); try { args[2] = key.toString(); } catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badKey", args[1]), e); args[2] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); } } if (value != null) { args[3] = getPrettyClassName(value.getClass()); try { args[4] = value.toString(); } catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badValue", args[3]), e); args[4] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); } } if (value == null) { if (log.isDebugEnabled()) { log.debug(sm.getString( "webappClassLoader.checkThreadLocalsForLeaksDebug", args)); } } else { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks", args)); } } } } } } }
8
            
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException nfe){ targetField = thread.getClass().getDeclaredField("runnable"); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException nfe){ Method cancelMethod = thread.getClass().getDeclaredMethod("cancel"); if (null != cancelMethod){ synchronized(thread) { cancelMethod.setAccessible(true); cancelMethod.invoke(thread); } } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchFieldException e) { if (System.getProperty("java.vendor").startsWith("Sun")) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } else { log.debug(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (NoSuchFieldException e) { // Should never happen. On that basis don't log // it. }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (NoSuchFieldException e) { // Should never happen. On that basis don't log it. }
0 0
unknown (Lib) NoSuchMethodException 1
            
// in java/org/apache/tomcat/util/IntrospectionUtils.java
public static Object callMethod1(Object target, String methodN, Object param1, String typeParam1, ClassLoader cl) throws Exception { if (target == null || param1 == null) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Assert: Illegal params " + target + " " + param1); } if (log.isDebugEnabled()) log.debug("IntrospectionUtils: callMethod1 " + target.getClass().getName() + " " + param1.getClass().getName() + " " + typeParam1); Class<?> params[] = new Class[1]; if (typeParam1 == null) params[0] = param1.getClass(); else params[0] = cl.loadClass(typeParam1); Method m = findMethod(target.getClass(), methodN, params); if (m == null) throw new NoSuchMethodException(target.getClass().getName() + " " + methodN); try { return m.invoke(target, new Object[] { param1 }); } catch (InvocationTargetException ie) { ExceptionUtils.handleThrowable(ie.getCause()); throw ie; } }
0 2
            
// in java/org/apache/catalina/core/AprLifecycleListener.java
private static void terminateAPR() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { String methodName = "terminate"; Method method = Class.forName("org.apache.tomcat.jni.Library") .getMethod(methodName, (Class [])null); method.invoke(null, (Object []) null); aprAvailable = false; aprInitialized = false; sslInitialized = false; // Well we cleaned the pool in terminate. sslAvailable = false; // Well we cleaned the pool in terminate. fipsModeActive = false; }
// in java/org/apache/catalina/core/AprLifecycleListener.java
private static void initializeSSL() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { if ("off".equalsIgnoreCase(SSLEngine)) { return; } if (sslInitialized) { //only once per VM return; } sslInitialized = true; String methodName = "randSet"; Class<?> paramTypes[] = new Class[1]; paramTypes[0] = String.class; Object paramValues[] = new Object[1]; paramValues[0] = SSLRandomSeed; Class<?> clazz = Class.forName("org.apache.tomcat.jni.SSL"); Method method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); methodName = "initialize"; paramValues[0] = "on".equalsIgnoreCase(SSLEngine)?null:SSLEngine; method = clazz.getMethod(methodName, paramTypes); method.invoke(null, paramValues); if("on".equalsIgnoreCase(FIPSMode)) { log.info(sm.getString("aprListener.initializingFIPS")); int result = SSL.fipsModeSet(1); // success is defined as return value = 1 if(1 == result) { fipsModeActive = true; log.info(sm.getString("aprListener.initializeFIPSSuccess")); } else { // This case should be handled by the native method, // but we'll make absolutely sure, here. String message = sm.getString("aprListener.initializeFIPSFailed"); log.error(message); throw new IllegalStateException(message); } } log.info(sm.getString("aprListener.initializedOpenSSL", SSL.versionString())); sslAvailable = true; }
21
            
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
// in java/org/apache/jasper/compiler/Validator.java
catch (NoSuchMethodException e) { err.jspError("jsp.error.noFunctionMethod", n .getMethodName(), n.getName(), c.getName()); }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (NoSuchMethodException e) { exception = e; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (NoSuchMethodException e) { exception = e; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (NoSuchMethodException e) { exception = e; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (NoSuchMethodException e) { exception = e; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (NoSuchMethodException e) { exception = e; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (NoSuchMethodException e) { exception = e; }
// in java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsIntrospectionSource.java
catch (java.lang.NoSuchMethodException e) { return false; }
// in java/org/apache/catalina/startup/WebRuleSet.java
catch (NoSuchMethodException e) { digester.getLogger().error("Can't find method " + method + " in " + top + " CLASS " + top.getClass()); return; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (NoSuchMethodException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (NoSuchMethodException e) { log.debug(sm.getString("namingResources.cleanupNoClose", name, container, closeMethod)); return; }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (NoSuchMethodException e) { // Should never happen. On that basis don't log // it. }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (NoSuchMethodException e) { // Should never happen. On that basis don't log it. }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (NoSuchMethodException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (NoSuchMethodException e) { log.warn(sm.getString("jreLeakListener.authPolicyFail"), e); }
// in java/javax/el/ExpressionFactory.java
catch (NoSuchMethodException nsme) { // This can be ignored // This is OK for this constructor not to exist }
// in java/javax/el/BeanELResolver.java
catch (NoSuchMethodException e) { // Ignore }
// in java/javax/el/BeanELResolver.java
catch (NoSuchMethodException e) { // Ignore }
// in java/javax/el/BeanELResolver.java
catch (NoSuchMethodException e) { throw new MethodNotFoundException(e); }
3
            
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
// in java/javax/el/BeanELResolver.java
catch (NoSuchMethodException e) { throw new MethodNotFoundException(e); }
3
unknown (Lib) NoSuchProviderException 0 0 0 3
            
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (NoSuchProviderException e) { getLog().error(sm.getString("ajpprocessor.certs.fail"), e); return; }
// in java/org/apache/catalina/valves/SSLValve.java
catch (NoSuchProviderException e) { log.error(sm.getString( "sslValve.invalidProvider", providerName), e); }
// in java/org/apache/catalina/util/SessionIdGenerator.java
catch (NoSuchProviderException e) { log.error(sm.getString("sessionIdGenerator.randomProvider", secureRandomProvider), e); }
0 0
unknown (Lib) NotContextException 2
            
// in java/org/apache/naming/NamingContext.java
Override public void destroySubcontext(Name name) throws NamingException { if (!checkWritable()) { return; } while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) throw new NamingException (sm.getString("namingContext.invalidName")); NamingEntry entry = bindings.get(name.get(0)); if (entry == null) { throw new NameNotFoundException (sm.getString("namingContext.nameNotBound", name, name.get(0))); } if (name.size() > 1) { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).destroySubcontext(name.getSuffix(1)); } else { throw new NamingException (sm.getString("namingContext.contextExpected")); } } else { if (entry.type == NamingEntry.CONTEXT) { ((Context) entry.value).close(); bindings.remove(name.get(0)); } else { throw new NotContextException (sm.getString("namingContext.contextExpected")); } } }
// in java/org/apache/naming/NamingContext.java
Override public NameParser getNameParser(Name name) throws NamingException { while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1); if (name.isEmpty()) return nameParser; if (name.size() > 1) { Object obj = bindings.get(name.get(0)); if (obj instanceof Context) { return ((Context) obj).getNameParser(name.getSuffix(1)); } else { throw new NotContextException (sm.getString("namingContext.contextExpected")); } } return nameParser; }
0 0 0 0 0
unknown (Lib) NotSerializableException 0 0 0 2
            
// in java/org/apache/catalina/session/StandardSession.java
catch (NotSerializableException e) { manager.getContainer().getLogger().warn (sm.getString("standardSession.notSerializable", saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); if (manager.getContainer().getLogger().isDebugEnabled()) manager.getContainer().getLogger().debug (" storing attribute '" + saveNames.get(i) + "' with value NOT_SERIALIZED"); }
// in java/org/apache/catalina/ha/session/DeltaSession.java
catch (NotSerializableException e) { log.error(sm.getString("standardSession.notSerializable",saveNames.get(i), id), e); stream.writeObject(NOT_SERIALIZED); log.error(" storing attribute '" + saveNames.get(i)+ "' with value NOT_SERIALIZED"); }
0 0
runtime (Lib) NullPointerException 73
            
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public Object getAttribute(String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } return pageAttributes.get(name); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public Object getAttribute(String name, int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (scope == PAGE_SCOPE) { return pageAttributes.get(name); } return invokingJspCtxt.getAttribute(name, scope); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void setAttribute(String name, Object value) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (value != null) { pageAttributes.put(name, value); } else { removeAttribute(name, PAGE_SCOPE); } }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void setAttribute(String name, Object value, int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (scope == PAGE_SCOPE) { if (value != null) { pageAttributes.put(name, value); } else { removeAttribute(name, PAGE_SCOPE); } } else { invokingJspCtxt.setAttribute(name, value, scope); } }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public Object findAttribute(String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } Object o = pageAttributes.get(name); if (o == null) { o = invokingJspCtxt.getAttribute(name, REQUEST_SCOPE); if (o == null) { if (getSession() != null) { o = invokingJspCtxt.getAttribute(name, SESSION_SCOPE); } if (o == null) { o = invokingJspCtxt.getAttribute(name, APPLICATION_SCOPE); } } } return o; }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void removeAttribute(String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } pageAttributes.remove(name); invokingJspCtxt.removeAttribute(name, REQUEST_SCOPE); if (getSession() != null) { invokingJspCtxt.removeAttribute(name, SESSION_SCOPE); } invokingJspCtxt.removeAttribute(name, APPLICATION_SCOPE); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void removeAttribute(String name, int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (scope == PAGE_SCOPE) { pageAttributes.remove(name); } else { invokingJspCtxt.removeAttribute(name, scope); } }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public int getAttributesScope(String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (pageAttributes.get(name) != null) { return PAGE_SCOPE; } else { return invokingJspCtxt.getAttributesScope(name); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public Object getAttribute(final String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { return AccessController.doPrivileged( new PrivilegedAction<Object>() { @Override public Object run() { return doGetAttribute(name); } }); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public Object getAttribute(final String name, final int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { return AccessController.doPrivileged( new PrivilegedAction<Object>() { @Override public Object run() { return doGetAttribute(name, scope); } }); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void setAttribute(final String name, final Object attribute) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { doSetAttribute(name, attribute); return null; } }); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void setAttribute(final String name, final Object o, final int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { doSetAttribute(name, o, scope); return null; } }); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void removeAttribute(final String name, final int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { doRemoveAttribute(name, scope); return null; } }); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public int getAttributesScope(final String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { return (AccessController .doPrivileged(new PrivilegedAction<Integer>() { @Override public Integer run() { return Integer.valueOf(doGetAttributeScope(name)); } })).intValue();
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public Object run() { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } return doFindAttribute(name); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void removeAttribute(final String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { doRemoveAttribute(name); return null; } }); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void handlePageException(final Throwable t) throws IOException, ServletException { if (t == null) throw new NullPointerException("null Throwable"); if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doHandlePageException(t); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { return this.variableResolver.resolveVariable(property .toString()); } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getValue(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { Object obj = this.variableResolver.resolveVariable(property .toString()); return (obj != null) ? obj.getClass() : null; } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getType(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); throw new PropertyNotWritableException( "Legacy VariableResolver wrapped, not writable"); } if (!context.isPropertyResolved()) { elResolver.setValue(context, base, property, value); } }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return true; } return elResolver.isReadOnly(context, base, property); }
// in java/org/apache/tomcat/util/collections/ManagedConcurrentWeakHashMap.java
private static void checkNotNull(Object value) { if (value == null) { throw new NullPointerException(); } }
// in java/org/apache/tomcat/util/http/fileupload/FileUploadBase.java
public List<FileItem> parseRequest(RequestContext ctx) throws FileUploadException { List<FileItem> items = new ArrayList<FileItem>(); boolean successful = false; try { FileItemIterator iter = getItemIterator(ctx); FileItemFactory fac = getFileItemFactory(); if (fac == null) { throw new NullPointerException( "No FileItemFactory has been set."); } while (iter.hasNext()) { final FileItemStream item = iter.next(); // Don't use getName() here to prevent an InvalidFileNameException. final String fileName = ((org.apache.tomcat.util.http.fileupload.FileUploadBase.FileItemIteratorImpl.FileItemStreamImpl) item).name; FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), fileName); items.add(fileItem); try { Streams.copy(item.openStream(), fileItem.getOutputStream(), true); } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); } if (fileItem instanceof FileItemHeadersSupport) { final FileItemHeaders fih = item.getHeaders(); ((FileItemHeadersSupport) fileItem).setHeaders(fih); } } successful = true; return items; } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new FileUploadException(e.getMessage(), e); } finally { if (!successful) { for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) { FileItem fileItem = iterator.next(); try { fileItem.delete(); } catch (Exception e) { // ignore it } } } } }
// in java/org/apache/tomcat/util/http/fileupload/FileCleaningTracker.java
public void track(File file, Object marker, FileDeleteStrategy deleteStrategy) { if (file == null) { throw new NullPointerException("The file must not be null"); } addTracker(file.getPath(), marker, deleteStrategy); }
// in java/org/apache/tomcat/util/http/fileupload/FileCleaningTracker.java
public void track(String path, Object marker, FileDeleteStrategy deleteStrategy) { if (path == null) { throw new NullPointerException("The path must not be null"); } addTracker(path, marker, deleteStrategy); }
// in java/org/apache/tomcat/util/digester/ObjectCreateRule.java
Override public void begin(String namespace, String name, Attributes attributes) throws Exception { // Identify the name of the class to instantiate String realClassName = className; if (attributeName != null) { String value = attributes.getValue(attributeName); if (value != null) { realClassName = value; } } if (digester.log.isDebugEnabled()) { digester.log.debug("[ObjectCreateRule]{" + digester.match + "}New " + realClassName); } if (realClassName == null) { throw new NullPointerException("No class name specified for " + namespace + " " + name); } // Instantiate the new object and push it on the context stack Class<?> clazz = digester.getClassLoader().loadClass(realClassName); Object instance = clazz.newInstance(); digester.push(instance); }
// in java/org/apache/el/lang/ExpressionBuilder.java
public MethodExpression createMethodExpression(Class<?> expectedReturnType, Class<?>[] expectedParamTypes) throws ELException { Node n = this.build(); if (!n.isParametersProvided() && expectedParamTypes == null) { throw new NullPointerException(MessageFactory .get("error.method.nullParms")); } if (n instanceof AstValue || n instanceof AstIdentifier) { return new MethodExpressionImpl(expression, n, this.fnMapper, this.varMapper, expectedReturnType, expectedParamTypes); } else if (n instanceof AstLiteralExpression) { return new MethodExpressionLiteral(expression, expectedReturnType, expectedParamTypes); } else { throw new ELException("Not a Valid Method Expression: " + expression); } }
// in java/org/apache/el/ExpressionFactoryImpl.java
Override public ValueExpression createValueExpression(ELContext context, String expression, Class<?> expectedType) { if (expectedType == null) { throw new NullPointerException(MessageFactory .get("error.value.expectedType")); } ExpressionBuilder builder = new ExpressionBuilder(expression, context); return builder.createValueExpression(expectedType); }
// in java/org/apache/el/ExpressionFactoryImpl.java
Override public ValueExpression createValueExpression(Object instance, Class<?> expectedType) { if (expectedType == null) { throw new NullPointerException(MessageFactory .get("error.value.expectedType")); } return new ValueExpressionLiteral(instance, expectedType); }
// in java/org/apache/catalina/core/AccessLogAdapter.java
public void add(AccessLog log) { if (log == null) { throw new NullPointerException(); } AccessLog newArray[] = Arrays.copyOf(logs, logs.length + 1); newArray[newArray.length - 1] = log; logs = newArray; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { PageContext page = (PageContext) context .getContext(JspContext.class); context.setPropertyResolved(true); switch (idx) { case APPLICATIONSCOPE: return ScopeManager.get(page).getApplicationScope(); case COOKIE: return ScopeManager.get(page).getCookie(); case HEADER: return ScopeManager.get(page).getHeader(); case HEADERVALUES: return ScopeManager.get(page).getHeaderValues(); case INITPARAM: return ScopeManager.get(page).getInitParam(); case PAGECONTEXT: return ScopeManager.get(page).getPageContext(); case PAGESCOPE: return ScopeManager.get(page).getPageScope(); case PARAM: return ScopeManager.get(page).getParam(); case PARAM_VALUES: return ScopeManager.get(page).getParamValues(); case REQUEST_SCOPE: return ScopeManager.get(page).getRequestScope(); case SESSION_SCOPE: return ScopeManager.get(page).getSessionScope(); } } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
public Class getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); throw new PropertyNotWritableException(); } } }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); return true; } } return false; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public final V put(String key, V value) { if (key == null) { throw new NullPointerException(); } if (value == null) { this.removeAttribute(key); } else { this.setAttribute(key, value); } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public final V remove(Object key) { if (key == null) { throw new NullPointerException(); } this.removeAttribute((String) key); return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); return page.findAttribute(key); } } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Class<Object> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); int scope = page.getAttributesScope(key); if (scope != 0) { page.setAttribute(key, value, scope); } else { page.setAttribute(key, value); } } } }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); } return false; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); if (property != null) { try { return ((ResourceBundle) base).getObject(property .toString()); } catch (MissingResourceException mre) { return "???" + property.toString() + "???"; } } } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } }
// in java/javax/el/ResourceBundleELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return true; }
// in java/javax/el/CompositeELResolver.java
public void add(ELResolver elResolver) { if (elResolver == null) { throw new NullPointerException(); } if (this.size >= this.resolvers.length) { ELResolver[] nr = new ELResolver[this.size * 2]; System.arraycopy(this.resolvers, 0, nr, 0, this.size); this.resolvers = nr; } this.resolvers[this.size++] = elResolver; }
// in java/javax/el/ArrayELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); if (idx < 0 || idx >= Array.getLength(base)) { return null; } return Array.get(base, idx); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); return base.getClass().getComponentType(); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); checkBounds(base, idx); if (value != null && !base.getClass().getComponentType().isAssignableFrom( value.getClass())) { throw new ClassCastException(message(context, "objectNotAssignable", new Object[] {value.getClass().getName(), base.getClass().getComponentType().getName()})); } Array.set(base, idx, value); } }
// in java/javax/el/ArrayELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); } return this.readOnly; }
// in java/javax/el/MapELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return ((Map<?,?>) base).get(property); } return null; }
// in java/javax/el/MapELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/el/MapELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } try { @SuppressWarnings("unchecked") // Must be OK Map<Object, Object> map = ((Map<Object, Object>) base); map.put(property, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } } }
// in java/javax/el/MapELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); return this.readOnly || UNMODIFIABLE.equals(base.getClass()); } return this.readOnly; }
// in java/javax/el/BeanELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); Method m = this.property(context, base, property).read(context); try { return m.invoke(base, (Object[]) null); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); return this.property(context, base, property).getPropertyType(); }
// in java/javax/el/BeanELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return; } context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } Method m = this.property(context, base, property).write(context); try { m.invoke(base, value); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return false; } context.setPropertyResolved(true); return this.readOnly || this.property(context, base, property).isReadOnly(); }
// in java/javax/el/BeanELResolver.java
Override public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) { if (context == null) { throw new NullPointerException(); } if (base == null) { return null; } try { BeanInfo info = Introspector.getBeanInfo(base.getClass()); PropertyDescriptor[] pds = info.getPropertyDescriptors(); for (int i = 0; i < pds.length; i++) { pds[i].setValue(RESOLVABLE_AT_DESIGN_TIME, Boolean.TRUE); pds[i].setValue(TYPE, pds[i].getPropertyType()); } return Arrays.asList((FeatureDescriptor[]) pds).iterator(); } catch (IntrospectionException e) { // } return null; }
// in java/javax/el/BeanELResolver.java
Override public Class<?> getCommonPropertyType(ELContext context, Object base) { if (context == null) { throw new NullPointerException(); } if (base != null) { return Object.class; } return null; }
// in java/javax/el/BeanELResolver.java
Override public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { if (context == null) { throw new NullPointerException(); } if (base == null || method == null) { return null; } ExpressionFactory factory = ExpressionFactory.newInstance(); String methodName = (String) factory.coerceToType(method, String.class); // Find the matching method Method matchingMethod = null; Class<?> clazz = base.getClass(); if (paramTypes != null) { try { matchingMethod = getMethod(clazz, clazz.getMethod(methodName, paramTypes)); } catch (NoSuchMethodException e) { throw new MethodNotFoundException(e); } } else { int paramCount = 0; if (params != null) { paramCount = params.length; } Method[] methods = clazz.getMethods(); for (Method m : methods) { if (methodName.equals(m.getName())) { if (m.getParameterTypes().length == paramCount) { // Same number of parameters - use the first match matchingMethod = getMethod(clazz, m); break; } if (m.isVarArgs() && paramCount > m.getParameterTypes().length - 2) { matchingMethod = getMethod(clazz, m); } } } if (matchingMethod == null) { throw new MethodNotFoundException( "Unable to find method [" + methodName + "] with [" + paramCount + "] parameters"); } } Class<?>[] parameterTypes = matchingMethod.getParameterTypes(); Object[] parameters = null; if (parameterTypes.length > 0) { parameters = new Object[parameterTypes.length]; @SuppressWarnings("null") // params.length >= parameterTypes.length int paramCount = params.length; if (matchingMethod.isVarArgs()) { int varArgIndex = parameterTypes.length - 1; // First argCount-1 parameters are standard for (int i = 0; (i < varArgIndex); i++) { parameters[i] = factory.coerceToType(params[i], parameterTypes[i]); } // Last parameter is the varargs Class<?> varArgClass = parameterTypes[varArgIndex].getComponentType(); final Object varargs = Array.newInstance( varArgClass, (paramCount - varArgIndex)); for (int i = (varArgIndex); i < paramCount; i++) { Array.set(varargs, i - varArgIndex, factory.coerceToType(params[i], varArgClass)); } parameters[varArgIndex] = varargs; } else { parameters = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { parameters[i] = factory.coerceToType(params[i], parameterTypes[i]); } } }
// in java/javax/el/ListELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { return null; } return list.get(idx); } return null; }
// in java/javax/el/ListELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return Object.class; } return null; }
// in java/javax/el/ListELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); @SuppressWarnings("unchecked") // Must be OK to cast to Object List<Object> list = (List<Object>) base; if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); try { list.set(idx, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); } } }
// in java/javax/el/ListELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return this.readOnly || UNMODIFIABLE.equals(list.getClass()); } return this.readOnly; }
0 43
            
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { return this.variableResolver.resolveVariable(property .toString()); } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getValue(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { Object obj = this.variableResolver.resolveVariable(property .toString()); return (obj != null) ? obj.getClass() : null; } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getType(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); throw new PropertyNotWritableException( "Legacy VariableResolver wrapped, not writable"); } if (!context.isPropertyResolved()) { elResolver.setValue(context, base, property, value); } }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return true; } return elResolver.isReadOnly(context, base, property); }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public MethodInfo getMethodInfo(ELContext context) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.getMethodInfo(context); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public Object invoke(ELContext context, Object[] params) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.invoke(context, params); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Class<?> getType(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getType(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public boolean isReadOnly(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.isReadOnly(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void setValue(ELContext context, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { try { this.target.setValue(context, value); } catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Object getValue(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getValue(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/catalina/servlets/CGIServlet.java
protected String[] hashToStringArray(Hashtable<String,?> h) throws NullPointerException { Vector<String> v = new Vector<String>(); Enumeration<String> e = h.keys(); while (e.hasMoreElements()) { String k = e.nextElement(); v.add(k + "=" + h.get(k).toString()); } String[] strArr = new String[v.size()]; v.copyInto(strArr); return strArr; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { PageContext page = (PageContext) context .getContext(JspContext.class); context.setPropertyResolved(true); switch (idx) { case APPLICATIONSCOPE: return ScopeManager.get(page).getApplicationScope(); case COOKIE: return ScopeManager.get(page).getCookie(); case HEADER: return ScopeManager.get(page).getHeader(); case HEADERVALUES: return ScopeManager.get(page).getHeaderValues(); case INITPARAM: return ScopeManager.get(page).getInitParam(); case PAGECONTEXT: return ScopeManager.get(page).getPageContext(); case PAGESCOPE: return ScopeManager.get(page).getPageScope(); case PARAM: return ScopeManager.get(page).getParam(); case PARAM_VALUES: return ScopeManager.get(page).getParamValues(); case REQUEST_SCOPE: return ScopeManager.get(page).getRequestScope(); case SESSION_SCOPE: return ScopeManager.get(page).getSessionScope(); } } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
public Class getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); throw new PropertyNotWritableException(); } } }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); return true; } } return false; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); return page.findAttribute(key); } } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Class<Object> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); int scope = page.getAttributesScope(key); if (scope != 0) { page.setAttribute(key, value, scope); } else { page.setAttribute(key, value); } } } }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); } return false; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); if (property != null) { try { return ((ResourceBundle) base).getObject(property .toString()); } catch (MissingResourceException mre) { return "???" + property.toString() + "???"; } } } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } }
// in java/javax/el/ResourceBundleELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return true; }
// in java/javax/el/CompositeELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; Object result = null; for (int i = 0; i < sz; i++) { result = this.resolvers[i].getValue(context, base, property); if (context.isPropertyResolved()) { return result; } } return null; }
// in java/javax/el/CompositeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { context.setPropertyResolved(false); int sz = this.size; for (int i = 0; i < sz; i++) { this.resolvers[i].setValue(context, base, property, value); if (context.isPropertyResolved()) { return; } } }
// in java/javax/el/CompositeELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; boolean readOnly = false; for (int i = 0; i < sz; i++) { readOnly = this.resolvers[i].isReadOnly(context, base, property); if (context.isPropertyResolved()) { return readOnly; } } return false; }
// in java/javax/el/CompositeELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; Class<?> type; for (int i = 0; i < sz; i++) { type = this.resolvers[i].getType(context, base, property); if (context.isPropertyResolved()) { if (SCOPED_ATTRIBUTE_EL_RESOLVER != null && SCOPED_ATTRIBUTE_EL_RESOLVER.isAssignableFrom( resolvers[i].getClass())) { // Special case since // javax.servlet.jsp.el.ScopedAttributeELResolver will // always return Object.class for type Object value = resolvers[i].getValue(context, base, property); if (value != null) { return value.getClass(); } } return type; } } return null; }
// in java/javax/el/ArrayELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); if (idx < 0 || idx >= Array.getLength(base)) { return null; } return Array.get(base, idx); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); return base.getClass().getComponentType(); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); checkBounds(base, idx); if (value != null && !base.getClass().getComponentType().isAssignableFrom( value.getClass())) { throw new ClassCastException(message(context, "objectNotAssignable", new Object[] {value.getClass().getName(), base.getClass().getComponentType().getName()})); } Array.set(base, idx, value); } }
// in java/javax/el/ArrayELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); } return this.readOnly; }
// in java/javax/el/MapELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return ((Map<?,?>) base).get(property); } return null; }
// in java/javax/el/MapELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/el/MapELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } try { @SuppressWarnings("unchecked") // Must be OK Map<Object, Object> map = ((Map<Object, Object>) base); map.put(property, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } } }
// in java/javax/el/MapELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); return this.readOnly || UNMODIFIABLE.equals(base.getClass()); } return this.readOnly; }
// in java/javax/el/BeanELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); Method m = this.property(context, base, property).read(context); try { return m.invoke(base, (Object[]) null); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); return this.property(context, base, property).getPropertyType(); }
// in java/javax/el/BeanELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return; } context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } Method m = this.property(context, base, property).write(context); try { m.invoke(base, value); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return false; } context.setPropertyResolved(true); return this.readOnly || this.property(context, base, property).isReadOnly(); }
// in java/javax/el/ListELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { return null; } return list.get(idx); } return null; }
// in java/javax/el/ListELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return Object.class; } return null; }
// in java/javax/el/ListELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); @SuppressWarnings("unchecked") // Must be OK to cast to Object List<Object> list = (List<Object>) base; if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); try { list.set(idx, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); } } }
// in java/javax/el/ListELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return this.readOnly || UNMODIFIABLE.equals(list.getClass()); } return this.readOnly; }
7
            
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch ( NullPointerException x ) { //sun bug 5076772 on windows JDK 1.5 if (selector==null) throw x; if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( NullPointerException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.accept.fail"), npe); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (NullPointerException e) { /* BZ 42449 - Kludge Sun's LDAP provider with broken SSL */ // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (NullPointerException e) { throw new MBeanException(e); }
3
            
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch ( NullPointerException x ) { //sun bug 5076772 on windows JDK 1.5 if (selector==null) throw x; if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( NullPointerException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (NullPointerException e) { throw new MBeanException(e); }
0
unknown (Lib) NumberFormatException 5
            
// in java/org/apache/tomcat/util/buf/Ascii.java
public static long parseLong(byte[] b, int off, int len) throws NumberFormatException { int c; if (b == null || len <= 0 || !isDigit(c = b[off++])) { throw new NumberFormatException(); } long n = c - '0'; long m; while (--len > 0) { if (!isDigit(c = b[off++])) { throw new NumberFormatException(); } m = n * 10 + c - '0'; if (m < n) { // Overflow throw new NumberFormatException(); } else { n = m; } } return n; }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { if (filterConfig.getInitParameter(INTERNAL_PROXIES_PARAMETER) != null) { setInternalProxies(filterConfig.getInitParameter(INTERNAL_PROXIES_PARAMETER)); } if (filterConfig.getInitParameter(PROTOCOL_HEADER_PARAMETER) != null) { setProtocolHeader(filterConfig.getInitParameter(PROTOCOL_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER) != null) { setProtocolHeaderHttpsValue(filterConfig.getInitParameter(PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER)); } if (filterConfig.getInitParameter(PORT_HEADER_PARAMETER) != null) { setPortHeader(filterConfig.getInitParameter(PORT_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(CHANGE_LOCAL_PORT_PARAMETER) != null) { setChangeLocalPort(Boolean.parseBoolean(filterConfig.getInitParameter(CHANGE_LOCAL_PORT_PARAMETER))); } if (filterConfig.getInitParameter(PROXIES_HEADER_PARAMETER) != null) { setProxiesHeader(filterConfig.getInitParameter(PROXIES_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(REMOTE_IP_HEADER_PARAMETER) != null) { setRemoteIpHeader(filterConfig.getInitParameter(REMOTE_IP_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(TRUSTED_PROXIES_PARAMETER) != null) { setTrustedProxies(filterConfig.getInitParameter(TRUSTED_PROXIES_PARAMETER)); } if (filterConfig.getInitParameter(HTTP_SERVER_PORT_PARAMETER) != null) { try { setHttpServerPort(Integer.parseInt(filterConfig.getInitParameter(HTTP_SERVER_PORT_PARAMETER))); } catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTP_SERVER_PORT_PARAMETER + " : " + e.getMessage()); } } if (filterConfig.getInitParameter(HTTPS_SERVER_PORT_PARAMETER) != null) { try { setHttpsServerPort(Integer.parseInt(filterConfig.getInitParameter(HTTPS_SERVER_PORT_PARAMETER))); } catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTPS_SERVER_PORT_PARAMETER + " : " + e.getMessage()); } } }
2
            
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTP_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTPS_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
2
            
// in java/org/apache/tomcat/util/buf/Ascii.java
public static long parseLong(byte[] b, int off, int len) throws NumberFormatException { int c; if (b == null || len <= 0 || !isDigit(c = b[off++])) { throw new NumberFormatException(); } long n = c - '0'; long m; while (--len > 0) { if (!isDigit(c = b[off++])) { throw new NumberFormatException(); } m = n * 10 + c - '0'; if (m < n) { // Overflow throw new NumberFormatException(); } else { n = m; } } return n; }
// in java/org/apache/catalina/util/Extension.java
private boolean isNewer(String first, String second) throws NumberFormatException { if ((first == null) || (second == null)) return (false); if (first.equals(second)) return (true); StringTokenizer fTok = new StringTokenizer(first, ".", true); StringTokenizer sTok = new StringTokenizer(second, ".", true); int fVersion = 0; int sVersion = 0; while (fTok.hasMoreTokens() || sTok.hasMoreTokens()) { if (fTok.hasMoreTokens()) fVersion = Integer.parseInt(fTok.nextToken()); else fVersion = 0; if (sTok.hasMoreTokens()) sVersion = Integer.parseInt(sTok.nextToken()); else sVersion = 0; if (fVersion < sVersion) return (false); else if (fVersion > sVersion) return (true); if (fTok.hasMoreTokens()) // Swallow the periods fTok.nextToken(); if (sTok.hasMoreTokens()) sTok.nextToken(); } return (true); // Exact match }
57
            
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
catch (NumberFormatException e) { err.jspError("jsp.error.invalid.implicit.version", path); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (NumberFormatException ex) { errDispatcher.jspError(ex); }
// in java/org/apache/jasper/compiler/PageInfo.java
catch (NumberFormatException e) { if (n == null) { err.jspError("jsp.error.page.invalid.buffer"); } else { err.jspError(n, "jsp.error.page.invalid.buffer"); } }
// in java/org/apache/jasper/compiler/ErrorDispatcher.java
catch (NumberFormatException e) { lineNum = -1; }
// in java/org/apache/jasper/compiler/JspConfig.java
catch (NumberFormatException e) { }
// in java/org/apache/jasper/JspC.java
catch (NumberFormatException nfe) { dieLevel = DEFAULT_DIE_LEVEL; }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.checkInterval")); } }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval")); } }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.maxLoadedJsps", ""+this.maxLoadedJsps)); } }
// in java/org/apache/jasper/EmbeddedServletOptions.java
catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.jspIdleTimeout", ""+this.jspIdleTimeout)); } }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (NumberFormatException e) { // Ignore }
// in java/org/apache/juli/FileHandler.java
catch (NumberFormatException ignore) { //no op }
// in java/org/apache/coyote/Response.java
catch( NumberFormatException ex ) { // Do nothing - the spec doesn't have any "throws" // and the user might know what he's doing return false; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (NumberFormatException nfe) { // Ignore invalid value }
// in java/org/apache/tomcat/util/net/URL.java
catch (NumberFormatException e) { throw new MalformedURLException(e.toString()); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (NumberFormatException ex) { ok = false; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (NumberFormatException ex) { ok = false; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (NumberFormatException ex) { }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (NumberFormatException e) { log.error(sm.getString("webappLoader.reloadable", event.getNewValue().toString())); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { throw new RuntimeException("Exception parsing number '" + i + "' (zero based) of comma delimited list '" + commaDelimitedInts + "'"); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { // default to now calendar = Calendar.getInstance(); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { throw new IllegalStateException(sm.getString( "Invalid duration (number) '{}' in directive '{}'", currentToken, line)); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException nfe) { log.debug("Invalid port value [" + portHeaderValue + "] provided in header [" + getPortHeader() + "]"); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTP_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTPS_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to integer:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to long:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to float:" + value); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (NumberFormatException ex) { if (isEcho()) handleErrorOutput("Unable to convert to double:" + value); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (NumberFormatException e) { log("Could not parse idle parameter to an int: " + idleParam); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (NumberFormatException e) { log("Could not parse idle parameter to an int: " + idleParam); }
// in java/org/apache/catalina/session/ManagerBase.java
catch (NumberFormatException e) { log.error(sm.getString("managerBase.sessionTimeout", event.getNewValue())); }
// in java/org/apache/catalina/valves/RemoteIpValve.java
catch (NumberFormatException nfe) { if (log.isDebugEnabled()) { log.debug(sm.getString( "remoteIpValve.invalidPortHeader", portHeaderValue, portHeader), nfe); } }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
catch (NumberFormatException nfe) { return false; }
// in java/org/apache/catalina/authenticator/DigestAuthenticator.java
catch (NumberFormatException nfe) { return false; }
// in java/org/apache/catalina/deploy/ErrorPage.java
catch (NumberFormatException nfe) { this.errorCode = 0; }
// in java/org/apache/catalina/deploy/WebXml.java
catch (NumberFormatException nfe) { log.warn(sm.getString("webXml.version.nfe", major, version), nfe); majorVersion = 0; }
// in java/org/apache/catalina/deploy/WebXml.java
catch (NumberFormatException nfe) { log.warn(sm.getString("webXml.version.nfe", minor, version), nfe); minorVersion = 0; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NumberFormatException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NumberFormatException e) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse .SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NumberFormatException e) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError (HttpServletResponse .SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NumberFormatException e) { lockDuration = MAX_TIMEOUT; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (NumberFormatException nfe) { // Not a valid status code log ("runCGI: invalid status code:" + status); return HttpServletResponse.SC_INTERNAL_SERVER_ERROR; }
// in java/org/apache/catalina/servlets/CGIServlet.java
catch (NumberFormatException nfe) { // Not a valid status code log ("runCGI: invalid status code:" + status); return HttpServletResponse.SC_INTERNAL_SERVER_ERROR; }
// in java/org/apache/catalina/connector/Request.java
catch (NumberFormatException e) { quality = 0.0; }
// in java/org/apache/catalina/core/NamingContextListener.java
catch (NumberFormatException e) { logger.error(sm.getString("naming.invalidEnvEntryValue", env.getName())); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (NumberFormatException e) { setLoadOnStartup(0); }
// in java/org/apache/catalina/security/SecurityListener.java
catch (NumberFormatException nfe) { log.warn(sm.getString("SecurityListener.checkUmaskParseFail", prop)); }
// in java/javax/servlet/http/HttpUtils.java
catch (NumberFormatException e) { // XXX // need to be more specific about illegal arg throw new IllegalArgumentException(); }
14
            
// in java/org/apache/tomcat/util/net/URL.java
catch (NumberFormatException e) { throw new MalformedURLException(e.toString()); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/el/lang/ELSupport.java
catch (NumberFormatException nfe) { throw new ELException(MessageFactory.get("error.convert", val, String.class, type)); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { throw new RuntimeException("Exception parsing number '" + i + "' (zero based) of comma delimited list '" + commaDelimitedInts + "'"); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { throw new IllegalStateException(sm.getString( "Invalid duration (number) '{}' in directive '{}'", currentToken, line)); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTP_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTPS_SERVER_PORT_PARAMETER + " : " + e.getMessage()); }
// in java/javax/servlet/http/HttpUtils.java
catch (NumberFormatException e) { // XXX // need to be more specific about illegal arg throw new IllegalArgumentException(); }
11
unknown (Lib) OperationNotSupportedException 20
            
// in java/org/apache/naming/NamingContext.java
Override public String getNameInNamespace() throws NamingException { throw new OperationNotSupportedException (sm.getString("namingContext.noAbsoluteName")); //FIXME ? }
// in java/org/apache/naming/NamingContext.java
protected boolean checkWritable() throws NamingException { if (isWritable()) { return true; } else { if (exceptionOnFailedWrite) { throw new javax.naming.OperationNotSupportedException( sm.getString("namingContext.readOnly")); } } return false; }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void unbind(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void rename(String oldName, String newName) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void destroySubcontext(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void bind(String name, Object obj, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public void rebind(String name, Object obj, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public DirContext getSchema(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public DirContext getSchemaClassDefinition(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/WARDirContext.java
Override public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public DirContext getSchema(String name) throws NamingException { throw new OperationNotSupportedException(); }
// in java/org/apache/naming/resources/FileDirContext.java
Override public DirContext getSchemaClassDefinition(String name) throws NamingException { throw new OperationNotSupportedException(); }
0 0 1
            
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
catch( OperationNotSupportedException ex) { log.error("Operation not supported " + ex); }
0 0
unknown (Lib) OutOfMemoryError 0 0 0 3
            
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; socket.getPoller().cancelledKey(key,SocketStatus.ERROR); releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
0 0
checked (Domain) ParseException
public class ParseException extends Exception {

  /**
   * The version identifier for this Serializable class.
   * Increment only if the <i>serialized</i> form of the
   * class changes.
   */
  private static final long serialVersionUID = 1L;

  /**
   * This constructor is used by the method "generateParseException"
   * in the generated parser.  Calling this constructor generates
   * a new object of this type with the fields "currentToken",
   * "expectedTokenSequences", and "tokenImage" set.
   */
  public ParseException(Token currentTokenVal,
                        int[][] expectedTokenSequencesVal,
                        String[] tokenImageVal
                       )
  {
    super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));
    currentToken = currentTokenVal;
    expectedTokenSequences = expectedTokenSequencesVal;
    tokenImage = tokenImageVal;
  }

  /**
   * The following constructors are for use by you for whatever
   * purpose you can think of.  Constructing the exception in this
   * manner makes the exception behave in the normal way - i.e., as
   * documented in the class "Throwable".  The fields "errorToken",
   * "expectedTokenSequences", and "tokenImage" do not contain
   * relevant information.  The JavaCC generated code does not use
   * these constructors.
   */

  public ParseException() {
    super();
  }

  /** Constructor with message. */
  public ParseException(String message) {
    super(message);
  }


  /**
   * This is the last token that has been consumed successfully.  If
   * this object has been created due to a parse error, the token
   * followng this token will (therefore) be the first error token.
   */
  public Token currentToken;

  /**
   * Each entry in this array is an array of integers.  Each array
   * of integers represents a sequence of tokens (by their ordinal
   * values) that is expected at this point of the parse.
   */
  public int[][] expectedTokenSequences;

  /**
   * This is a reference to the "tokenImage" array of the generated
   * parser within which the parse error occurred.  This array is
   * defined in the generated ...Constants interface.
   */
  public String[] tokenImage;

  /**
   * It uses "currentToken" and "expectedTokenSequences" to generate a parse
   * error message and returns it.  If this object has been created
   * due to a parse error, and you do not catch it (it gets thrown
   * from the parser) the correct error message
   * gets displayed.
   */
  private static String initialise(Token currentToken,
                           int[][] expectedTokenSequences,
                           String[] tokenImage) {
    String eol = System.getProperty("line.separator", "\n");
    StringBuffer expected = new StringBuffer();
    int maxSize = 0;
    for (int i = 0; i < expectedTokenSequences.length; i++) {
      if (maxSize < expectedTokenSequences[i].length) {
        maxSize = expectedTokenSequences[i].length;
      }
      for (int j = 0; j < expectedTokenSequences[i].length; j++) {
        expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
      }
      if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
        expected.append("...");
      }
      expected.append(eol).append("    ");
    }
    String retval = "Encountered \"";
    Token tok = currentToken.next;
    for (int i = 0; i < maxSize; i++) {
      if (i != 0) retval += " ";
      if (tok.kind == 0) {
        retval += tokenImage[0];
        break;
      }
      retval += " " + tokenImage[tok.kind];
      retval += " \"";
      retval += add_escapes(tok.image);
      retval += " \"";
      tok = tok.next;
    }
    retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
    retval += "." + eol;
    if (expectedTokenSequences.length == 1) {
      retval += "Was expecting:" + eol + "    ";
    } else {
      retval += "Was expecting one of:" + eol + "    ";
    }
    retval += expected.toString();
    return retval;
  }

  /**
   * The end of line string for this machine.
   */
  protected String eol = System.getProperty("line.separator", "\n");

  /**
   * Used to convert raw characters to their escaped version
   * when these raw version cannot be used as part of an ASCII
   * string literal.
   */
  static String add_escapes(String str) {
      StringBuffer retval = new StringBuffer();
      char ch;
      for (int i = 0; i < str.length(); i++) {
        switch (str.charAt(i))
        {
           case 0 :
              continue;
           case '\b':
              retval.append("\\b");
              continue;
           case '\t':
              retval.append("\\t");
              continue;
           case '\n':
              retval.append("\\n");
              continue;
           case '\f':
              retval.append("\\f");
              continue;
           case '\r':
              retval.append("\\r");
              continue;
           case '\"':
              retval.append("\\\"");
              continue;
           case '\'':
              retval.append("\\\'");
              continue;
           case '\\':
              retval.append("\\\\");
              continue;
           default:
              if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
                 String s = "0000" + Integer.toString(ch, 16);
                 retval.append("\\u" + s.substring(s.length() - 4, s.length()));
              } else {
                 retval.append(ch);
              }
              continue;
        }
      }
      return retval.toString();
   }

}public class ParseException extends Exception {

  /**
   * The version identifier for this Serializable class.
   * Increment only if the <i>serialized</i> form of the
   * class changes.
   */
  private static final long serialVersionUID = 1L;

  /**
   * This constructor is used by the method "generateParseException"
   * in the generated parser.  Calling this constructor generates
   * a new object of this type with the fields "currentToken",
   * "expectedTokenSequences", and "tokenImage" set.
   */
  public ParseException(Token currentTokenVal,
                        int[][] expectedTokenSequencesVal,
                        String[] tokenImageVal
                       )
  {
    super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));
    currentToken = currentTokenVal;
    expectedTokenSequences = expectedTokenSequencesVal;
    tokenImage = tokenImageVal;
  }

  /**
   * The following constructors are for use by you for whatever
   * purpose you can think of.  Constructing the exception in this
   * manner makes the exception behave in the normal way - i.e., as
   * documented in the class "Throwable".  The fields "errorToken",
   * "expectedTokenSequences", and "tokenImage" do not contain
   * relevant information.  The JavaCC generated code does not use
   * these constructors.
   */

  public ParseException() {
    super();
  }

  /** Constructor with message. */
  public ParseException(String message) {
    super(message);
  }


  /**
   * This is the last token that has been consumed successfully.  If
   * this object has been created due to a parse error, the token
   * followng this token will (therefore) be the first error token.
   */
  public Token currentToken;

  /**
   * Each entry in this array is an array of integers.  Each array
   * of integers represents a sequence of tokens (by their ordinal
   * values) that is expected at this point of the parse.
   */
  public int[][] expectedTokenSequences;

  /**
   * This is a reference to the "tokenImage" array of the generated
   * parser within which the parse error occurred.  This array is
   * defined in the generated ...Constants interface.
   */
  public String[] tokenImage;

  /**
   * It uses "currentToken" and "expectedTokenSequences" to generate a parse
   * error message and returns it.  If this object has been created
   * due to a parse error, and you do not catch it (it gets thrown
   * from the parser) the correct error message
   * gets displayed.
   */
  private static String initialise(Token currentToken,
                           int[][] expectedTokenSequences,
                           String[] tokenImage) {
    String eol = System.getProperty("line.separator", "\n");
    StringBuffer expected = new StringBuffer();
    int maxSize = 0;
    for (int i = 0; i < expectedTokenSequences.length; i++) {
      if (maxSize < expectedTokenSequences[i].length) {
        maxSize = expectedTokenSequences[i].length;
      }
      for (int j = 0; j < expectedTokenSequences[i].length; j++) {
        expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
      }
      if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
        expected.append("...");
      }
      expected.append(eol).append("    ");
    }
    String retval = "Encountered \"";
    Token tok = currentToken.next;
    for (int i = 0; i < maxSize; i++) {
      if (i != 0) retval += " ";
      if (tok.kind == 0) {
        retval += tokenImage[0];
        break;
      }
      retval += " " + tokenImage[tok.kind];
      retval += " \"";
      retval += add_escapes(tok.image);
      retval += " \"";
      tok = tok.next;
    }
    retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
    retval += "." + eol;
    if (expectedTokenSequences.length == 1) {
      retval += "Was expecting:" + eol + "    ";
    } else {
      retval += "Was expecting one of:" + eol + "    ";
    }
    retval += expected.toString();
    return retval;
  }

  /**
   * The end of line string for this machine.
   */
  protected String eol = System.getProperty("line.separator", "\n");

  /**
   * Used to convert raw characters to their escaped version
   * when these raw version cannot be used as part of an ASCII
   * string literal.
   */
  static String add_escapes(String str) {
      StringBuffer retval = new StringBuffer();
      char ch;
      for (int i = 0; i < str.length(); i++) {
        switch (str.charAt(i))
        {
           case 0 :
              continue;
           case '\b':
              retval.append("\\b");
              continue;
           case '\t':
              retval.append("\\t");
              continue;
           case '\n':
              retval.append("\\n");
              continue;
           case '\f':
              retval.append("\\f");
              continue;
           case '\r':
              retval.append("\\r");
              continue;
           case '\"':
              retval.append("\\\"");
              continue;
           case '\'':
              retval.append("\\\'");
              continue;
           case '\\':
              retval.append("\\\\");
              continue;
           default:
              if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
                 String s = "0000" + Integer.toString(ch, 16);
                 retval.append("\\u" + s.substring(s.length() - 4, s.length()));
              } else {
                 retval.append(ch);
              }
              continue;
        }
      }
      return retval.toString();
   }

}
26
            
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
final public void Value() throws ParseException { /*@bgen(jjtree) Value */ AstValue jjtn000 = new AstValue(JJTVALUE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case HTTP_TOKEN: t = jj_consume_token(HTTP_TOKEN); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image.trim()); break; case QUOTED_STRING: t = jj_consume_token(QUOTED_STRING); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image.trim()); break; default: jj_la1[1] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public AstCompositeExpression CompositeExpression() throws ParseException { /*@bgen(jjtree) CompositeExpression */ AstCompositeExpression jjtn000 = new AstCompositeExpression(JJTCOMPOSITEEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { label_1: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LITERAL_EXPRESSION: case START_DYNAMIC_EXPRESSION: case START_DEFERRED_EXPRESSION: ; break; default: jj_la1[0] = jj_gen; break label_1; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case START_DEFERRED_EXPRESSION: DeferredExpression(); break; case START_DYNAMIC_EXPRESSION: DynamicExpression(); break; case LITERAL_EXPRESSION: LiteralExpression(); break; default: jj_la1[1] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } jj_consume_token(0); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; {if (true) return jjtn000;} } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } throw new Error("Missing return statement in function"); }
// in java/org/apache/el/parser/ELParser.java
final public void Or() throws ParseException { And(); label_3: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OR0: case OR1: ; break; default: jj_la1[2] = jj_gen; break label_3; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OR0: jj_consume_token(OR0); break; case OR1: jj_consume_token(OR1); break; default: jj_la1[3] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstOr jjtn001 = new AstOr(JJTOR); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { And(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } } }
// in java/org/apache/el/parser/ELParser.java
final public void And() throws ParseException { Equality(); label_4: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case AND0: case AND1: ; break; default: jj_la1[4] = jj_gen; break label_4; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case AND0: jj_consume_token(AND0); break; case AND1: jj_consume_token(AND1); break; default: jj_la1[5] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstAnd jjtn001 = new AstAnd(JJTAND); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Equality(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } } }
// in java/org/apache/el/parser/ELParser.java
final public void Equality() throws ParseException { Compare(); label_5: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQ0: case EQ1: case NE0: case NE1: ; break; default: jj_la1[6] = jj_gen; break label_5; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQ0: case EQ1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQ0: jj_consume_token(EQ0); break; case EQ1: jj_consume_token(EQ1); break; default: jj_la1[7] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstEqual jjtn001 = new AstEqual(JJTEQUAL); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Compare(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case NE0: case NE1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NE0: jj_consume_token(NE0); break; case NE1: jj_consume_token(NE1); break; default: jj_la1[8] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstNotEqual jjtn002 = new AstNotEqual(JJTNOTEQUAL); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Compare(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; default: jj_la1[9] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Compare() throws ParseException { Math(); label_6: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case GT0: case GT1: case LT0: case LT1: case GE0: case GE1: case LE0: case LE1: ; break; default: jj_la1[10] = jj_gen; break label_6; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LT0: case LT1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LT0: jj_consume_token(LT0); break; case LT1: jj_consume_token(LT1); break; default: jj_la1[11] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstLessThan jjtn001 = new AstLessThan(JJTLESSTHAN); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Math(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case GT0: case GT1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case GT0: jj_consume_token(GT0); break; case GT1: jj_consume_token(GT1); break; default: jj_la1[12] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstGreaterThan jjtn002 = new AstGreaterThan(JJTGREATERTHAN); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Math(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; case LE0: case LE1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LE0: jj_consume_token(LE0); break; case LE1: jj_consume_token(LE1); break; default: jj_la1[13] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstLessThanEqual jjtn003 = new AstLessThanEqual(JJTLESSTHANEQUAL); boolean jjtc003 = true; jjtree.openNodeScope(jjtn003); try { Math(); } catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} } finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, 2); } } break; case GE0: case GE1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case GE0: jj_consume_token(GE0); break; case GE1: jj_consume_token(GE1); break; default: jj_la1[14] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstGreaterThanEqual jjtn004 = new AstGreaterThanEqual(JJTGREATERTHANEQUAL); boolean jjtc004 = true; jjtree.openNodeScope(jjtn004); try { Math(); } catch (Throwable jjte004) { if (jjtc004) { jjtree.clearNodeScope(jjtn004); jjtc004 = false; } else { jjtree.popNode(); } if (jjte004 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte004;} } if (jjte004 instanceof ParseException) { {if (true) throw (ParseException)jjte004;} } {if (true) throw (Error)jjte004;} } finally { if (jjtc004) { jjtree.closeNodeScope(jjtn004, 2); } } break; default: jj_la1[15] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Math() throws ParseException { Multiplication(); label_7: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PLUS: case MINUS: ; break; default: jj_la1[16] = jj_gen; break label_7; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PLUS: jj_consume_token(PLUS); AstPlus jjtn001 = new AstPlus(JJTPLUS); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Multiplication(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case MINUS: jj_consume_token(MINUS); AstMinus jjtn002 = new AstMinus(JJTMINUS); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Multiplication(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; default: jj_la1[17] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Multiplication() throws ParseException { Unary(); label_8: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MULT: case DIV0: case DIV1: case MOD0: case MOD1: ; break; default: jj_la1[18] = jj_gen; break label_8; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MULT: jj_consume_token(MULT); AstMult jjtn001 = new AstMult(JJTMULT); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Unary(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case DIV0: case DIV1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DIV0: jj_consume_token(DIV0); break; case DIV1: jj_consume_token(DIV1); break; default: jj_la1[19] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstDiv jjtn002 = new AstDiv(JJTDIV); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Unary(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; case MOD0: case MOD1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MOD0: jj_consume_token(MOD0); break; case MOD1: jj_consume_token(MOD1); break; default: jj_la1[20] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstMod jjtn003 = new AstMod(JJTMOD); boolean jjtc003 = true; jjtree.openNodeScope(jjtn003); try { Unary(); } catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} } finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, 2); } } break; default: jj_la1[21] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Unary() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MINUS: jj_consume_token(MINUS); AstNegative jjtn001 = new AstNegative(JJTNEGATIVE); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Unary(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } } break; case NOT0: case NOT1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NOT0: jj_consume_token(NOT0); break; case NOT1: jj_consume_token(NOT1); break; default: jj_la1[22] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstNot jjtn002 = new AstNot(JJTNOT); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Unary(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, true); } } break; case EMPTY: jj_consume_token(EMPTY); AstEmpty jjtn003 = new AstEmpty(JJTEMPTY); boolean jjtc003 = true; jjtree.openNodeScope(jjtn003); try { Unary(); } catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} } finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, true); } } break; case INTEGER_LITERAL: case FLOATING_POINT_LITERAL: case STRING_LITERAL: case TRUE: case FALSE: case NULL: case LPAREN: case IDENTIFIER: Value(); break; default: jj_la1[23] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/el/parser/ELParser.java
final public void ValuePrefix() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case INTEGER_LITERAL: case FLOATING_POINT_LITERAL: case STRING_LITERAL: case TRUE: case FALSE: case NULL: Literal(); break; case LPAREN: case IDENTIFIER: NonLiteral(); break; default: jj_la1[25] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/el/parser/ELParser.java
final public void ValueSuffix() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DOT: DotSuffix(); break; case LBRACK: BracketSuffix(); break; default: jj_la1[26] = jj_gen; jj_consume_token(-1); throw new ParseException(); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LPAREN: MethodParameters(); break; default: jj_la1[27] = jj_gen; ; } }
// in java/org/apache/el/parser/ELParser.java
final public void NonLiteral() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LPAREN: jj_consume_token(LPAREN); Expression(); jj_consume_token(RPAREN); break; default: jj_la1[30] = jj_gen; if (jj_2_2(2147483647)) { Function(); } else { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: Identifier(); break; default: jj_la1[31] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } } }
// in java/org/apache/el/parser/ELParser.java
final public void Literal() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TRUE: case FALSE: Boolean(); break; case FLOATING_POINT_LITERAL: FloatingPoint(); break; case INTEGER_LITERAL: Integer(); break; case STRING_LITERAL: String(); break; case NULL: Null(); break; default: jj_la1[34] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/el/parser/ELParser.java
final public void Boolean() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TRUE: AstTrue jjtn001 = new AstTrue(JJTTRUE); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { jj_consume_token(TRUE); } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } } break; case FALSE: AstFalse jjtn002 = new AstFalse(JJTFALSE); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { jj_consume_token(FALSE); } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, true); } } break; default: jj_la1[35] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/catalina/ssi/ExpressionParseTree.java
private void parseExpression(String expr) throws ParseException { StringNode currStringNode = null; // We cheat a little and start an artificial // group right away. It makes finishing easier. pushOpp(null); ExpressionTokenizer et = new ExpressionTokenizer(expr); while (et.hasMoreTokens()) { int token = et.nextToken(); if (token != ExpressionTokenizer.TOKEN_STRING) currStringNode = null; switch (token) { case ExpressionTokenizer.TOKEN_STRING : if (currStringNode == null) { currStringNode = new StringNode(et.getTokenValue()); nodeStack.add(0, currStringNode); } else { // Add to the existing currStringNode.value.append(" "); currStringNode.value.append(et.getTokenValue()); } break; case ExpressionTokenizer.TOKEN_AND : pushOpp(new AndNode()); break; case ExpressionTokenizer.TOKEN_OR : pushOpp(new OrNode()); break; case ExpressionTokenizer.TOKEN_NOT : pushOpp(new NotNode()); break; case ExpressionTokenizer.TOKEN_EQ : pushOpp(new EqualNode()); break; case ExpressionTokenizer.TOKEN_NOT_EQ : pushOpp(new NotNode()); // Sneak the regular node in. The NOT will // be resolved when the next opp comes along. oppStack.add(0, new EqualNode()); break; case ExpressionTokenizer.TOKEN_RBRACE : // Closeout the current group resolveGroup(); break; case ExpressionTokenizer.TOKEN_LBRACE : // Push a group marker pushOpp(null); break; case ExpressionTokenizer.TOKEN_GE : pushOpp(new NotNode()); // Similar strategy to NOT_EQ above, except this // is NOT less than oppStack.add(0, new LessThanNode()); break; case ExpressionTokenizer.TOKEN_LE : pushOpp(new NotNode()); // Similar strategy to NOT_EQ above, except this // is NOT greater than oppStack.add(0, new GreaterThanNode()); break; case ExpressionTokenizer.TOKEN_GT : pushOpp(new GreaterThanNode()); break; case ExpressionTokenizer.TOKEN_LT : pushOpp(new LessThanNode()); break; case ExpressionTokenizer.TOKEN_END : break; } } // Finish off the rest of the opps resolveGroup(); if (nodeStack.size() == 0) { throw new ParseException("No nodes created.", et.getIndex()); } if (nodeStack.size() > 1) { throw new ParseException("Extra nodes created.", et.getIndex()); } if (oppStack.size() != 0) { throw new ParseException("Unused opp nodes exist.", et.getIndex()); } root = nodeStack.get(0); }
0 37
            
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
final public void Type() throws ParseException { /*@bgen(jjtree) Type */ AstType jjtn000 = new AstType(JJTTYPE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(HTTP_TOKEN); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image.trim()); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
final public void SubType() throws ParseException { /*@bgen(jjtree) SubType */ AstSubType jjtn000 = new AstSubType(JJTSUBTYPE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(HTTP_TOKEN); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image.trim()); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
final public void Parameter() throws ParseException { /*@bgen(jjtree) Parameter */ AstParameter jjtn000 = new AstParameter(JJTPARAMETER); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { Attribute(); jj_consume_token(EQUALS); Value(); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
final public void Attribute() throws ParseException { /*@bgen(jjtree) Attribute */ AstAttribute jjtn000 = new AstAttribute(JJTATTRIBUTE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(HTTP_TOKEN); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image.trim()); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
final public void Value() throws ParseException { /*@bgen(jjtree) Value */ AstValue jjtn000 = new AstValue(JJTVALUE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case HTTP_TOKEN: t = jj_consume_token(HTTP_TOKEN); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image.trim()); break; case QUOTED_STRING: t = jj_consume_token(QUOTED_STRING); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image.trim()); break; default: jj_la1[1] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
private Token jj_consume_token(int kind) throws ParseException { Token oldToken; if ((oldToken = token).next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; if (token.kind == kind) { jj_gen++; return token; } token = oldToken; jj_kind = kind; throw generateParseException(); }
// in java/org/apache/el/parser/ELParser.java
final public AstCompositeExpression CompositeExpression() throws ParseException { /*@bgen(jjtree) CompositeExpression */ AstCompositeExpression jjtn000 = new AstCompositeExpression(JJTCOMPOSITEEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { label_1: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LITERAL_EXPRESSION: case START_DYNAMIC_EXPRESSION: case START_DEFERRED_EXPRESSION: ; break; default: jj_la1[0] = jj_gen; break label_1; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case START_DEFERRED_EXPRESSION: DeferredExpression(); break; case START_DYNAMIC_EXPRESSION: DynamicExpression(); break; case LITERAL_EXPRESSION: LiteralExpression(); break; default: jj_la1[1] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } jj_consume_token(0); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; {if (true) return jjtn000;} } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } throw new Error("Missing return statement in function"); }
// in java/org/apache/el/parser/ELParser.java
final public void LiteralExpression() throws ParseException { /*@bgen(jjtree) LiteralExpression */ AstLiteralExpression jjtn000 = new AstLiteralExpression(JJTLITERALEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(LITERAL_EXPRESSION); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.setImage(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void DeferredExpression() throws ParseException { /*@bgen(jjtree) DeferredExpression */ AstDeferredExpression jjtn000 = new AstDeferredExpression(JJTDEFERREDEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(START_DEFERRED_EXPRESSION); Expression(); jj_consume_token(END_EXPRESSION); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void DynamicExpression() throws ParseException { /*@bgen(jjtree) DynamicExpression */ AstDynamicExpression jjtn000 = new AstDynamicExpression(JJTDYNAMICEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(START_DYNAMIC_EXPRESSION); Expression(); jj_consume_token(END_EXPRESSION); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Expression() throws ParseException { Choice(); }
// in java/org/apache/el/parser/ELParser.java
final public void Choice() throws ParseException { Or(); label_2: while (true) { if (jj_2_1(3)) { ; } else { break label_2; } jj_consume_token(QUESTIONMARK); Choice(); jj_consume_token(COLON); AstChoice jjtn001 = new AstChoice(JJTCHOICE); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Choice(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 3); } } } }
// in java/org/apache/el/parser/ELParser.java
final public void Or() throws ParseException { And(); label_3: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OR0: case OR1: ; break; default: jj_la1[2] = jj_gen; break label_3; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OR0: jj_consume_token(OR0); break; case OR1: jj_consume_token(OR1); break; default: jj_la1[3] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstOr jjtn001 = new AstOr(JJTOR); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { And(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } } }
// in java/org/apache/el/parser/ELParser.java
final public void And() throws ParseException { Equality(); label_4: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case AND0: case AND1: ; break; default: jj_la1[4] = jj_gen; break label_4; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case AND0: jj_consume_token(AND0); break; case AND1: jj_consume_token(AND1); break; default: jj_la1[5] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstAnd jjtn001 = new AstAnd(JJTAND); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Equality(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } } }
// in java/org/apache/el/parser/ELParser.java
final public void Equality() throws ParseException { Compare(); label_5: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQ0: case EQ1: case NE0: case NE1: ; break; default: jj_la1[6] = jj_gen; break label_5; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQ0: case EQ1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQ0: jj_consume_token(EQ0); break; case EQ1: jj_consume_token(EQ1); break; default: jj_la1[7] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstEqual jjtn001 = new AstEqual(JJTEQUAL); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Compare(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case NE0: case NE1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NE0: jj_consume_token(NE0); break; case NE1: jj_consume_token(NE1); break; default: jj_la1[8] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstNotEqual jjtn002 = new AstNotEqual(JJTNOTEQUAL); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Compare(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; default: jj_la1[9] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Compare() throws ParseException { Math(); label_6: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case GT0: case GT1: case LT0: case LT1: case GE0: case GE1: case LE0: case LE1: ; break; default: jj_la1[10] = jj_gen; break label_6; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LT0: case LT1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LT0: jj_consume_token(LT0); break; case LT1: jj_consume_token(LT1); break; default: jj_la1[11] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstLessThan jjtn001 = new AstLessThan(JJTLESSTHAN); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Math(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case GT0: case GT1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case GT0: jj_consume_token(GT0); break; case GT1: jj_consume_token(GT1); break; default: jj_la1[12] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstGreaterThan jjtn002 = new AstGreaterThan(JJTGREATERTHAN); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Math(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; case LE0: case LE1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LE0: jj_consume_token(LE0); break; case LE1: jj_consume_token(LE1); break; default: jj_la1[13] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstLessThanEqual jjtn003 = new AstLessThanEqual(JJTLESSTHANEQUAL); boolean jjtc003 = true; jjtree.openNodeScope(jjtn003); try { Math(); } catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} } finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, 2); } } break; case GE0: case GE1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case GE0: jj_consume_token(GE0); break; case GE1: jj_consume_token(GE1); break; default: jj_la1[14] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstGreaterThanEqual jjtn004 = new AstGreaterThanEqual(JJTGREATERTHANEQUAL); boolean jjtc004 = true; jjtree.openNodeScope(jjtn004); try { Math(); } catch (Throwable jjte004) { if (jjtc004) { jjtree.clearNodeScope(jjtn004); jjtc004 = false; } else { jjtree.popNode(); } if (jjte004 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte004;} } if (jjte004 instanceof ParseException) { {if (true) throw (ParseException)jjte004;} } {if (true) throw (Error)jjte004;} } finally { if (jjtc004) { jjtree.closeNodeScope(jjtn004, 2); } } break; default: jj_la1[15] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Math() throws ParseException { Multiplication(); label_7: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PLUS: case MINUS: ; break; default: jj_la1[16] = jj_gen; break label_7; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PLUS: jj_consume_token(PLUS); AstPlus jjtn001 = new AstPlus(JJTPLUS); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Multiplication(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case MINUS: jj_consume_token(MINUS); AstMinus jjtn002 = new AstMinus(JJTMINUS); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Multiplication(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; default: jj_la1[17] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Multiplication() throws ParseException { Unary(); label_8: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MULT: case DIV0: case DIV1: case MOD0: case MOD1: ; break; default: jj_la1[18] = jj_gen; break label_8; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MULT: jj_consume_token(MULT); AstMult jjtn001 = new AstMult(JJTMULT); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Unary(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } break; case DIV0: case DIV1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DIV0: jj_consume_token(DIV0); break; case DIV1: jj_consume_token(DIV1); break; default: jj_la1[19] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstDiv jjtn002 = new AstDiv(JJTDIV); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Unary(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, 2); } } break; case MOD0: case MOD1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MOD0: jj_consume_token(MOD0); break; case MOD1: jj_consume_token(MOD1); break; default: jj_la1[20] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstMod jjtn003 = new AstMod(JJTMOD); boolean jjtc003 = true; jjtree.openNodeScope(jjtn003); try { Unary(); } catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} } finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, 2); } } break; default: jj_la1[21] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Unary() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MINUS: jj_consume_token(MINUS); AstNegative jjtn001 = new AstNegative(JJTNEGATIVE); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Unary(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } } break; case NOT0: case NOT1: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NOT0: jj_consume_token(NOT0); break; case NOT1: jj_consume_token(NOT1); break; default: jj_la1[22] = jj_gen; jj_consume_token(-1); throw new ParseException(); } AstNot jjtn002 = new AstNot(JJTNOT); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { Unary(); } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, true); } } break; case EMPTY: jj_consume_token(EMPTY); AstEmpty jjtn003 = new AstEmpty(JJTEMPTY); boolean jjtc003 = true; jjtree.openNodeScope(jjtn003); try { Unary(); } catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} } finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, true); } } break; case INTEGER_LITERAL: case FLOATING_POINT_LITERAL: case STRING_LITERAL: case TRUE: case FALSE: case NULL: case LPAREN: case IDENTIFIER: Value(); break; default: jj_la1[23] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/el/parser/ELParser.java
final public void Value() throws ParseException { AstValue jjtn001 = new AstValue(JJTVALUE); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { ValuePrefix(); label_9: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DOT: case LBRACK: ; break; default: jj_la1[24] = jj_gen; break label_9; } ValueSuffix(); } } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, jjtree.nodeArity() > 1); } } }
// in java/org/apache/el/parser/ELParser.java
final public void ValuePrefix() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case INTEGER_LITERAL: case FLOATING_POINT_LITERAL: case STRING_LITERAL: case TRUE: case FALSE: case NULL: Literal(); break; case LPAREN: case IDENTIFIER: NonLiteral(); break; default: jj_la1[25] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/el/parser/ELParser.java
final public void ValueSuffix() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DOT: DotSuffix(); break; case LBRACK: BracketSuffix(); break; default: jj_la1[26] = jj_gen; jj_consume_token(-1); throw new ParseException(); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LPAREN: MethodParameters(); break; default: jj_la1[27] = jj_gen; ; } }
// in java/org/apache/el/parser/ELParser.java
final public void DotSuffix() throws ParseException { /*@bgen(jjtree) DotSuffix */ AstDotSuffix jjtn000 = new AstDotSuffix(JJTDOTSUFFIX); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { jj_consume_token(DOT); t = jj_consume_token(IDENTIFIER); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.setImage(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void BracketSuffix() throws ParseException { /*@bgen(jjtree) BracketSuffix */ AstBracketSuffix jjtn000 = new AstBracketSuffix(JJTBRACKETSUFFIX); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(LBRACK); Expression(); jj_consume_token(RBRACK); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void MethodParameters() throws ParseException { /*@bgen(jjtree) MethodParameters */ AstMethodParameters jjtn000 = new AstMethodParameters(JJTMETHODPARAMETERS); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(LPAREN); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case INTEGER_LITERAL: case FLOATING_POINT_LITERAL: case STRING_LITERAL: case TRUE: case FALSE: case NULL: case LPAREN: case NOT0: case NOT1: case EMPTY: case MINUS: case IDENTIFIER: Expression(); label_10: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: ; break; default: jj_la1[28] = jj_gen; break label_10; } jj_consume_token(COMMA); Expression(); } break; default: jj_la1[29] = jj_gen; ; } jj_consume_token(RPAREN); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void NonLiteral() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LPAREN: jj_consume_token(LPAREN); Expression(); jj_consume_token(RPAREN); break; default: jj_la1[30] = jj_gen; if (jj_2_2(2147483647)) { Function(); } else { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: Identifier(); break; default: jj_la1[31] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } } }
// in java/org/apache/el/parser/ELParser.java
final public void Identifier() throws ParseException { /*@bgen(jjtree) Identifier */ AstIdentifier jjtn000 = new AstIdentifier(JJTIDENTIFIER); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(IDENTIFIER); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.setImage(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Function() throws ParseException { /*@bgen(jjtree) Function */ AstFunction jjtn000 = new AstFunction(JJTFUNCTION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t0 = null; Token t1 = null; try { if (jj_2_3(2)) { t0 = jj_consume_token(IDENTIFIER); jj_consume_token(COLON); } else { ; } t1 = jj_consume_token(IDENTIFIER); if (t0 != null) { jjtn000.setPrefix(t0.image); jjtn000.setLocalName(t1.image); } else { jjtn000.setLocalName(t1.image); } jj_consume_token(LPAREN); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case INTEGER_LITERAL: case FLOATING_POINT_LITERAL: case STRING_LITERAL: case TRUE: case FALSE: case NULL: case LPAREN: case NOT0: case NOT1: case EMPTY: case MINUS: case IDENTIFIER: Expression(); label_11: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: ; break; default: jj_la1[32] = jj_gen; break label_11; } jj_consume_token(COMMA); Expression(); } break; default: jj_la1[33] = jj_gen; ; } jj_consume_token(RPAREN); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Literal() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TRUE: case FALSE: Boolean(); break; case FLOATING_POINT_LITERAL: FloatingPoint(); break; case INTEGER_LITERAL: Integer(); break; case STRING_LITERAL: String(); break; case NULL: Null(); break; default: jj_la1[34] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/el/parser/ELParser.java
final public void Boolean() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TRUE: AstTrue jjtn001 = new AstTrue(JJTTRUE); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { jj_consume_token(TRUE); } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } } break; case FALSE: AstFalse jjtn002 = new AstFalse(JJTFALSE); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { jj_consume_token(FALSE); } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, true); } } break; default: jj_la1[35] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
// in java/org/apache/el/parser/ELParser.java
final public void FloatingPoint() throws ParseException { /*@bgen(jjtree) FloatingPoint */ AstFloatingPoint jjtn000 = new AstFloatingPoint(JJTFLOATINGPOINT); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(FLOATING_POINT_LITERAL); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.setImage(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Integer() throws ParseException { /*@bgen(jjtree) Integer */ AstInteger jjtn000 = new AstInteger(JJTINTEGER); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(INTEGER_LITERAL); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.setImage(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void String() throws ParseException { /*@bgen(jjtree) String */ AstString jjtn000 = new AstString(JJTSTRING); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { t = jj_consume_token(STRING_LITERAL); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.setImage(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
final public void Null() throws ParseException { /*@bgen(jjtree) Null */ AstNull jjtn000 = new AstNull(JJTNULL); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(NULL); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
// in java/org/apache/el/parser/ELParser.java
private Token jj_consume_token(int kind) throws ParseException { Token oldToken; if ((oldToken = token).next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; if (token.kind == kind) { jj_gen++; if (++jj_gc > 100) { jj_gc = 0; for (int i = 0; i < jj_2_rtns.length; i++) { JJCalls c = jj_2_rtns[i]; while (c != null) { if (c.gen < jj_gen) c.first = null; c = c.next; } } } return token; } token = oldToken; jj_kind = kind; throw generateParseException(); }
// in java/org/apache/catalina/ssi/ExpressionParseTree.java
private void parseExpression(String expr) throws ParseException { StringNode currStringNode = null; // We cheat a little and start an artificial // group right away. It makes finishing easier. pushOpp(null); ExpressionTokenizer et = new ExpressionTokenizer(expr); while (et.hasMoreTokens()) { int token = et.nextToken(); if (token != ExpressionTokenizer.TOKEN_STRING) currStringNode = null; switch (token) { case ExpressionTokenizer.TOKEN_STRING : if (currStringNode == null) { currStringNode = new StringNode(et.getTokenValue()); nodeStack.add(0, currStringNode); } else { // Add to the existing currStringNode.value.append(" "); currStringNode.value.append(et.getTokenValue()); } break; case ExpressionTokenizer.TOKEN_AND : pushOpp(new AndNode()); break; case ExpressionTokenizer.TOKEN_OR : pushOpp(new OrNode()); break; case ExpressionTokenizer.TOKEN_NOT : pushOpp(new NotNode()); break; case ExpressionTokenizer.TOKEN_EQ : pushOpp(new EqualNode()); break; case ExpressionTokenizer.TOKEN_NOT_EQ : pushOpp(new NotNode()); // Sneak the regular node in. The NOT will // be resolved when the next opp comes along. oppStack.add(0, new EqualNode()); break; case ExpressionTokenizer.TOKEN_RBRACE : // Closeout the current group resolveGroup(); break; case ExpressionTokenizer.TOKEN_LBRACE : // Push a group marker pushOpp(null); break; case ExpressionTokenizer.TOKEN_GE : pushOpp(new NotNode()); // Similar strategy to NOT_EQ above, except this // is NOT less than oppStack.add(0, new LessThanNode()); break; case ExpressionTokenizer.TOKEN_LE : pushOpp(new NotNode()); // Similar strategy to NOT_EQ above, except this // is NOT greater than oppStack.add(0, new GreaterThanNode()); break; case ExpressionTokenizer.TOKEN_GT : pushOpp(new GreaterThanNode()); break; case ExpressionTokenizer.TOKEN_LT : pushOpp(new LessThanNode()); break; case ExpressionTokenizer.TOKEN_END : break; } } // Finish off the rest of the opps resolveGroup(); if (nodeStack.size() == 0) { throw new ParseException("No nodes created.", et.getIndex()); } if (nodeStack.size() > 1) { throw new ParseException("Extra nodes created.", et.getIndex()); } if (oppStack.size() != 0) { throw new ParseException("Unused opp nodes exist.", et.getIndex()); } root = nodeStack.get(0); }
9
            
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (ParseException e) { // Ignore }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (ParseException e) { // Ignore }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (ParseException e) { // Ignore }
// in java/org/apache/naming/resources/ResourceAttributes.java
catch (ParseException e) { // Ignore }
// in java/org/apache/coyote/Response.java
catch (ParseException e) { // Invalid - Assume no charset and just pass through whatever // the user provided. this.contentType = type; return; }
// in java/org/apache/tomcat/util/http/FastHttpDateFormat.java
catch (ParseException e) { // Ignore }
// in java/org/apache/el/parser/ELParser.java
catch (ParseException pe) { throw new ELException(pe.getMessage());
// in java/org/apache/catalina/filters/RemoteIpFilter.java
catch (Exception ParseException) { // Ignore }
// in java/org/apache/catalina/ssi/SSIConditional.java
catch (ParseException e) { //throw new SsiCommandException( "Error parsing expression." ); throw new SSIStopProcessingException(); }
// in java/org/apache/catalina/connector/Response.java
catch (ParseException e) { // Invalid - Assume no charset and just pass through whatever // the user provided. coyoteResponse.setContentTypeNoCharset(type); return; }
2
            
// in java/org/apache/el/parser/ELParser.java
catch (ParseException pe) { throw new ELException(pe.getMessage());
// in java/org/apache/catalina/ssi/SSIConditional.java
catch (ParseException e) { //throw new SsiCommandException( "Error parsing expression." ); throw new SSIStopProcessingException(); }
1
unknown (Lib) ParserConfigurationException 0 0 11
            
// in java/org/apache/tomcat/util/digester/Digester.java
public SAXParserFactory getFactory() throws SAXNotRecognizedException, SAXNotSupportedException, ParserConfigurationException { if (factory == null) { factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(namespaceAware); factory.setValidating(validating); if (validating) { // Enable DTD validation factory.setFeature( "http://xml.org/sax/features/validation", true); // Enable schema validation factory.setFeature( "http://apache.org/xml/features/validation/schema", true); } } return (factory); }
// in java/org/apache/tomcat/util/digester/Digester.java
public boolean getFeature(String feature) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException { return (getFactory().getFeature(feature)); }
// in java/org/apache/tomcat/util/digester/Digester.java
public void setFeature(String feature, boolean value) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException { getFactory().setFeature(feature, value); }
// in java/org/apache/tomcat/util/digester/XercesParser.java
public static SAXParser newSAXParser(Properties properties) throws ParserConfigurationException, SAXException, SAXNotSupportedException { SAXParserFactory factory = (SAXParserFactory)properties.get("SAXParserFactory"); if (versionNumber == null){ versionNumber = getXercesVersion(); version = new Float( versionNumber ).floatValue(); } // Note: 2.2 is completely broken (with XML Schema). if (version > 2.1) { configureXerces(factory); return factory.newSAXParser(); } else { SAXParser parser = factory.newSAXParser(); configureOldXerces(parser,properties); return parser; } }
// in java/org/apache/tomcat/util/digester/XercesParser.java
private static void configureOldXerces(SAXParser parser, Properties properties) throws ParserConfigurationException, SAXNotSupportedException { String schemaLocation = (String)properties.get("schemaLocation"); String schemaLanguage = (String)properties.get("schemaLanguage"); try{ if (schemaLocation != null) { parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage); parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation); } } catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); } }
// in java/org/apache/tomcat/util/digester/XercesParser.java
private static void configureXerces(SAXParserFactory factory) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException { factory.setFeature(XERCES_DYNAMIC, true); factory.setFeature(XERCES_SCHEMA, true); }
// in java/org/apache/tomcat/util/digester/ParserFeatureSetterFactory.java
public static SAXParser newSAXParser(Properties properties) throws ParserConfigurationException, SAXException, SAXNotRecognizedException, SAXNotSupportedException { if (isXercesUsed){ return XercesParser.newSAXParser(properties); } else { return GenericParser.newSAXParser(properties); } }
// in java/org/apache/tomcat/util/digester/GenericParser.java
public static SAXParser newSAXParser(Properties properties) throws ParserConfigurationException, SAXException, SAXNotRecognizedException{ SAXParserFactory factory = (SAXParserFactory)properties.get("SAXParserFactory"); SAXParser parser = factory.newSAXParser(); String schemaLocation = (String)properties.get("schemaLocation"); String schemaLanguage = (String)properties.get("schemaLanguage"); try{ if (schemaLocation != null) { parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage); parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation); } } catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); } return parser; }
3
            
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (ParserConfigurationException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), ex); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch(ParserConfigurationException e) { throw new ServletException (sm.getString("webdavservlet.jaxpfailed")); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (ParserConfigurationException e) { log.error(sm.getString("jreLeakListener.xmlParseFail"), e); }
2
            
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (ParserConfigurationException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), ex); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch(ParserConfigurationException e) { throw new ServletException (sm.getString("webdavservlet.jaxpfailed")); }
0
unknown (Lib) PartialResultException 0 0 0 5
            
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; else return (null); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
5
            
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; else return (null); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (PartialResultException ex) { if (!adCompat) throw ex; }
0
unknown (Lib) PatternSyntaxException 0 0 0 2
            
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
catch (PatternSyntaxException pse) { log.error(sm.getString("ReplicationValve.filter.failure", filter), pse); }
// in java/org/apache/catalina/ssi/ExpressionParseTree.java
catch (PatternSyntaxException pse) { ssiMediator.log("Invalid expression: " + expr, pse); return 0; }
0 0
unknown (Lib) PrivilegedActionException 0 0 1
            
// in java/org/apache/catalina/core/ApplicationContextFacade.java
private Object executeMethod(final Method method, final ApplicationContext context, final Object[] params) throws PrivilegedActionException, IllegalAccessException, InvocationTargetException { if (SecurityUtil.isPackageProtectionEnabled()){ return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>(){ @Override public Object run() throws IllegalAccessException, InvocationTargetException{ return method.invoke(context, params); } }); }
31
            
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); throw (JasperException)e; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ServletException) throw (ServletException)t; throw new ServletException("Could not precompile jsp: " + jspFile, e); }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof ClassNotFoundException){ throw (ClassNotFoundException)exception; } else if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in load() " + exception); }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in unLoad() " + exception); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); log.error("Exception clearing the Store: " + exception, exception); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); log.error("Exception in the Store during load: " + exception, exception); return; }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); log.error("Exception in the Store during removeSession: " + exception, exception); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (PrivilegedActionException ex) { Exception e = ex.getException(); log.error(sm.getString( "persistentManager.swapInException", id), e); if (e instanceof IOException){ throw (IOException)e; } else if (e instanceof ClassNotFoundException) { throw (ClassNotFoundException)e; } }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException) { throw (IOException) exception; } log.error("Exception in the Store during writeSession: " + exception, exception); }
// in java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
catch (PrivilegedActionException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail", e)); response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
// in java/org/apache/catalina/connector/OutputBuffer.java
catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } }
// in java/org/apache/catalina/connector/Response.java
catch (PrivilegedActionException pae){ IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(pae.getException()); throw iae; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage() ,e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/InputBuffer.java
catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } }
// in java/org/apache/catalina/connector/ResponseFacade.java
catch(PrivilegedActionException e){ Exception ex = e.getException(); if (ex instanceof IOException){ throw (IOException)ex; } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; }
// in java/org/apache/catalina/security/SecurityUtil.java
catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
52
            
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); throw (JasperException)e; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ServletException) throw (ServletException)t; throw new ServletException("Could not precompile jsp: " + jspFile, e); }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof ClassNotFoundException){ throw (ClassNotFoundException)exception; } else if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in load() " + exception); }
// in java/org/apache/catalina/session/StandardManager.java
catch (PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException){ throw (IOException)exception; } if (log.isDebugEnabled()) log.debug("Unreported exception in unLoad() " + exception); }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch (PrivilegedActionException ex) { Exception e = ex.getException(); log.error(sm.getString( "persistentManager.swapInException", id), e); if (e instanceof IOException){ throw (IOException)e; } else if (e instanceof ClassNotFoundException) { throw (ClassNotFoundException)e; } }
// in java/org/apache/catalina/session/PersistentManagerBase.java
catch(PrivilegedActionException ex){ Exception exception = ex.getException(); if (exception instanceof IOException) { throw (IOException) exception; } log.error("Exception in the Store during writeSession: " + exception, exception); }
// in java/org/apache/catalina/connector/OutputBuffer.java
catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } }
// in java/org/apache/catalina/connector/Response.java
catch (PrivilegedActionException pae){ IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(pae.getException()); throw iae; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage() ,e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/InputBuffer.java
catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } }
// in java/org/apache/catalina/connector/ResponseFacade.java
catch(PrivilegedActionException e){ Exception ex = e.getException(); if (ex instanceof IOException){ throw (IOException)ex; } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; }
// in java/org/apache/catalina/security/SecurityUtil.java
catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
9
runtime (Domain) PropertyNotFoundException
public class PropertyNotFoundException extends ELException {

    private static final long serialVersionUID = -3799200961303506745L;

    /**
     *
     */
    public PropertyNotFoundException() {
        super();
    }

    /**
     * @param message
     */
    public PropertyNotFoundException(String message) {
        super(message);
    }

    /**
     * @param message
     * @param cause
     */
    public PropertyNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * @param cause
     */
    public PropertyNotFoundException(Throwable cause) {
        super(cause);
    }

}
18
            
// in java/org/apache/el/parser/AstIdentifier.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { return expr.getType(ctx.getELContext()); } } ctx.setPropertyResolved(false); Class<?> result = ctx.getELResolver().getType(ctx, null, this.image); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } return result; }
// in java/org/apache/el/parser/AstIdentifier.java
Override public Object getValue(EvaluationContext ctx) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { return expr.getValue(ctx.getELContext()); } } ctx.setPropertyResolved(false); Object result = ctx.getELResolver().getValue(ctx, null, this.image); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } return result; }
// in java/org/apache/el/parser/AstIdentifier.java
Override public boolean isReadOnly(EvaluationContext ctx) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { return expr.isReadOnly(ctx.getELContext()); } } ctx.setPropertyResolved(false); boolean result = ctx.getELResolver().isReadOnly(ctx, null, this.image); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } return result; }
// in java/org/apache/el/parser/AstIdentifier.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { VariableMapper varMapper = ctx.getVariableMapper(); if (varMapper != null) { ValueExpression expr = varMapper.resolveVariable(this.image); if (expr != null) { expr.setValue(ctx.getELContext(), value); return; } } ctx.setPropertyResolved(false); ctx.getELResolver().setValue(ctx, null, this.image, value); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled.null", this.image)); } }
// in java/org/apache/el/parser/AstValue.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { Target t = getTarget(ctx); ctx.setPropertyResolved(false); Class<?> result = ctx.getELResolver().getType(ctx, t.base, t.property); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", t.base, t.property)); } return result; }
// in java/org/apache/el/parser/AstValue.java
private final Target getTarget(EvaluationContext ctx) throws ELException { // evaluate expr-a to value-a Object base = this.children[0].getValue(ctx); // if our base is null (we know there are more properties to evaluate) if (base == null) { throw new PropertyNotFoundException(MessageFactory.get( "error.unreachable.base", this.children[0].getImage())); } // set up our start/end Object property = null; int propCount = this.jjtGetNumChildren(); if (propCount > 2 && this.jjtGetChild(propCount - 1) instanceof AstMethodParameters) { // Method call with paramaters. propCount-=2; } else { propCount--; } int i = 1; // evaluate any properties before our target ELResolver resolver = ctx.getELResolver(); if (propCount > 1) { while (base != null && i < propCount) { property = this.children[i].getValue(ctx); ctx.setPropertyResolved(false); base = resolver.getValue(ctx, base, property); i++; } // if we are in this block, we have more properties to resolve, // but our base was null if (base == null || property == null) { throw new PropertyNotFoundException(MessageFactory.get( "error.unreachable.property", property)); } } property = this.children[i].getValue(ctx); if (property == null) { throw new PropertyNotFoundException(MessageFactory.get( "error.unreachable.property", this.children[i])); } Target t = new Target(); t.base = base; t.property = property; return t; }
// in java/org/apache/el/parser/AstValue.java
Override public Object getValue(EvaluationContext ctx) throws ELException { Object base = this.children[0].getValue(ctx); int propCount = this.jjtGetNumChildren(); int i = 1; Object suffix = null; ELResolver resolver = ctx.getELResolver(); while (base != null && i < propCount) { suffix = this.children[i].getValue(ctx); if (i + 1 < propCount && (this.children[i+1] instanceof AstMethodParameters)) { AstMethodParameters mps = (AstMethodParameters) this.children[i+1]; // This is a method base = resolver.invoke(ctx, base, suffix, null, mps.getParameters(ctx)); i+=2; } else { // This is a property if (suffix == null) { return null; } ctx.setPropertyResolved(false); base = resolver.getValue(ctx, base, suffix); i++; } } if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", base, suffix)); } return base; }
// in java/org/apache/el/parser/AstValue.java
Override public boolean isReadOnly(EvaluationContext ctx) throws ELException { Target t = getTarget(ctx); ctx.setPropertyResolved(false); boolean result = ctx.getELResolver().isReadOnly(ctx, t.base, t.property); if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", t.base, t.property)); } return result; }
// in java/org/apache/el/parser/AstValue.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { Target t = getTarget(ctx); ctx.setPropertyResolved(false); ELResolver resolver = ctx.getELResolver(); // coerce to the expected type Class<?> targetClass = resolver.getType(ctx, t.base, t.property); if (COERCE_TO_ZERO == true || !isAssignable(value, targetClass)) { resolver.setValue(ctx, t.base, t.property, ELSupport.coerceToType(value, targetClass)); } else { resolver.setValue(ctx, t.base, t.property, value); } if (!ctx.isPropertyResolved()) { throw new PropertyNotFoundException(MessageFactory.get( "error.resolver.unhandled", t.base, t.property)); } }
// in java/javax/el/ArrayELResolver.java
private static final void checkBounds(Object base, int idx) { if (idx < 0 || idx >= Array.getLength(base)) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } }
// in java/javax/el/BeanELResolver.java
private BeanProperty get(ELContext ctx, String name) { BeanProperty property = this.properties.get(name); if (property == null) { throw new PropertyNotFoundException(message(ctx, "propertyNotFound", new Object[] { type.getName(), name })); } return property; }
// in java/javax/el/BeanELResolver.java
private Method write(ELContext ctx) { if (this.write == null) { this.write = getMethod(this.owner, descriptor.getWriteMethod()); if (this.write == null) { throw new PropertyNotFoundException(message(ctx, "propertyNotWritable", new Object[] { type.getName(), descriptor.getName() })); } } return this.write; }
// in java/javax/el/BeanELResolver.java
private Method read(ELContext ctx) { if (this.read == null) { this.read = getMethod(this.owner, descriptor.getReadMethod()); if (this.read == null) { throw new PropertyNotFoundException(message(ctx, "propertyNotReadable", new Object[] { type.getName(), descriptor.getName() })); } } return this.read; }
// in java/javax/el/ListELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return Object.class; } return null; }
// in java/javax/el/ListELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); @SuppressWarnings("unchecked") // Must be OK to cast to Object List<Object> list = (List<Object>) base; if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); try { list.set(idx, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); } } }
// in java/javax/el/ListELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return this.readOnly || UNMODIFIABLE.equals(list.getClass()); } return this.readOnly; }
1
            
// in java/javax/el/ListELResolver.java
catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); }
48
            
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { return this.variableResolver.resolveVariable(property .toString()); } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getValue(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { try { Object obj = this.variableResolver.resolveVariable(property .toString()); return (obj != null) ? obj.getClass() : null; } catch (javax.servlet.jsp.el.ELException e) { throw new ELException(e.getMessage(), e.getCause()); } } } if (!context.isPropertyResolved()) { return elResolver.getType(context, base, property); } return null; }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); throw new PropertyNotWritableException( "Legacy VariableResolver wrapped, not writable"); } if (!context.isPropertyResolved()) { elResolver.setValue(context, base, property, value); } }
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return true; } return elResolver.isReadOnly(context, base, property); }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public MethodInfo getMethodInfo(ELContext context) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.getMethodInfo(context); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspMethodExpression.java
Override public Object invoke(ELContext context, Object[] params) throws NullPointerException, PropertyNotFoundException, MethodNotFoundException, ELException { try { return this.target.invoke(context, params); } catch (MethodNotFoundException e) { if (e instanceof JspMethodNotFoundException) throw e; throw new JspMethodNotFoundException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Class<?> getType(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getType(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public boolean isReadOnly(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.isReadOnly(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void setValue(ELContext context, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { try { this.target.setValue(context, value); } catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public Object getValue(ELContext context) throws NullPointerException, PropertyNotFoundException, ELException { try { return this.target.getValue(context); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/el/MethodExpressionImpl.java
Override public MethodInfo getMethodInfo(ELContext context) throws PropertyNotFoundException, MethodNotFoundException, ELException { Node n = this.getNode(); EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return n.getMethodInfo(ctx, this.paramTypes); }
// in java/org/apache/el/MethodExpressionImpl.java
Override public Object invoke(ELContext context, Object[] params) throws PropertyNotFoundException, MethodNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return this.getNode().invoke(ctx, this.paramTypes, params); }
// in java/org/apache/el/ValueExpressionImpl.java
Override public Class<?> getType(ELContext context) throws PropertyNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return this.getNode().getType(ctx); }
// in java/org/apache/el/ValueExpressionImpl.java
Override public Object getValue(ELContext context) throws PropertyNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); Object value = this.getNode().getValue(ctx); if (this.expectedType != null) { return ELSupport.coerceToType(value, this.expectedType); } return value; }
// in java/org/apache/el/ValueExpressionImpl.java
Override public boolean isReadOnly(ELContext context) throws PropertyNotFoundException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); return this.getNode().isReadOnly(ctx); }
// in java/org/apache/el/ValueExpressionImpl.java
Override public void setValue(ELContext context, Object value) throws PropertyNotFoundException, PropertyNotWritableException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); this.getNode().setValue(ctx, value); }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { PageContext page = (PageContext) context .getContext(JspContext.class); context.setPropertyResolved(true); switch (idx) { case APPLICATIONSCOPE: return ScopeManager.get(page).getApplicationScope(); case COOKIE: return ScopeManager.get(page).getCookie(); case HEADER: return ScopeManager.get(page).getHeader(); case HEADERVALUES: return ScopeManager.get(page).getHeaderValues(); case INITPARAM: return ScopeManager.get(page).getInitParam(); case PAGECONTEXT: return ScopeManager.get(page).getPageContext(); case PAGESCOPE: return ScopeManager.get(page).getPageScope(); case PARAM: return ScopeManager.get(page).getParam(); case PARAM_VALUES: return ScopeManager.get(page).getParamValues(); case REQUEST_SCOPE: return ScopeManager.get(page).getRequestScope(); case SESSION_SCOPE: return ScopeManager.get(page).getSessionScope(); } } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
public Class getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); } } return null; }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); throw new PropertyNotWritableException(); } } }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); return true; } } return false; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); return page.findAttribute(key); } } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public Class<Object> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); int scope = page.getAttributesScope(key); if (scope != 0) { page.setAttribute(key, value, scope); } else { page.setAttribute(key, value); } } } }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); } return false; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); if (property != null) { try { return ((ResourceBundle) base).getObject(property .toString()); } catch (MissingResourceException mre) { return "???" + property.toString() + "???"; } } } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return null; }
// in java/javax/el/ResourceBundleELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } }
// in java/javax/el/ResourceBundleELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return true; }
// in java/javax/el/CompositeELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; Object result = null; for (int i = 0; i < sz; i++) { result = this.resolvers[i].getValue(context, base, property); if (context.isPropertyResolved()) { return result; } } return null; }
// in java/javax/el/CompositeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { context.setPropertyResolved(false); int sz = this.size; for (int i = 0; i < sz; i++) { this.resolvers[i].setValue(context, base, property, value); if (context.isPropertyResolved()) { return; } } }
// in java/javax/el/CompositeELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; boolean readOnly = false; for (int i = 0; i < sz; i++) { readOnly = this.resolvers[i].isReadOnly(context, base, property); if (context.isPropertyResolved()) { return readOnly; } } return false; }
// in java/javax/el/CompositeELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { context.setPropertyResolved(false); int sz = this.size; Class<?> type; for (int i = 0; i < sz; i++) { type = this.resolvers[i].getType(context, base, property); if (context.isPropertyResolved()) { if (SCOPED_ATTRIBUTE_EL_RESOLVER != null && SCOPED_ATTRIBUTE_EL_RESOLVER.isAssignableFrom( resolvers[i].getClass())) { // Special case since // javax.servlet.jsp.el.ScopedAttributeELResolver will // always return Object.class for type Object value = resolvers[i].getValue(context, base, property); if (value != null) { return value.getClass(); } } return type; } } return null; }
// in java/javax/el/ArrayELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); if (idx < 0 || idx >= Array.getLength(base)) { return null; } return Array.get(base, idx); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); return base.getClass().getComponentType(); } return null; }
// in java/javax/el/ArrayELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); checkBounds(base, idx); if (value != null && !base.getClass().getComponentType().isAssignableFrom( value.getClass())) { throw new ClassCastException(message(context, "objectNotAssignable", new Object[] {value.getClass().getName(), base.getClass().getComponentType().getName()})); } Array.set(base, idx, value); } }
// in java/javax/el/ArrayELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); int idx = coerce(property); checkBounds(base, idx); } return this.readOnly; }
// in java/javax/el/MapELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return ((Map<?,?>) base).get(property); } return null; }
// in java/javax/el/MapELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?,?>) { context.setPropertyResolved(true); return Object.class; } return null; }
// in java/javax/el/MapELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } try { @SuppressWarnings("unchecked") // Must be OK Map<Object, Object> map = ((Map<Object, Object>) base); map.put(property, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } } }
// in java/javax/el/MapELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); return this.readOnly || UNMODIFIABLE.equals(base.getClass()); } return this.readOnly; }
// in java/javax/el/BeanELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); Method m = this.property(context, base, property).read(context); try { return m.invoke(base, (Object[]) null); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyReadError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return null; } context.setPropertyResolved(true); return this.property(context, base, property).getPropertyType(); }
// in java/javax/el/BeanELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return; } context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } Method m = this.property(context, base, property).write(context); try { m.invoke(base, value); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/BeanELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return false; } context.setPropertyResolved(true); return this.readOnly || this.property(context, base, property).isReadOnly(); }
// in java/javax/el/ListELResolver.java
Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { return null; } return list.get(idx); } return null; }
// in java/javax/el/ListELResolver.java
Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return Object.class; } return null; }
// in java/javax/el/ListELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); @SuppressWarnings("unchecked") // Must be OK to cast to Object List<Object> list = (List<Object>) base; if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); try { list.set(idx, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); } } }
// in java/javax/el/ListELResolver.java
Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return this.readOnly || UNMODIFIABLE.equals(list.getClass()); } return this.readOnly; }
6
            
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
12
            
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspMethodExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); }
6
runtime (Domain) PropertyNotWritableException
public class PropertyNotWritableException extends ELException {

    private static final long serialVersionUID = 827987155471214717L;

    /**
     *
     */
    public PropertyNotWritableException() {
        super();
    }

    /**
     * @param message
     */
    public PropertyNotWritableException(String message) {
        super(message);
    }

    /**
     * @param message
     * @param cause
     */
    public PropertyNotWritableException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * @param cause
     */
    public PropertyNotWritableException(Throwable cause) {
        super(cause);
    }
}
11
            
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); throw new PropertyNotWritableException( "Legacy VariableResolver wrapped, not writable"); } if (!context.isPropertyResolved()) { elResolver.setValue(context, base, property, value); } }
// in java/org/apache/el/parser/SimpleNode.java
Override public void setValue(EvaluationContext ctx, Object value) throws ELException { throw new PropertyNotWritableException(MessageFactory.get("error.syntax.set")); }
// in java/org/apache/el/ValueExpressionLiteral.java
Override public void setValue(ELContext context, Object value) { throw new PropertyNotWritableException(MessageFactory.get( "error.value.literal.write", this.value)); }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); throw new PropertyNotWritableException(); } } }
// in java/javax/el/ResourceBundleELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } }
// in java/javax/el/ArrayELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); checkBounds(base, idx); if (value != null && !base.getClass().getComponentType().isAssignableFrom( value.getClass())) { throw new ClassCastException(message(context, "objectNotAssignable", new Object[] {value.getClass().getName(), base.getClass().getComponentType().getName()})); } Array.set(base, idx, value); } }
// in java/javax/el/MapELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } try { @SuppressWarnings("unchecked") // Must be OK Map<Object, Object> map = ((Map<Object, Object>) base); map.put(property, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } } }
// in java/javax/el/BeanELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return; } context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } Method m = this.property(context, base, property).write(context); try { m.invoke(base, value); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/ListELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); @SuppressWarnings("unchecked") // Must be OK to cast to Object List<Object> list = (List<Object>) base; if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); try { list.set(idx, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); } } }
2
            
// in java/javax/el/MapELResolver.java
catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); }
// in java/javax/el/ListELResolver.java
catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); }
11
            
// in java/org/apache/jasper/el/ELResolverImpl.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); throw new PropertyNotWritableException( "Legacy VariableResolver wrapped, not writable"); } if (!context.isPropertyResolved()) { elResolver.setValue(context, base, property, value); } }
// in java/org/apache/jasper/el/JspValueExpression.java
Override public void setValue(ELContext context, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { try { this.target.setValue(context, value); } catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); } catch (PropertyNotFoundException e) { if (e instanceof JspPropertyNotFoundException) throw e; throw new JspPropertyNotFoundException(this.mark, e); } catch (ELException e) { if (e instanceof JspELException) throw e; throw new JspELException(this.mark, e); } }
// in java/org/apache/el/ValueExpressionImpl.java
Override public void setValue(ELContext context, Object value) throws PropertyNotFoundException, PropertyNotWritableException, ELException { EvaluationContext ctx = new EvaluationContext(context, this.fnMapper, this.varMapper); this.getNode().setValue(ctx, value); }
// in java/javax/servlet/jsp/el/ImplicitObjectELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(true); throw new PropertyNotWritableException(); } } }
// in java/javax/servlet/jsp/el/ScopedAttributeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null) { context.setPropertyResolved(true); if (property != null) { String key = property.toString(); PageContext page = (PageContext) context .getContext(JspContext.class); int scope = page.getAttributesScope(key); if (scope != 0) { page.setAttribute(key, value, scope); } else { page.setAttribute(key, value); } } } }
// in java/javax/el/ResourceBundleELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } }
// in java/javax/el/CompositeELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { context.setPropertyResolved(false); int sz = this.size; for (int i = 0; i < sz; i++) { this.resolvers[i].setValue(context, base, property, value); if (context.isPropertyResolved()) { return; } } }
// in java/javax/el/ArrayELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base != null && base.getClass().isArray()) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); checkBounds(base, idx); if (value != null && !base.getClass().getComponentType().isAssignableFrom( value.getClass())) { throw new ClassCastException(message(context, "objectNotAssignable", new Object[] {value.getClass().getName(), base.getClass().getComponentType().getName()})); } Array.set(base, idx, value); } }
// in java/javax/el/MapELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof Map<?, ?>) { context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } try { @SuppressWarnings("unchecked") // Must be OK Map<Object, Object> map = ((Map<Object, Object>) base); map.put(property, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } } }
// in java/javax/el/BeanELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base == null || property == null) { return; } context.setPropertyResolved(true); if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } Method m = this.property(context, base, property).write(context); try { m.invoke(base, value); } catch (IllegalAccessException e) { throw new ELException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } throw new ELException(message(context, "propertyWriteError", new Object[] { base.getClass().getName(), property.toString() }), cause); } catch (Exception e) { throw new ELException(e); } }
// in java/javax/el/ListELResolver.java
Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof List<?>) { context.setPropertyResolved(true); @SuppressWarnings("unchecked") // Must be OK to cast to Object List<Object> list = (List<Object>) base; if (this.readOnly) { throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } int idx = coerce(property); try { list.set(idx, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); } } }
1
            
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); }
2
            
// in java/org/apache/jasper/el/JspValueExpression.java
catch (PropertyNotWritableException e) { if (e instanceof JspPropertyNotWritableException) throw e; throw new JspPropertyNotWritableException(this.mark, e); }
1
unknown (Lib) ReflectionException 4
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
Method getGetter(String aname, BaseModelMBean mbean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); // Look up the actual operation to be used if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname + " for " + resource); String getMethod = attrInfo.getGetMethod(); if (getMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " get method name"); Object object = null; NoSuchMethodException exception = null; try { object = mbean; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find getter method " + getMethod); return m; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getSetter(String aname, BaseModelMBean bean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname); // Look up the actual operation to be used String setMethod = attrInfo.getSetMethod(); if (setMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " set method name"); String argType=attrInfo.getType(); Class<?> signature[] = new Class[] { BaseModelMBean.getAttributeClass( argType ) }; Object object = null; NoSuchMethodException exception = null; try { object = bean; m = object.getClass().getMethod(setMethod, signature); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(setMethod, signature); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find setter method " + setMethod + " " + resource); return m; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getInvoke(String aname, Object[] params, String[] signature, BaseModelMBean bean, Object resource) throws MBeanException, ReflectionException { Method method = null; if (params == null) params = new Object[0]; if (signature == null) signature = new String[0]; if (params.length != signature.length) throw new RuntimeOperationsException( new IllegalArgumentException( "Inconsistent arguments and signature"), "Inconsistent arguments and signature"); // Acquire the ModelMBeanOperationInfo information for // the requested operation OperationInfo opInfo = operations.get(aname); if (opInfo == null) throw new MBeanException(new ServiceNotFoundException( "Cannot find operation " + aname), "Cannot find operation " + aname); // Prepare the signature required by Java reflection APIs // FIXME - should we use the signature from opInfo? Class<?> types[] = new Class[signature.length]; for (int i = 0; i < signature.length; i++) { types[i] = BaseModelMBean.getAttributeClass(signature[i]); } // Locate the method to be invoked, either in this MBean itself // or in the corresponding managed resource // FIXME - Accessible methods in superinterfaces? Object object = null; Exception exception = null; try { object = bean; method = object.getClass().getMethod(aname, types); } catch (NoSuchMethodException e) { exception = e; } try { if ((method == null) && (resource != null)) { object = resource; method = object.getClass().getMethod(aname, types); } } catch (NoSuchMethodException e) { exception = e; } if (method == null) { throw new ReflectionException(exception, "Cannot find method " + aname + " with this signature"); } return method; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
static Class<?> getAttributeClass(String signature) throws ReflectionException { if (signature.equals(Boolean.TYPE.getName())) return Boolean.TYPE; else if (signature.equals(Byte.TYPE.getName())) return Byte.TYPE; else if (signature.equals(Character.TYPE.getName())) return Character.TYPE; else if (signature.equals(Double.TYPE.getName())) return Double.TYPE; else if (signature.equals(Float.TYPE.getName())) return Float.TYPE; else if (signature.equals(Integer.TYPE.getName())) return Integer.TYPE; else if (signature.equals(Long.TYPE.getName())) return Long.TYPE; else if (signature.equals(Short.TYPE.getName())) return Short.TYPE; else { try { ClassLoader cl=Thread.currentThread().getContextClassLoader(); if( cl!=null ) return cl.loadClass(signature); } catch( ClassNotFoundException e ) { } try { return Class.forName(signature); } catch (ClassNotFoundException e) { throw new ReflectionException (e, "Cannot find Class for " + signature); } } }
1
            
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (ClassNotFoundException e) { throw new ReflectionException (e, "Cannot find Class for " + signature); }
14
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
Method getGetter(String aname, BaseModelMBean mbean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); // Look up the actual operation to be used if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname + " for " + resource); String getMethod = attrInfo.getGetMethod(); if (getMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " get method name"); Object object = null; NoSuchMethodException exception = null; try { object = mbean; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(getMethod, NO_ARGS_PARAM_SIG); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find getter method " + getMethod); return m; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getSetter(String aname, BaseModelMBean bean, Object resource) throws AttributeNotFoundException, ReflectionException { Method m = null; AttributeInfo attrInfo = attributes.get(aname); if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname); // Look up the actual operation to be used String setMethod = attrInfo.getSetMethod(); if (setMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " set method name"); String argType=attrInfo.getType(); Class<?> signature[] = new Class[] { BaseModelMBean.getAttributeClass( argType ) }; Object object = null; NoSuchMethodException exception = null; try { object = bean; m = object.getClass().getMethod(setMethod, signature); } catch (NoSuchMethodException e) { exception = e; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(setMethod, signature); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find setter method " + setMethod + " " + resource); return m; }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getInvoke(String aname, Object[] params, String[] signature, BaseModelMBean bean, Object resource) throws MBeanException, ReflectionException { Method method = null; if (params == null) params = new Object[0]; if (signature == null) signature = new String[0]; if (params.length != signature.length) throw new RuntimeOperationsException( new IllegalArgumentException( "Inconsistent arguments and signature"), "Inconsistent arguments and signature"); // Acquire the ModelMBeanOperationInfo information for // the requested operation OperationInfo opInfo = operations.get(aname); if (opInfo == null) throw new MBeanException(new ServiceNotFoundException( "Cannot find operation " + aname), "Cannot find operation " + aname); // Prepare the signature required by Java reflection APIs // FIXME - should we use the signature from opInfo? Class<?> types[] = new Class[signature.length]; for (int i = 0; i < signature.length; i++) { types[i] = BaseModelMBean.getAttributeClass(signature[i]); } // Locate the method to be invoked, either in this MBean itself // or in the corresponding managed resource // FIXME - Accessible methods in superinterfaces? Object object = null; Exception exception = null; try { object = bean; method = object.getClass().getMethod(aname, types); } catch (NoSuchMethodException e) { exception = e; } try { if ((method == null) && (resource != null)) { object = resource; method = object.getClass().getMethod(aname, types); } } catch (NoSuchMethodException e) { exception = e; } if (method == null) { throw new ReflectionException(exception, "Cannot find method " + aname + " with this signature"); } return method; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).getAttribute(name); } Method m=managedBean.getGetter(name, this, resource); Object result = null; try { Class<?> declaring = m.getDeclaringClass(); // workaround for catalina weird mbeans - the declaring class is BaseModelMBean. // but this is the catalina class. if( declaring.isAssignableFrom(this.getClass()) ) { result = m.invoke(this, NO_ARGS_PARAM ); } else { result = m.invoke(resource, NO_ARGS_PARAM ); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object invoke(String name, Object params[], String signature[]) throws MBeanException, ReflectionException { if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).invoke(name, params, signature); } // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Method name is null"), "Method name is null"); if( log.isDebugEnabled()) log.debug("Invoke " + name); Method method= managedBean.getInvoke(name, params, signature, this, resource); // Invoke the selected method on the appropriate object Object result = null; try { if( method.getDeclaringClass().isAssignableFrom( this.getClass()) ) { result = method.invoke(this, params ); } else { result = method.invoke(resource, params); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
static Class<?> getAttributeClass(String signature) throws ReflectionException { if (signature.equals(Boolean.TYPE.getName())) return Boolean.TYPE; else if (signature.equals(Byte.TYPE.getName())) return Byte.TYPE; else if (signature.equals(Character.TYPE.getName())) return Character.TYPE; else if (signature.equals(Double.TYPE.getName())) return Double.TYPE; else if (signature.equals(Float.TYPE.getName())) return Float.TYPE; else if (signature.equals(Integer.TYPE.getName())) return Integer.TYPE; else if (signature.equals(Long.TYPE.getName())) return Long.TYPE; else if (signature.equals(Short.TYPE.getName())) return Short.TYPE; else { try { ClassLoader cl=Thread.currentThread().getContextClassLoader(); if( cl!=null ) return cl.loadClass(signature); } catch( ClassNotFoundException e ) { } try { return Class.forName(signature); } catch (ClassNotFoundException e) { throw new ReflectionException (e, "Cannot find Class for " + signature); } } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if( log.isDebugEnabled() ) log.debug("Setting attribute " + this + " " + attribute ); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { try { ((DynamicMBean)resource).setAttribute(attribute); } catch (InvalidAttributeValueException e) { throw new MBeanException(e); } return; } // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); Object oldValue=null; //if( getAttMap.get(name) != null ) // oldValue=getAttribute( name ); Method m=managedBean.getSetter(name,this,resource); try { if( m.getDeclaringClass().isAssignableFrom( this.getClass()) ) { m.invoke(this, new Object[] { value }); } else { m.invoke(resource, new Object[] { value }); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } try { sendAttributeChangeNotification(new Attribute( name, oldValue), attribute); } catch(Exception ex) { log.error("Error sending notification " + name, ex); } //attributes.put( name, value ); // if( source != null ) { // // this mbean is associated with a source - maybe we want to persist // source.updateField(oname, name, value); // } }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); Object result = null; try { Connector connector = (Connector) getManagedResource(); result = IntrospectionUtils.getProperty(connector, name); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return result; }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); try { Connector connector = (Connector) getManagedResource(); IntrospectionUtils.setProperty(connector, name, String.valueOf(value)); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("auth".equals(name)) { return (cr.getAuth()); } else if ("description".equals(name)) { return (cr.getDescription()); } else if ("name".equals(name)) { return (cr.getName()); } else if ("scope".equals(name)) { return (cr.getScope()); } else if ("type".equals(name)) { return (cr.getType()); } else { value = (String) cr.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("auth".equals(name)) { cr.setAuth((String)value); } else if ("description".equals(name)) { cr.setDescription((String)value); } else if ("name".equals(name)) { cr.setName((String)value); } else if ("scope".equals(name)) { cr.setScope((String)value); } else if ("type".equals(name)) { cr.setType((String)value); } else { cr.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = cr.getNamingResources(); nr.removeResource(cr.getName()); nr.addResource(cr); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink cl = null; try { cl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("global".equals(name)) { return (cl.getGlobal()); } else if ("description".equals(name)) { return (cl.getDescription()); } else if ("name".equals(name)) { return (cl.getName()); } else if ("type".equals(name)) { return (cl.getType()); } else { value = (String) cl.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink crl = null; try { crl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("global".equals(name)) { crl.setGlobal((String)value); } else if ("description".equals(name)) { crl.setDescription((String)value); } else if ("name".equals(name)) { crl.setName((String)value); } else if ("type".equals(name)) { crl.setType((String)value); } else { crl.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = crl.getNamingResources(); nr.removeResourceLink(crl.getName()); nr.addResourceLink(crl); }
// in java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { super.setAttribute(attribute); ContextEnvironment ce = null; try { ce = (ContextEnvironment) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = ce.getNamingResources(); nr.removeEnvironment(ce.getName()); nr.addEnvironment(ce); }
0 0 0
unknown (Lib) RejectedExecutionException 6
            
// in java/org/apache/tomcat/util/threads/TaskQueue.java
public boolean force(Runnable o) { if ( parent.isShutdown() ) throw new RejectedExecutionException("Executor not running, can't force a command into the queue"); return super.offer(o); //forces the item onto the queue, to be used if the task is rejected }
// in java/org/apache/tomcat/util/threads/TaskQueue.java
public boolean force(Runnable o, long timeout, TimeUnit unit) throws InterruptedException { if ( parent.isShutdown() ) throw new RejectedExecutionException("Executor not running, can't force a command into the queue"); return super.offer(o,timeout,unit); //forces the item onto the queue, to be used if the task is rejected }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
public void execute(Runnable command, long timeout, TimeUnit unit) { submittedCount.incrementAndGet(); try { super.execute(command); } catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } } }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
Override public void rejectedExecution(Runnable r, java.util.concurrent.ThreadPoolExecutor executor) { throw new RejectedExecutionException(); }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
Override public void execute(Runnable command) { if ( executor != null ) { try { executor.execute(command); } catch (RejectedExecutionException rx) { //there could have been contention around the queue if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException("Work queue full."); } } else throw new IllegalStateException("StandardThreadPool not started."); }
3
            
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
catch (RejectedExecutionException rx) { //there could have been contention around the queue if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException("Work queue full."); }
0 9
            
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (RejectedExecutionException rx) { log.warn("Socket processing request was rejected for:"+socket,rx); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for: "+socket, x); return false; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket reprocessing request was rejected for:"+socket,x); try { //unable to handle connection at this time handler.process(socket, SocketStatus.DISCONNECT); } finally { countDownConnection(); } }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); return false; }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
catch (RejectedExecutionException rx) { //there could have been contention around the queue if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException("Work queue full."); }
4
            
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } }
// in java/org/apache/catalina/core/StandardThreadExecutor.java
catch (RejectedExecutionException rx) { //there could have been contention around the queue if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException("Work queue full."); }
0
unknown (Lib) RemoteException 0 0 0 1
            
// in java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
catch (RemoteException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.createRegistryFailed", serverName, Integer.toString(theRmiRegistryPort)), e); return null; }
0 0
runtime (Domain) RemoteProcessException
public class RemoteProcessException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    public RemoteProcessException() {
        super();
    }

    public RemoteProcessException(String message) {
        super(message);
    }

    public RemoteProcessException(String message, Throwable cause) {
        super(message, cause);
    }

    public RemoteProcessException(Throwable cause) {
        super(cause);
    }

}
3
            
// in java/org/apache/catalina/tribes/group/GroupChannel.java
Override public void messageReceived(ChannelMessage msg) { if ( msg == null ) return; try { if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("GroupChannel - Received msg:" + new UniqueId(msg.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " from "+msg.getAddress().getName()); } Serializable fwd = null; if ( (msg.getOptions() & SEND_OPTIONS_BYTE_MESSAGE) == SEND_OPTIONS_BYTE_MESSAGE ) { fwd = new ByteMessage(msg.getMessage().getBytes()); } else { try { fwd = XByteBuffer.deserialize(msg.getMessage().getBytesDirect(), 0, msg.getMessage().getLength()); }catch (Exception sx) { log.error("Unable to deserialize message:"+msg,sx); return; } } if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("GroupChannel - Receive Message:" + new UniqueId(msg.getUniqueId()) + " is " +fwd); } //get the actual member with the correct alive time Member source = msg.getAddress(); boolean rx = false; boolean delivered = false; for ( int i=0; i<channelListeners.size(); i++ ) { ChannelListener channelListener = (ChannelListener)channelListeners.get(i); if (channelListener != null && channelListener.accept(fwd, source)) { channelListener.messageReceived(fwd, source); delivered = true; //if the message was accepted by an RPC channel, that channel //is responsible for returning the reply, otherwise we send an absence reply if ( channelListener instanceof RpcChannel ) rx = true; } }//for if ((!rx) && (fwd instanceof RpcMessage)) { //if we have a message that requires a response, //but none was given, send back an immediate one sendNoRpcChannelReply((RpcMessage)fwd,source); } if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("GroupChannel delivered["+delivered+"] id:"+new UniqueId(msg.getUniqueId())); } } catch ( Exception x ) { //this could be the channel listener throwing an exception, we should log it //as a warning. if ( log.isWarnEnabled() ) log.warn("Error receiving message:",x); throw new RemoteProcessException("Exception:"+x.getMessage(),x); } }
// in java/org/apache/catalina/tribes/transport/bio/BioSender.java
protected void waitForAck() throws java.io.IOException { try { boolean ackReceived = false; boolean failAckReceived = false; ackbuf.clear(); int bytesRead = 0; int i = soIn.read(); while ((i != -1) && (bytesRead < Constants.ACK_COMMAND.length)) { bytesRead++; byte d = (byte)i; ackbuf.append(d); if (ackbuf.doesPackageExist() ) { byte[] ackcmd = ackbuf.extractDataPackage(true).getBytes(); ackReceived = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.ACK_DATA); failAckReceived = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA); ackReceived = ackReceived || failAckReceived; break; } i = soIn.read(); } if (!ackReceived) { if (i == -1) throw new IOException(sm.getString("IDataSender.ack.eof",getAddress(), new Integer(socket.getLocalPort()))); else throw new IOException(sm.getString("IDataSender.ack.wrong",getAddress(), new Integer(socket.getLocalPort()))); } else if ( failAckReceived && getThrowOnFailedAck()) { throw new RemoteProcessException("Received a failed ack:org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA"); } } catch (IOException x) { String errmsg = sm.getString("IDataSender.ack.missing", getAddress(),new Integer(socket.getLocalPort()), new Long(getTimeout())); if ( SenderState.getSenderState(getDestination()).isReady() ) { SenderState.getSenderState(getDestination()).setSuspect(); if ( log.isWarnEnabled() ) log.warn(errmsg, x); } else { if ( log.isDebugEnabled() )log.debug(errmsg, x); } throw x; } finally { ackbuf.clear(); } }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
protected boolean read() throws IOException { //if there is no message here, we are done if ( current == null ) return true; int read = isUdpBased()?dataChannel.read(readbuf) : socketChannel.read(readbuf); //end of stream if ( read == -1 ) throw new IOException("Unable to receive an ack message. EOF on socket channel has been reached."); //no data read else if ( read == 0 ) return false; readbuf.flip(); ackbuf.append(readbuf,read); readbuf.clear(); if (ackbuf.doesPackageExist() ) { byte[] ackcmd = ackbuf.extractDataPackage(true).getBytes(); boolean ack = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.ACK_DATA); boolean fack = Arrays.equals(ackcmd,org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA); if ( fack && getThrowOnFailedAck() ) throw new RemoteProcessException("Received a failed ack:org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA"); return ack || fack; } else { return false; } }
1
            
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Exception x ) { //this could be the channel listener throwing an exception, we should log it //as a warning. if ( log.isWarnEnabled() ) log.warn("Error receiving message:",x); throw new RemoteProcessException("Exception:"+x.getMessage(),x); }
0 1
            
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( RemoteProcessException e ) { if ( log.isDebugEnabled() ) log.error("Processing of cluster message failed.",e); if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,Constants.FAIL_ACK_COMMAND,saddr); }
0 0
unknown (Lib) RuntimeErrorException 3
            
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).getAttribute(name); } Method m=managedBean.getGetter(name, this, resource); Object result = null; try { Class<?> declaring = m.getDeclaringClass(); // workaround for catalina weird mbeans - the declaring class is BaseModelMBean. // but this is the catalina class. if( declaring.isAssignableFrom(this.getClass()) ) { result = m.invoke(this, NO_ARGS_PARAM ); } else { result = m.invoke(resource, NO_ARGS_PARAM ); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object invoke(String name, Object params[], String signature[]) throws MBeanException, ReflectionException { if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).invoke(name, params, signature); } // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Method name is null"), "Method name is null"); if( log.isDebugEnabled()) log.debug("Invoke " + name); Method method= managedBean.getInvoke(name, params, signature, this, resource); // Invoke the selected method on the appropriate object Object result = null; try { if( method.getDeclaringClass().isAssignableFrom( this.getClass()) ) { result = method.invoke(this, params ); } else { result = method.invoke(resource, params); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if( log.isDebugEnabled() ) log.debug("Setting attribute " + this + " " + attribute ); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { try { ((DynamicMBean)resource).setAttribute(attribute); } catch (InvalidAttributeValueException e) { throw new MBeanException(e); } return; } // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); Object oldValue=null; //if( getAttMap.get(name) != null ) // oldValue=getAttribute( name ); Method m=managedBean.getSetter(name,this,resource); try { if( m.getDeclaringClass().isAssignableFrom( this.getClass()) ) { m.invoke(this, new Object[] { value }); } else { m.invoke(resource, new Object[] { value }); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } try { sendAttributeChangeNotification(new Attribute( name, oldValue), attribute); } catch(Exception ex) { log.error("Error sending notification " + name, ex); } //attributes.put( name, value ); // if( source != null ) { // // this mbean is associated with a source - maybe we want to persist // source.updateField(oname, name, value); // } }
3
            
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
0 0 0 0
runtime (Lib) RuntimeException 48
            
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
public void mapFunction(String fnQName, final Class<?> c, final String methodName, final Class<?>[] args) { java.lang.reflect.Method method; if (SecurityUtil.isPackageProtectionEnabled()) { try { method = AccessController.doPrivileged( new PrivilegedExceptionAction<Method>() { @Override public Method run() throws Exception { return c.getDeclaredMethod(methodName, args); } }); } catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); } }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
public static ProtectedFunctionMapper getMapForFunction(String fnQName, final Class<?> c, final String methodName, final Class<?>[] args) { java.lang.reflect.Method method; ProtectedFunctionMapper funcMapper; if (SecurityUtil.isPackageProtectionEnabled()) { funcMapper = AccessController.doPrivileged( new PrivilegedAction<ProtectedFunctionMapper>() { @Override public ProtectedFunctionMapper run() { return new ProtectedFunctionMapper(); } }); try { method = AccessController.doPrivileged( new PrivilegedExceptionAction<Method>() { @Override public Method run() throws Exception { return c.getDeclaredMethod(methodName, args); } }); } catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); } }
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
Override public TagFileInfo getTagFile(String shortName) { TagFileInfo tagFile = super.getTagFile(shortName); if (tagFile == null) { String path = tagFileMap.get(shortName); if (path == null) { return null; } TagInfo tagInfo = null; try { tagInfo = TagFileProcessor.parseTagFileDirectives(pc, shortName, path, pc.getJspCompilationContext().getTagFileJarResource(path), this); } catch (JasperException je) { throw new RuntimeException(je.toString(), je); } tagFile = new TagFileInfo(shortName, path, tagInfo); vec.addElement(tagFile); this.tagFiles = new TagFileInfo[vec.size()]; vec.copyInto(this.tagFiles); } return tagFile; }
// in java/org/apache/jasper/compiler/JarURLResource.java
Override public URL getEntry(String name) { try { return new URL("jar:" + jarUrl + "!/" + name); } catch (MalformedURLException e) { throw new RuntimeException("", e); } }
// in java/org/apache/jasper/JspC.java
protected void initClassLoader(JspCompilationContext clctxt) throws IOException { classPath = getClassPath(); ClassLoader jspcLoader = getClass().getClassLoader(); if (jspcLoader instanceof AntClassLoader) { classPath += File.pathSeparator + ((AntClassLoader) jspcLoader).getClasspath(); } // Turn the classPath into URLs ArrayList<URL> urls = new ArrayList<URL>(); StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { String path = tokenizer.nextToken(); try { File libFile = new File(path); urls.add(libFile.toURI().toURL()); } catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); } } File webappBase = new File(uriRoot); if (webappBase.exists()) { File classes = new File(webappBase, "/WEB-INF/classes"); try { if (classes.exists()) { classPath = classPath + File.pathSeparator + classes.getCanonicalPath(); urls.add(classes.getCanonicalFile().toURI().toURL()); } } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } File lib = new File(webappBase, "/WEB-INF/lib"); if (lib.exists() && lib.isDirectory()) { String[] libs = lib.list(); for (int i = 0; i < libs.length; i++) { if( libs[i].length() <5 ) continue; String ext=libs[i].substring( libs[i].length() - 4 ); if (! ".jar".equalsIgnoreCase(ext)) { if (".tld".equalsIgnoreCase(ext)) { log.warn("TLD files should not be placed in " + "/WEB-INF/lib"); } continue; } try { File libFile = new File(lib, libs[i]); classPath = classPath + File.pathSeparator + libFile.getAbsolutePath(); urls.add(libFile.getAbsoluteFile().toURI().toURL()); } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } } } } // What is this ?? urls.add(new File( clctxt.getRealPath("/")).getCanonicalFile().toURI().toURL()); URL urlsA[]=new URL[urls.size()]; urls.toArray(urlsA); loader = new URLClassLoader(urlsA, this.getClass().getClassLoader()); }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
Override public Binding nextElement() { try { return nextElementInternal(); } catch (NamingException e) { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
public void setTicketKey(byte[] key48Bytes) { if(key48Bytes.length != 48) { throw new RuntimeException("Key must be 48 bytes"); } this.ticketKey = key48Bytes; }
// in java/org/apache/tomcat/spdy/SpdyFrame.java
public void headerName(byte[] buf, int soff, int len) { // if it's the first header, leave space for extra params and NV count. // they'll be filled in by send. if (off == 8) { if (type == SpdyConnection.TYPE_SYN_REPLY) { off = 16; } else if (type == SpdyConnection.TYPE_SYN_STREAM) { off = 20; } else if (type != SpdyConnection.TYPE_HEADERS) { off = 16; } else { throw new RuntimeException("Wrong frame type"); } } nvCount++; headerValue(buf, soff, len); }
// in java/org/apache/tomcat/spdy/SpdyContext.java
public NetSupport getNetSupport() { if (netSupport == null) { try { Class<?> c0 = Class.forName("org.apache.tomcat.spdy.NetSupportOpenSSL"); netSupport = (NetSupport) c0.newInstance(); netSupport.setSpdyContext(this); return netSupport; } catch (Throwable t) { // ignore, openssl not supported } try { Class<?> c1 = Class.forName("org.apache.tomcat.spdy.NetSupportJava7"); netSupport = (NetSupport) c1.newInstance(); netSupport.setSpdyContext(this); return netSupport; } catch (Throwable t) { // ignore, npn not supported } // non-ssl mode must be set explicitly throw new RuntimeException("SSL NextProtoclNegotiation no supported."); } return netSupport; }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
public void ReInit(java.io.InputStream stream, String encoding) { try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jjtree.reset(); jj_gen = 0; for (int i = 0; i < 2; i++) jj_la1[i] = -1; }
// in java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
protected void stopCurrentThreadIfNeeded() { if (currentThreadShouldBeStopped()) { long lastTime = lastTimeThreadKilledItself.longValue(); if (lastTime + threadRenewalDelay < System.currentTimeMillis()) { if (lastTimeThreadKilledItself.compareAndSet(lastTime, System.currentTimeMillis() + 1)) { // OK, it's really time to dispose of this thread final String msg = sm.getString( "threadPoolExecutor.threadStoppedToAvoidPotentialLeak", Thread.currentThread().getName()); Thread.currentThread().setUncaughtExceptionHandler( new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { // yes, swallow the exception log.debug(msg); } }); throw new RuntimeException(msg); } } }
// in java/org/apache/tomcat/util/bcel/classfile/ElementValue.java
public static ElementValue readElementValue(DataInputStream dis, ConstantPool cpool) throws IOException { byte type = dis.readByte(); switch (type) { case 'B': // byte return new SimpleElementValue(PRIMITIVE_BYTE, dis .readUnsignedShort(), cpool); case 'C': // char return new SimpleElementValue(PRIMITIVE_CHAR, dis .readUnsignedShort(), cpool); case 'D': // double return new SimpleElementValue(PRIMITIVE_DOUBLE, dis .readUnsignedShort(), cpool); case 'F': // float return new SimpleElementValue(PRIMITIVE_FLOAT, dis .readUnsignedShort(), cpool); case 'I': // int return new SimpleElementValue(PRIMITIVE_INT, dis .readUnsignedShort(), cpool); case 'J': // long return new SimpleElementValue(PRIMITIVE_LONG, dis .readUnsignedShort(), cpool); case 'S': // short return new SimpleElementValue(PRIMITIVE_SHORT, dis .readUnsignedShort(), cpool); case 'Z': // boolean return new SimpleElementValue(PRIMITIVE_BOOLEAN, dis .readUnsignedShort(), cpool); case 's': // String return new SimpleElementValue(STRING, dis.readUnsignedShort(), cpool); case 'e': // Enum constant return new EnumElementValue(ENUM_CONSTANT, dis.readUnsignedShort(), dis.readUnsignedShort(), cpool); case 'c': // Class return new ClassElementValue(CLASS, dis.readUnsignedShort(), cpool); case '@': // Annotation // TODO isRuntimeVisible return new AnnotationElementValue(ANNOTATION, AnnotationEntry.read( dis, cpool), cpool); case '[': // Array int numArrayVals = dis.readUnsignedShort(); ElementValue[] evalues = new ElementValue[numArrayVals]; for (int j = 0; j < numArrayVals; j++) { evalues[j] = ElementValue.readElementValue(dis, cpool); } return new ArrayElementValue(ARRAY, evalues, cpool); default: throw new RuntimeException( "Unexpected element value kind in annotation: " + type); } }
// in java/org/apache/tomcat/util/bcel/classfile/AnnotationDefault.java
Override public Attribute copy(ConstantPool _constant_pool) { throw new RuntimeException("Not implemented yet!"); }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public String constantToString( Constant c ) throws ClassFormatException { String str; int i; byte tag = c.getTag(); switch (tag) { case Constants.CONSTANT_Class: i = ((ConstantClass) c).getNameIndex(); c = getConstant(i, Constants.CONSTANT_Utf8); str = Utility.compactClassName(((ConstantUtf8) c).getBytes(), false); break; case Constants.CONSTANT_String: i = ((ConstantString) c).getStringIndex(); c = getConstant(i, Constants.CONSTANT_Utf8); str = "\"" + escape(((ConstantUtf8) c).getBytes()) + "\""; break; case Constants.CONSTANT_Utf8: str = ((ConstantUtf8) c).getBytes(); break; case Constants.CONSTANT_Double: str = String.valueOf(((ConstantDouble) c).getBytes()); break; case Constants.CONSTANT_Float: str = String.valueOf(((ConstantFloat) c).getBytes()); break; case Constants.CONSTANT_Long: str = String.valueOf(((ConstantLong) c).getBytes()); break; case Constants.CONSTANT_Integer: str = String.valueOf(((ConstantInteger) c).getBytes()); break; case Constants.CONSTANT_NameAndType: str = (constantToString(((ConstantNameAndType) c).getNameIndex(), Constants.CONSTANT_Utf8) + " " + constantToString(((ConstantNameAndType) c).getSignatureIndex(), Constants.CONSTANT_Utf8)); break; case Constants.CONSTANT_InterfaceMethodref: case Constants.CONSTANT_Methodref: case Constants.CONSTANT_Fieldref: str = (constantToString(((ConstantCP) c).getClassIndex(), Constants.CONSTANT_Class) + "." + constantToString(((ConstantCP) c).getNameAndTypeIndex(), Constants.CONSTANT_NameAndType)); break; default: // Never reached throw new RuntimeException("Unknown constant type " + tag); } return str; }
// in java/org/apache/tomcat/util/bcel/classfile/ConstantPool.java
public String getConstantString( int index, byte tag ) throws ClassFormatException { Constant c; int i; c = getConstant(index, tag); /* This switch() is not that elegant, since the two classes have the * same contents, they just differ in the name of the index * field variable. * But we want to stick to the JVM naming conventions closely though * we could have solved these more elegantly by using the same * variable name or by subclassing. */ switch (tag) { case Constants.CONSTANT_Class: i = ((ConstantClass) c).getNameIndex(); break; case Constants.CONSTANT_String: i = ((ConstantString) c).getStringIndex(); break; default: throw new RuntimeException("getConstantString called with illegal tag " + tag); } // Finally get the string from the constant pool c = getConstant(i, Constants.CONSTANT_Utf8); return ((ConstantUtf8) c).getBytes(); }
// in java/org/apache/tomcat/util/bcel/classfile/EnclosingMethod.java
Override public Attribute copy(ConstantPool constant_pool) { throw new RuntimeException("Not implemented yet!"); // is this next line sufficient? // return (EnclosingMethod)clone(); }
// in java/org/apache/tomcat/util/bcel/classfile/StackMapType.java
public void setType( byte t ) { if ((t < Constants.ITEM_Bogus) || (t > Constants.ITEM_NewObject)) { throw new RuntimeException("Illegal type for StackMapType: " + t); } type = t; }
// in java/org/apache/tomcat/util/bcel/classfile/SimpleElementValue.java
Override public String stringifyValue() { switch (type) { case PRIMITIVE_INT: ConstantInteger c = (ConstantInteger) cpool.getConstant(getIndex(), Constants.CONSTANT_Integer); return Integer.toString(c.getBytes()); case PRIMITIVE_LONG: ConstantLong j = (ConstantLong) cpool.getConstant(getIndex(), Constants.CONSTANT_Long); return Long.toString(j.getBytes()); case PRIMITIVE_DOUBLE: ConstantDouble d = (ConstantDouble) cpool.getConstant(getIndex(), Constants.CONSTANT_Double); return Double.toString(d.getBytes()); case PRIMITIVE_FLOAT: ConstantFloat f = (ConstantFloat) cpool.getConstant(getIndex(), Constants.CONSTANT_Float); return Float.toString(f.getBytes()); case PRIMITIVE_SHORT: ConstantInteger s = (ConstantInteger) cpool.getConstant(getIndex(), Constants.CONSTANT_Integer); return Integer.toString(s.getBytes()); case PRIMITIVE_BYTE: ConstantInteger b = (ConstantInteger) cpool.getConstant(getIndex(), Constants.CONSTANT_Integer); return Integer.toString(b.getBytes()); case PRIMITIVE_CHAR: ConstantInteger ch = (ConstantInteger) cpool.getConstant( getIndex(), Constants.CONSTANT_Integer); return String.valueOf((char)ch.getBytes()); case PRIMITIVE_BOOLEAN: ConstantInteger bo = (ConstantInteger) cpool.getConstant( getIndex(), Constants.CONSTANT_Integer); if (bo.getBytes() == 0) { return "false"; } return "true"; case STRING: ConstantUtf8 cu8 = (ConstantUtf8) cpool.getConstant(getIndex(), Constants.CONSTANT_Utf8); return cu8.getBytes(); default: throw new RuntimeException( "SimpleElementValue class does not know how to stringify type " + type); } }
// in java/org/apache/tomcat/util/bcel/classfile/SimpleElementValue.java
Override public void dump(DataOutputStream dos) throws IOException { dos.writeByte(type); // u1 kind of value switch (type) { case PRIMITIVE_INT: case PRIMITIVE_BYTE: case PRIMITIVE_CHAR: case PRIMITIVE_FLOAT: case PRIMITIVE_LONG: case PRIMITIVE_BOOLEAN: case PRIMITIVE_SHORT: case PRIMITIVE_DOUBLE: case STRING: dos.writeShort(getIndex()); break; default: throw new RuntimeException( "SimpleElementValue doesnt know how to write out type " + type); } }
// in java/org/apache/el/parser/ELParser.java
public void ReInit(java.io.InputStream stream, String encoding) { try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jjtree.reset(); jj_gen = 0; for (int i = 0; i < 36; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
protected static int[] commaDelimitedListToIntArray( String commaDelimitedInts) { String[] intsAsStrings = commaDelimitedListToStringArray(commaDelimitedInts); int[] ints = new int[intsAsStrings.length]; for (int i = 0; i < intsAsStrings.length; i++) { String intAsString = intsAsStrings[i]; try { ints[i] = Integer.parseInt(intAsString); } catch (NumberFormatException e) { throw new RuntimeException("Exception parsing number '" + i + "' (zero based) of comma delimited list '" + commaDelimitedInts + "'"); } } return ints; }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
Override public DataSender getNewDataSender() { try { ParallelNioSender sender = new ParallelNioSender(); AbstractSender.transferProperties(this,sender); return sender; } catch ( IOException x ) { throw new RuntimeException("Unable to open NIO selector.",x); } }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
protected void init(MapOwner owner, Channel channel, String mapContextName, long timeout, int channelSendOptions,ClassLoader[] cls) { log.info("Initializing AbstractReplicatedMap with context name:"+mapContextName); this.mapOwner = owner; this.externalLoaders = cls; this.channelSendOptions = channelSendOptions; this.channel = channel; this.rpcTimeout = timeout; this.mapname = mapContextName; //unique context is more efficient if it is stored as bytes this.mapContextName = mapContextName.getBytes(CHARSET_ISO_8859_1); if ( log.isTraceEnabled() ) log.trace("Created Lazy Map with name:"+mapContextName+", bytes:"+Arrays.toString(this.mapContextName)); //create an rpc channel and add the map as a listener this.rpcChannel = new RpcChannel(this.mapContextName, channel, this); //add this map as a message listener this.channel.addChannelListener(this); //listen for membership notifications this.channel.addMembershipListener(this); try { //broadcast our map, this just notifies other members of our existence broadcast(MapMessage.MSG_INIT, true); //transfer state from another map transferState(); //state is transferred, we are ready for messaging broadcast(MapMessage.MSG_START, true); } catch (ChannelException x) { log.warn("Unable to send map start message."); // remove listener from channel this.rpcChannel.breakdown(); this.channel.removeChannelListener(this); this.channel.removeMembershipListener(this); throw new RuntimeException("Unable to start replicated map.",x); } }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public void setValue(Serializable value) { try { if ( value != null ) valuedata = XByteBuffer.serialize(value); this.value = value; }catch ( IOException x ) { throw new RuntimeException(x); } }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
public void setKey(Serializable key) { try { if (key != null) keydata = XByteBuffer.serialize(key); this.key = key; } catch (IOException x) { throw new RuntimeException(x); } }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
public String getHostname() { if ( this.hostname != null ) return hostname; else { try { if (DO_DNS_LOOKUPS) this.hostname = java.net.InetAddress.getByAddress(host).getHostName(); else this.hostname = org.apache.catalina.tribes.util.Arrays.toString(host,0,host.length,true); return this.hostname; }catch ( IOException x ) { throw new RuntimeException("Unable to parse hostname.",x); } } }
// in java/org/apache/catalina/tribes/membership/StaticMember.java
public void setHost(String host) { if ( host == null ) return; if ( host.startsWith("{") ) setHost(Arrays.fromString(host)); else try { setHostname(host); }catch (IOException x) { throw new RuntimeException(x);} }
// in java/org/apache/catalina/tribes/membership/StaticMember.java
public void setUniqueId(String id) { byte[] uuid = Arrays.fromString(id); if ( uuid==null || uuid.length != 16 ) throw new RuntimeException("UUID must be exactly 16 bytes, not:"+id); setUniqueId(uuid); }
// in java/org/apache/catalina/tribes/util/Arrays.java
public static byte[] fromString(String value) { if ( value == null ) return null; if ( !value.startsWith("{") ) throw new RuntimeException("byte arrays must be represented as {1,3,4,5,6}"); StringTokenizer t = new StringTokenizer(value,"{,}",false); byte[] result = new byte[t.countTokens()]; for (int i=0; i<result.length; i++ ) result[i] = Byte.parseByte(t.nextToken()); return result; }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int read() throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.readByte()); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int available() throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.available()); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int read(final byte[] b) throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.read(b, 0, b.length)); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage() ,e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public int read(final byte[] b, final int off, final int len) throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ Integer result = AccessController.doPrivileged( new PrivilegedExceptionAction<Integer>(){ @Override public Integer run() throws IOException{ Integer integer = Integer.valueOf(ib.read(b, off, len)); return integer; } }); return result.intValue(); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
Override public void close() throws IOException { if (SecurityUtil.isPackageProtectionEnabled()){ try{ AccessController.doPrivileged( new PrivilegedExceptionAction<Void>(){ @Override public Void run() throws IOException{ ib.close(); return null; } }); } catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
protected Class<?> loadClassMaybePrivileged(final String className, final ClassLoader classLoader) throws ClassNotFoundException { Class<?> clazz; if (SecurityUtil.isPackageProtectionEnabled()) { try { clazz = AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() { @Override public Class<?> run() throws Exception { return loadClass(className, classLoader); } }); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); } }
// in java/org/apache/catalina/core/AsyncContextImpl.java
Override public void run() { request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCHED, null); DispatcherType type = (DispatcherType)request.getAttribute(Globals.DISPATCHER_TYPE_ATTR); try { //piggy back on the request dispatcher to ensure that filters etc get called. //TODO SERVLET3 - async should this be include/forward or a new dispatch type //javadoc suggests include with the type of DispatcherType.ASYNC request.setAttribute(Globals.DISPATCHER_TYPE_ATTR, DispatcherType.ASYNC); requestDispatcher.include(servletRequest, servletResponse); }catch (Exception x) { //log.error("Async.dispatch",x); throw new RuntimeException(x); }finally { request.setAttribute(Globals.DISPATCHER_TYPE_ATTR, type); } }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
private Object doPrivileged(final String methodName, final Object[] params) { try{ return invokeMethod(context, methodName, params); }catch(Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage(), t); } }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
private Object doPrivileged(final String methodName, final Class<?>[] clazz, Object[] params) { try{ Method method = context.getClass().getMethod(methodName, clazz); return executeMethod(method,context,params); } catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; } finally { params = null; } }
// in java/javax/servlet/http/Cookie.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e.getMessage()); } }
31
            
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (PrivilegedActionException ex) { throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); }
// in java/org/apache/jasper/runtime/ProtectedFunctionMapper.java
catch (NoSuchMethodException e) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); }
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
catch (JasperException je) { throw new RuntimeException(je.toString(), je); }
// in java/org/apache/jasper/compiler/JarURLResource.java
catch (MalformedURLException e) { throw new RuntimeException("", e); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/jasper/JspC.java
catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); }
// in java/org/apache/naming/NamingContextBindingsEnumeration.java
catch (NamingException e) { throw new RuntimeException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/el/parser/ELParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/el/parser/ELParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (NumberFormatException e) { throw new RuntimeException("Exception parsing number '" + i + "' (zero based) of comma delimited list '" + commaDelimitedInts + "'"); }
// in java/org/apache/catalina/tribes/transport/nio/PooledParallelSender.java
catch ( IOException x ) { throw new RuntimeException("Unable to open NIO selector.",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (ChannelException x) { log.warn("Unable to send map start message."); // remove listener from channel this.rpcChannel.breakdown(); this.channel.removeChannelListener(this); this.channel.removeMembershipListener(this); throw new RuntimeException("Unable to start replicated map.",x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch ( IOException x ) { throw new RuntimeException(x); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
catch (IOException x) { throw new RuntimeException(x); }
// in java/org/apache/catalina/tribes/membership/MemberImpl.java
catch ( IOException x ) { throw new RuntimeException("Unable to parse hostname.",x); }
// in java/org/apache/catalina/tribes/membership/StaticMember.java
catch (IOException x) { throw new RuntimeException(x);}
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage() ,e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/connector/CoyoteInputStream.java
catch(PrivilegedActionException pae){ Exception e = pae.getException(); if (e instanceof IOException){ throw (IOException)e; } else { throw new RuntimeException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (Exception x) { //log.error("Async.dispatch",x); throw new RuntimeException(x); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch(Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage(), t); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); }
// in java/javax/servlet/http/Cookie.java
catch (CloneNotSupportedException e) { throw new RuntimeException(e.getMessage()); }
0 13
            
// in java/org/apache/jasper/servlet/JspServlet.java
catch (RuntimeException e) { throw e; }
// in java/org/apache/tomcat/util/buf/UDecoder.java
catch (RuntimeException ex) { throw new DecodeException(ex.getMessage()); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/mbeans/GlobalResourcesLifecycleListener.java
catch( RuntimeException ex) { log.error("RuntimeException " + ex); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (RuntimeException e) { throw new ServletException(sm.getString( "expiresFilter.exceptionProcessingParameter", name, value), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); runtimeException = e; }
13
            
// in java/org/apache/jasper/servlet/JspServlet.java
catch (RuntimeException e) { throw e; }
// in java/org/apache/tomcat/util/buf/UDecoder.java
catch (RuntimeException ex) { throw new DecodeException(ex.getMessage()); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (RuntimeException e) { throw new ServletException(sm.getString( "expiresFilter.exceptionProcessingParameter", name, value), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (RuntimeException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); }
0
unknown (Lib) RuntimeOperationsException 23
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public Method getInvoke(String aname, Object[] params, String[] signature, BaseModelMBean bean, Object resource) throws MBeanException, ReflectionException { Method method = null; if (params == null) params = new Object[0]; if (signature == null) signature = new String[0]; if (params.length != signature.length) throw new RuntimeOperationsException( new IllegalArgumentException( "Inconsistent arguments and signature"), "Inconsistent arguments and signature"); // Acquire the ModelMBeanOperationInfo information for // the requested operation OperationInfo opInfo = operations.get(aname); if (opInfo == null) throw new MBeanException(new ServiceNotFoundException( "Cannot find operation " + aname), "Cannot find operation " + aname); // Prepare the signature required by Java reflection APIs // FIXME - should we use the signature from opInfo? Class<?> types[] = new Class[signature.length]; for (int i = 0; i < signature.length; i++) { types[i] = BaseModelMBean.getAttributeClass(signature[i]); } // Locate the method to be invoked, either in this MBean itself // or in the corresponding managed resource // FIXME - Accessible methods in superinterfaces? Object object = null; Exception exception = null; try { object = bean; method = object.getClass().getMethod(aname, types); } catch (NoSuchMethodException e) { exception = e; } try { if ((method == null) && (resource != null)) { object = resource; method = object.getClass().getMethod(aname, types); } } catch (NoSuchMethodException e) { exception = e; } if (method == null) { throw new ReflectionException(exception, "Cannot find method " + aname + " with this signature"); } return method; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).getAttribute(name); } Method m=managedBean.getGetter(name, this, resource); Object result = null; try { Class<?> declaring = m.getDeclaringClass(); // workaround for catalina weird mbeans - the declaring class is BaseModelMBean. // but this is the catalina class. if( declaring.isAssignableFrom(this.getClass()) ) { result = m.invoke(this, NO_ARGS_PARAM ); } else { result = m.invoke(resource, NO_ARGS_PARAM ); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public AttributeList getAttributes(String names[]) { // Validate the input parameters if (names == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute names list is null"), "Attribute names list is null"); // Prepare our response, eating all exceptions AttributeList response = new AttributeList(); for (int i = 0; i < names.length; i++) { try { response.add(new Attribute(names[i],getAttribute(names[i]))); } catch (Exception e) { // Not having a particular attribute in the response // is the indication of a getter problem } } return (response); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public Object invoke(String name, Object params[], String signature[]) throws MBeanException, ReflectionException { if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { return ((DynamicMBean)resource).invoke(name, params, signature); } // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Method name is null"), "Method name is null"); if( log.isDebugEnabled()) log.debug("Invoke " + name); Method method= managedBean.getInvoke(name, params, signature, this, resource); // Invoke the selected method on the appropriate object Object result = null; try { if( method.getDeclaringClass().isAssignableFrom( this.getClass()) ) { result = method.invoke(this, params ); } else { result = method.invoke(resource, params); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } // Return the results of this method invocation // FIXME - should we validate the return type? return (result); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if( log.isDebugEnabled() ) log.debug("Setting attribute " + this + " " + attribute ); if( (resource instanceof DynamicMBean) && ! ( resource instanceof BaseModelMBean )) { try { ((DynamicMBean)resource).setAttribute(attribute); } catch (InvalidAttributeValueException e) { throw new MBeanException(e); } return; } // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); Object oldValue=null; //if( getAttMap.get(name) != null ) // oldValue=getAttribute( name ); Method m=managedBean.getSetter(name,this,resource); try { if( m.getDeclaringClass().isAssignableFrom( this.getClass()) ) { m.invoke(this, new Object[] { value }); } else { m.invoke(resource, new Object[] { value }); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); } catch (Exception e) { log.error("Exception invoking method " + name , e ); throw new MBeanException (e, "Exception invoking method " + name); } try { sendAttributeChangeNotification(new Attribute( name, oldValue), attribute); } catch(Exception ex) { log.error("Error sending notification " + name, ex); } //attributes.put( name, value ); // if( source != null ) { // // this mbean is associated with a source - maybe we want to persist // source.updateField(oname, name, value); // } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
public Object getManagedResource() throws InstanceNotFoundException, InvalidTargetObjectTypeException, MBeanException, RuntimeOperationsException { if (resource == null) throw new RuntimeOperationsException (new IllegalArgumentException("Managed resource is null"), "Managed resource is null"); return resource; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
public void setManagedResource(Object resource, String type) throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { if (resource == null) throw new RuntimeOperationsException (new IllegalArgumentException("Managed resource is null"), "Managed resource is null"); // if (!"objectreference".equalsIgnoreCase(type)) // throw new InvalidTargetObjectTypeException(type); this.resource = resource; this.resourceType = resource.getClass().getName(); // // Make the resource aware of the model mbean. // try { // Method m=resource.getClass().getMethod("setModelMBean", // new Class[] {ModelMBean.class}); // if( m!= null ) { // m.invoke(resource, new Object[] {this}); // } // } catch( NoSuchMethodException t ) { // // ignore // } catch( Throwable t ) { // log.error( "Can't set model mbean ", t ); // } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendAttributeChangeNotification (AttributeChangeNotification notification) throws MBeanException, RuntimeOperationsException { if (notification == null) throw new RuntimeOperationsException (new IllegalArgumentException("Notification is null"), "Notification is null"); if (attributeBroadcaster == null) return; // This means there are no registered listeners if( log.isDebugEnabled() ) log.debug( "AttributeChangeNotification " + notification ); attributeBroadcaster.sendNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendNotification(Notification notification) throws MBeanException, RuntimeOperationsException { if (notification == null) throw new RuntimeOperationsException (new IllegalArgumentException("Notification is null"), "Notification is null"); if (generalBroadcaster == null) return; // This means there are no registered listeners generalBroadcaster.sendNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendNotification(String message) throws MBeanException, RuntimeOperationsException { if (message == null) throw new RuntimeOperationsException (new IllegalArgumentException("Message is null"), "Message is null"); Notification notification = new Notification ("jmx.modelmbean.generic", this, 1, message); sendNotification(notification); }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); Object result = null; try { Connector connector = (Connector) getManagedResource(); result = IntrospectionUtils.getProperty(connector, name); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } return result; }
// in java/org/apache/catalina/mbeans/ConnectorMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException( "Attribute name is null"), "Attribute name is null"); try { Connector connector = (Connector) getManagedResource(); IntrospectionUtils.setProperty(connector, name, String.valueOf(value)); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("auth".equals(name)) { return (cr.getAuth()); } else if ("description".equals(name)) { return (cr.getDescription()); } else if ("name".equals(name)) { return (cr.getName()); } else if ("scope".equals(name)) { return (cr.getScope()); } else if ("type".equals(name)) { return (cr.getType()); } else { value = (String) cr.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResource cr = null; try { cr = (ContextResource) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("auth".equals(name)) { cr.setAuth((String)value); } else if ("description".equals(name)) { cr.setDescription((String)value); } else if ("name".equals(name)) { cr.setName((String)value); } else if ("scope".equals(name)) { cr.setScope((String)value); } else if ("type".equals(name)) { cr.setType((String)value); } else { cr.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = cr.getNamingResources(); nr.removeResource(cr.getName()); nr.addResource(cr); }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink cl = null; try { cl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } String value = null; if ("global".equals(name)) { return (cl.getGlobal()); } else if ("description".equals(name)) { return (cl.getDescription()); } else if ("name".equals(name)) { return (cl.getName()); } else if ("type".equals(name)) { return (cl.getType()); } else { value = (String) cl.getProperty(name); if (value == null) { throw new AttributeNotFoundException ("Cannot find attribute "+name); } } return value; }
// in java/org/apache/catalina/mbeans/ContextResourceLinkMBean.java
Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { // Validate the input parameters if (attribute == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute is null"), "Attribute is null"); String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) throw new RuntimeOperationsException (new IllegalArgumentException("Attribute name is null"), "Attribute name is null"); ContextResourceLink crl = null; try { crl = (ContextResourceLink) getManagedResource(); } catch (InstanceNotFoundException e) { throw new MBeanException(e); } catch (InvalidTargetObjectTypeException e) { throw new MBeanException(e); } if ("global".equals(name)) { crl.setGlobal((String)value); } else if ("description".equals(name)) { crl.setDescription((String)value); } else if ("name".equals(name)) { crl.setName((String)value); } else if ("type".equals(name)) { crl.setType((String)value); } else { crl.setProperty(name, ""+value); } // cannot use side-effects. It's removed and added back each time // there is a modification in a resource. NamingResources nr = crl.getNamingResources(); nr.removeResourceLink(crl.getName()); nr.addResourceLink(crl); }
3
            
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); log.error("Exception invoking method " + name , t ); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException ((Exception)t, "Exception invoking method " + name); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; if (t instanceof RuntimeException) throw new RuntimeOperationsException ((RuntimeException) t, "Exception invoking method " + name); else if (t instanceof Error) throw new RuntimeErrorException ((Error) t, "Error invoking method " + name); else throw new MBeanException (e, "Exception invoking method " + name); }
22
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public DynamicMBean createMBean() throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { return (createMBean(null)); }
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
public DynamicMBean createMBean(Object instance) throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { BaseModelMBean mbean = null; // Load the ModelMBean implementation class if(getClassName().equals(BASE_MBEAN)) { // Skip introspection mbean = new BaseModelMBean(); } else { Class<?> clazz = null; Exception ex = null; try { clazz = Class.forName(getClassName()); } catch (Exception e) { } if( clazz==null ) { try { ClassLoader cl= Thread.currentThread().getContextClassLoader(); if ( cl != null) clazz= cl.loadClass(getClassName()); } catch (Exception e) { ex=e; } } if( clazz==null) { throw new MBeanException (ex, "Cannot load ModelMBean class " + getClassName()); } try { // Stupid - this will set the default minfo first.... mbean = (BaseModelMBean) clazz.newInstance(); } catch (RuntimeOperationsException e) { throw e; } catch (Exception e) { throw new MBeanException (e, "Cannot instantiate ModelMBean of class " + getClassName()); } } mbean.setManagedBean(this); // Set the managed resource (if any) try { if (instance != null) mbean.setManagedResource(instance, "ObjectReference"); } catch (InstanceNotFoundException e) { throw e; } return (mbean); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
public Object getManagedResource() throws InstanceNotFoundException, InvalidTargetObjectTypeException, MBeanException, RuntimeOperationsException { if (resource == null) throw new RuntimeOperationsException (new IllegalArgumentException("Managed resource is null"), "Managed resource is null"); return resource; }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
public void setManagedResource(Object resource, String type) throws InstanceNotFoundException, MBeanException, RuntimeOperationsException { if (resource == null) throw new RuntimeOperationsException (new IllegalArgumentException("Managed resource is null"), "Managed resource is null"); // if (!"objectreference".equalsIgnoreCase(type)) // throw new InvalidTargetObjectTypeException(type); this.resource = resource; this.resourceType = resource.getClass().getName(); // // Make the resource aware of the model mbean. // try { // Method m=resource.getClass().getMethod("setModelMBean", // new Class[] {ModelMBean.class}); // if( m!= null ) { // m.invoke(resource, new Object[] {this}); // } // } catch( NoSuchMethodException t ) { // // ignore // } catch( Throwable t ) { // log.error( "Can't set model mbean ", t ); // } }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendAttributeChangeNotification (AttributeChangeNotification notification) throws MBeanException, RuntimeOperationsException { if (notification == null) throw new RuntimeOperationsException (new IllegalArgumentException("Notification is null"), "Notification is null"); if (attributeBroadcaster == null) return; // This means there are no registered listeners if( log.isDebugEnabled() ) log.debug( "AttributeChangeNotification " + notification ); attributeBroadcaster.sendNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendAttributeChangeNotification (Attribute oldValue, Attribute newValue) throws MBeanException, RuntimeOperationsException { // Calculate the class name for the change notification String type = null; if (newValue.getValue() != null) type = newValue.getValue().getClass().getName(); else if (oldValue.getValue() != null) type = oldValue.getValue().getClass().getName(); else return; // Old and new are both null == no change AttributeChangeNotification notification = new AttributeChangeNotification (this, 1, System.currentTimeMillis(), "Attribute value has changed", oldValue.getName(), type, oldValue.getValue(), newValue.getValue()); sendAttributeChangeNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendNotification(Notification notification) throws MBeanException, RuntimeOperationsException { if (notification == null) throw new RuntimeOperationsException (new IllegalArgumentException("Notification is null"), "Notification is null"); if (generalBroadcaster == null) return; // This means there are no registered listeners generalBroadcaster.sendNotification(notification); }
// in java/org/apache/tomcat/util/modeler/BaseModelMBean.java
Override public void sendNotification(String message) throws MBeanException, RuntimeOperationsException { if (message == null) throw new RuntimeOperationsException (new IllegalArgumentException("Message is null"), "Message is null"); Notification notification = new Notification ("jmx.modelmbean.generic", this, 1, message); sendNotification(notification); }
22
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (RuntimeOperationsException e) { throw e; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
22
            
// in java/org/apache/tomcat/util/modeler/ManagedBean.java
catch (RuntimeOperationsException e) { throw e; }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ServiceMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContextMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
// in java/org/apache/catalina/mbeans/ContainerMBean.java
catch (RuntimeOperationsException e) { throw new MBeanException(e); }
0
unknown (Lib) SAXException 12
            
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private Node parseCustomAction( String qName, String localName, String uri, Attributes nonTaglibAttrs, Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs, Mark start, Node parent) throws SAXException { // Check if this is a user-defined (custom) tag TagLibraryInfo tagLibInfo = pageInfo.getTaglib(uri); if (tagLibInfo == null) { return null; } TagInfo tagInfo = tagLibInfo.getTag(localName); TagFileInfo tagFileInfo = tagLibInfo.getTagFile(localName); if (tagInfo == null && tagFileInfo == null) { throw new SAXException( Localizer.getMessage("jsp.error.xml.bad_tag", localName, uri)); } Class<?> tagHandlerClass = null; if (tagInfo != null) { String handlerClassName = tagInfo.getTagClassName(); try { tagHandlerClass = ctxt.getClassLoader().loadClass(handlerClassName); } catch (Exception e) { throw new SAXException( Localizer.getMessage("jsp.error.loadclass.taghandler", handlerClassName, qName), e); } } String prefix = getPrefix(qName); Node.CustomTag ret = null; if (tagInfo != null) { ret = new Node.CustomTag( qName, prefix, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, parent, tagInfo, tagHandlerClass); } else { ret = new Node.CustomTag( qName, prefix, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, parent, tagFileInfo); } return ret; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void checkScriptingBody(Node.ScriptingElement scriptingElem) throws SAXException { Node.Nodes body = scriptingElem.getBody(); if (body != null) { int size = body.size(); for (int i = 0; i < size; i++) { Node n = body.getNode(i); if (!(n instanceof Node.TemplateText)) { String elemType = SCRIPTLET_ACTION; if (scriptingElem instanceof Node.Declaration) elemType = DECLARATION_ACTION; if (scriptingElem instanceof Node.Expression) elemType = EXPRESSION_ACTION; String msg = Localizer.getMessage( "jsp.error.parse.xml.scripting.invalid.body", elemType); throw new SAXException(msg); } } } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void processIncludeDirective(String fname, Node parent) throws SAXException { if (fname == null) { return; } try { parserController.parse(fname, parent, null); } catch (FileNotFoundException fnfe) { throw new SAXParseException( Localizer.getMessage("jsp.error.file.not.found", fname), locator, fnfe); } catch (Exception e) { throw new SAXException(e); } }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { for (int i = 0; i < Constants.CACHED_DTD_PUBLIC_IDS.size(); i++) { String cachedDtdPublicId = Constants.CACHED_DTD_PUBLIC_IDS.get(i); if (cachedDtdPublicId.equals(publicId)) { String resourcePath = Constants.CACHED_DTD_RESOURCE_PATHS.get(i); InputStream input = this.getClass().getResourceAsStream( resourcePath); if (input == null) { throw new SAXException(Localizer.getMessage( "jsp.error.internal.filenotfound", resourcePath)); } InputSource isrc = new InputSource(input); return isrc; } } Log log = LogFactory.getLog(MyEntityResolver.class); if (log.isDebugEnabled()) log.debug("Resolve entity failed" + publicId + " " + systemId); log.error(Localizer.getMessage("jsp.error.parse.xml.invalidPublicId", publicId)); return null; }
// in java/org/apache/tomcat/util/digester/CallMethodRule.java
Override public void end(String namespace, String name) throws Exception { // Retrieve or construct the parameter values array Object parameters[] = null; if (paramCount > 0) { parameters = (Object[]) digester.popParams(); if (digester.log.isTraceEnabled()) { for (int i=0,size=parameters.length;i<size;i++) { digester.log.trace("[CallMethodRule](" + i + ")" + parameters[i]) ; } } // In the case where the parameter for the method // is taken from an attribute, and that attribute // isn't actually defined in the source XML file, // skip the method call if (paramCount == 1 && parameters[0] == null) { return; } } else if (paramTypes != null && paramTypes.length != 0) { // In the case where the parameter for the method // is taken from the body text, but there is no // body text included in the source XML file, // skip the method call if (bodyText == null) { return; } parameters = new Object[1]; parameters[0] = bodyText; if (paramTypes.length == 0) { paramTypes = new Class[1]; paramTypes[0] = "abc".getClass(); } } // Construct the parameter values array we will need // We only do the conversion if the param value is a String and // the specified paramType is not String. Object paramValues[] = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { // convert nulls and convert stringy parameters // for non-stringy param types if( parameters[i] == null || (parameters[i] instanceof String && !String.class.isAssignableFrom(paramTypes[i]))) { paramValues[i] = IntrospectionUtils.convert((String) parameters[i], paramTypes[i]); } else { paramValues[i] = parameters[i]; } } // Determine the target object for the method call Object target; if (targetOffset >= 0) { target = digester.peek(targetOffset); } else { target = digester.peek( digester.getCount() + targetOffset ); } if (target == null) { StringBuilder sb = new StringBuilder(); sb.append("[CallMethodRule]{"); sb.append(digester.match); sb.append("} Call target is null ("); sb.append("targetOffset="); sb.append(targetOffset); sb.append(",stackdepth="); sb.append(digester.getCount()); sb.append(")"); throw new org.xml.sax.SAXException(sb.toString()); } // Invoke the required method on the top object if (digester.log.isDebugEnabled()) { StringBuilder sb = new StringBuilder("[CallMethodRule]{"); sb.append(digester.match); sb.append("} Call "); sb.append(target.getClass().getName()); sb.append("."); sb.append(methodName); sb.append("("); for (int i = 0; i < paramValues.length; i++) { if (i > 0) { sb.append(","); } if (paramValues[i] == null) { sb.append("null"); } else { sb.append(paramValues[i].toString()); } sb.append("/"); if (paramTypes[i] == null) { sb.append("null"); } else { sb.append(paramTypes[i].getName()); } } sb.append(")"); digester.log.debug(sb.toString()); } Object result = IntrospectionUtils.callMethodN(target, methodName, paramValues, paramTypes); processMethodCallResult(result); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void characters(char[] ch, int start, int length) throws SAXException { try { String str = new String(ch, start, length); if (str.trim().length() > 0) { top.appendChild(doc.createTextNode(str)); } } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { try { if (depth == 0) { getDigester().getXMLReader().setContentHandler( oldContentHandler); getDigester().push(root); getDigester().endElement(namespaceURI, localName, qName); } top = top.getParentNode(); depth--; } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void processingInstruction(String target, String data) throws SAXException { try { top.appendChild(doc.createProcessingInstruction(target, data)); } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { try { Node previousTop = top; if ((localName == null) || (localName.length() == 0)) { top = doc.createElement(qName); } else { top = doc.createElementNS(namespaceURI, localName); } for (int i = 0; i < atts.getLength(); i++) { Attr attr = null; if ((atts.getLocalName(i) == null) || (atts.getLocalName(i).length() == 0)) { attr = doc.createAttribute(atts.getQName(i)); attr.setNodeValue(atts.getValue(i)); ((Element)top).setAttributeNode(attr); } else { attr = doc.createAttributeNS(atts.getURI(i), atts.getLocalName(i)); attr.setNodeValue(atts.getValue(i)); ((Element)top).setAttributeNodeNS(attr); } } previousTop.appendChild(top); depth++; } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/catalina/startup/WebRuleSet.java
Override public void end(String namespace, String name) throws Exception { // Retrieve or construct the parameter values array Object parameters[] = null; if (paramCount > 0) { parameters = (Object[]) digester.popParams(); } else { parameters = new Object[0]; super.end(namespace, name); } ArrayList<?> multiParams = (ArrayList<?>) parameters[multiParamIndex]; // Construct the parameter values array we will need // We only do the conversion if the param value is a String and // the specified paramType is not String. Object paramValues[] = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { if (i != multiParamIndex) { // convert nulls and convert stringy parameters // for non-stringy param types if(parameters[i] == null || (parameters[i] instanceof String && !String.class.isAssignableFrom(paramTypes[i]))) { paramValues[i] = IntrospectionUtils.convert((String) parameters[i], paramTypes[i]); } else { paramValues[i] = parameters[i]; } } } // Determine the target object for the method call Object target; if (targetOffset >= 0) { target = digester.peek(targetOffset); } else { target = digester.peek(digester.getCount() + targetOffset); } if (target == null) { StringBuilder sb = new StringBuilder(); sb.append("[CallMethodRule]{"); sb.append(""); sb.append("} Call target is null ("); sb.append("targetOffset="); sb.append(targetOffset); sb.append(",stackdepth="); sb.append(digester.getCount()); sb.append(")"); throw new org.xml.sax.SAXException(sb.toString()); } if (multiParams == null) { paramValues[multiParamIndex] = null; IntrospectionUtils.callMethodN(target, methodName, paramValues, paramTypes); return; } for (int j = 0; j < multiParams.size(); j++) { Object param = multiParams.get(j); if(param == null || (param instanceof String && !String.class.isAssignableFrom(paramTypes[multiParamIndex]))) { paramValues[multiParamIndex] = IntrospectionUtils.convert((String) param, paramTypes[multiParamIndex]); } else { paramValues[multiParamIndex] = param; } IntrospectionUtils.callMethodN(target, methodName, paramValues, paramTypes); } }
// in java/org/apache/catalina/util/SchemaResolver.java
Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { if (publicId != null) { digester.setPublicId(publicId); } // Has this system identifier been registered? String entityURL = null; if (publicId != null) { entityURL = entityValidator.get(publicId); } // Redirect the schema location to a local destination String key = null; if (entityURL == null && systemId != null) { key = systemId.substring(systemId.lastIndexOf('/')+1); entityURL = entityValidator.get(key); } if (entityURL == null) { return (null); } try { return (new InputSource(entityURL)); } catch (Exception e) { throw new SAXException(e); } }
7
            
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { throw new SAXException( Localizer.getMessage("jsp.error.loadclass.taghandler", handlerClassName, qName), e); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (Exception e) { throw new SAXException(e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
catch (DOMException e) { throw new SAXException(e.getMessage(), e); }
// in java/org/apache/catalina/util/SchemaResolver.java
catch (Exception e) { throw new SAXException(e); }
55
            
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void addInclude(Node parent, List<String> files) throws SAXException { if (files != null) { Iterator<String> iter = files.iterator(); while (iter.hasNext()) { String file = iter.next(); AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute("", "file", "file", "CDATA", file); // Create a dummy Include directive node Node includeDir = new Node.IncludeDirective(attrs, null, // XXX parent); processIncludeDirective(file, includeDir); } } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void startElement( String uri, String localName, String qName, Attributes attrs) throws SAXException { AttributesImpl taglibAttrs = null; AttributesImpl nonTaglibAttrs = null; AttributesImpl nonTaglibXmlnsAttrs = null; processChars(); checkPrefixes(uri, qName, attrs); if (directivesOnly && !(JSP_URI.equals(uri) && localName.startsWith(DIRECTIVE_ACTION))) { return; } String currentPrefix = getPrefix(current.getQName()); // jsp:text must not have any subelements if (JSP_URI.equals(uri) && TEXT_ACTION.equals(current.getLocalName()) && "jsp".equals(currentPrefix)) { throw new SAXParseException( Localizer.getMessage("jsp.error.text.has_subelement"), locator); } startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); if (attrs != null) { /* * Notice that due to a bug in the underlying SAX parser, the * attributes must be enumerated in descending order. */ boolean isTaglib = false; for (int i = attrs.getLength() - 1; i >= 0; i--) { isTaglib = false; String attrQName = attrs.getQName(i); if (!attrQName.startsWith("xmlns")) { if (nonTaglibAttrs == null) { nonTaglibAttrs = new AttributesImpl(); } nonTaglibAttrs.addAttribute( attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getValue(i)); } else { if (attrQName.startsWith("xmlns:jsp")) { isTaglib = true; } else { String attrUri = attrs.getValue(i); // TaglibInfo for this uri already established in // startPrefixMapping isTaglib = pageInfo.hasTaglib(attrUri); } if (isTaglib) { if (taglibAttrs == null) { taglibAttrs = new AttributesImpl(); } taglibAttrs.addAttribute( attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getValue(i)); } else { if (nonTaglibXmlnsAttrs == null) { nonTaglibXmlnsAttrs = new AttributesImpl(); } nonTaglibXmlnsAttrs.addAttribute( attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getValue(i)); } } } } Node node = null; if (tagDependentPending && JSP_URI.equals(uri) && localName.equals(BODY_ACTION)) { tagDependentPending = false; tagDependentNesting++; current = parseStandardAction( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark); return; } if (tagDependentPending && JSP_URI.equals(uri) && localName.equals(ATTRIBUTE_ACTION)) { current = parseStandardAction( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark); return; } if (tagDependentPending) { tagDependentPending = false; tagDependentNesting++; } if (tagDependentNesting > 0) { node = new Node.UninterpretedTag( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark, current); } else if (JSP_URI.equals(uri)) { node = parseStandardAction( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark); } else { node = parseCustomAction( qName, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark, current); if (node == null) { node = new Node.UninterpretedTag( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark, current); } else { // custom action String bodyType = getBodyType((Node.CustomTag) node); if (scriptlessBodyNode == null && bodyType.equalsIgnoreCase(TagInfo.BODY_CONTENT_SCRIPTLESS)) { scriptlessBodyNode = node; } else if (TagInfo.BODY_CONTENT_TAG_DEPENDENT.equalsIgnoreCase(bodyType)) { tagDependentPending = true; } } } current = node; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void processChars() throws SAXException { if (charBuffer == null || directivesOnly) { return; } /* * JSP.6.1.1: All textual nodes that have only white space are to be * dropped from the document, except for nodes in a jsp:text element, * and any leading and trailing white-space-only textual nodes in a * jsp:attribute whose 'trim' attribute is set to FALSE, which are to * be kept verbatim. * JSP.6.2.3 defines white space characters. */ boolean isAllSpace = true; if (!(current instanceof Node.JspText) && !(current instanceof Node.NamedAttribute)) { for (int i = 0; i < charBuffer.length(); i++) { if (!(charBuffer.charAt(i) == ' ' || charBuffer.charAt(i) == '\n' || charBuffer.charAt(i) == '\r' || charBuffer.charAt(i) == '\t')) { isAllSpace = false; break; } } } if (!isAllSpace && tagDependentPending) { tagDependentPending = false; tagDependentNesting++; } if (tagDependentNesting > 0) { if (charBuffer.length() > 0) { new Node.TemplateText(charBuffer.toString(), startMark, current); } startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); charBuffer = null; return; } if ((current instanceof Node.JspText) || (current instanceof Node.NamedAttribute) || !isAllSpace) { int line = startMark.getLineNumber(); int column = startMark.getColumnNumber(); CharArrayWriter ttext = new CharArrayWriter(); int lastCh = 0, elType = 0; for (int i = 0; i < charBuffer.length(); i++) { int ch = charBuffer.charAt(i); if (ch == '\n') { column = 1; line++; } else { column++; } if ((lastCh == '$' || lastCh == '#') && ch == '{') { elType = lastCh; if (ttext.size() > 0) { new Node.TemplateText( ttext.toString(), startMark, current); ttext = new CharArrayWriter(); //We subtract two from the column number to //account for the '[$,#]{' that we've already parsed startMark = new Mark(ctxt, path, line, column - 2); } // following "${" || "#{" to first unquoted "}" i++; boolean singleQ = false; boolean doubleQ = false; lastCh = 0; for (;; i++) { if (i >= charBuffer.length()) { throw new SAXParseException( Localizer.getMessage( "jsp.error.unterminated", (char) elType + "{"), locator); } ch = charBuffer.charAt(i); if (ch == '\n') { column = 1; line++; } else { column++; } if (lastCh == '\\' && (singleQ || doubleQ)) { ttext.write(ch); lastCh = 0; continue; } if (ch == '}') { new Node.ELExpression((char) elType, ttext.toString(), startMark, current); ttext = new CharArrayWriter(); startMark = new Mark(ctxt, path, line, column); break; } if (ch == '"') doubleQ = !doubleQ; else if (ch == '\'') singleQ = !singleQ; ttext.write(ch); lastCh = ch; } } else if (lastCh == '\\' && (ch == '$' || ch == '#')) { if (pageInfo.isELIgnored()) { ttext.write('\\'); } ttext.write(ch); ch = 0; // Not start of EL anymore } else { if (lastCh == '$' || lastCh == '#' || lastCh == '\\') { ttext.write(lastCh); } if (ch != '$' && ch != '#' && ch != '\\') { ttext.write(ch); } } lastCh = ch; } if (lastCh == '$' || lastCh == '#' || lastCh == '\\') { ttext.write(lastCh); } if (ttext.size() > 0) { new Node.TemplateText(ttext.toString(), startMark, current); } } startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); charBuffer = null; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void endElement(String uri, String localName, String qName) throws SAXException { processChars(); if (directivesOnly && !(JSP_URI.equals(uri) && localName.startsWith(DIRECTIVE_ACTION))) { return; } if (current instanceof Node.NamedAttribute) { boolean isTrim = ((Node.NamedAttribute)current).isTrim(); Node.Nodes subElems = ((Node.NamedAttribute)current).getBody(); for (int i = 0; subElems != null && i < subElems.size(); i++) { Node subElem = subElems.getNode(i); if (!(subElem instanceof Node.TemplateText)) { continue; } // Ignore any whitespace (including spaces, carriage returns, // line feeds, and tabs, that appear at the beginning and at // the end of the body of the <jsp:attribute> action, if the // action's 'trim' attribute is set to TRUE (default). // In addition, any textual nodes in the <jsp:attribute> that // have only white space are dropped from the document, with // the exception of leading and trailing white-space-only // textual nodes in a <jsp:attribute> whose 'trim' attribute // is set to FALSE, which must be kept verbatim. if (i == 0) { if (isTrim) { ((Node.TemplateText)subElem).ltrim(); } } else if (i == subElems.size() - 1) { if (isTrim) { ((Node.TemplateText)subElem).rtrim(); } } else { if (((Node.TemplateText)subElem).isAllSpace()) { subElems.remove(subElem); } } } } else if (current instanceof Node.ScriptingElement) { checkScriptingBody((Node.ScriptingElement)current); } if ( isTagDependent(current)) { tagDependentNesting--; } if (scriptlessBodyNode != null && current.equals(scriptlessBodyNode)) { scriptlessBodyNode = null; } if (current instanceof Node.CustomTag) { String bodyType = getBodyType((Node.CustomTag) current); if (TagInfo.BODY_CONTENT_EMPTY.equalsIgnoreCase(bodyType)) { // Children - if any - must be JSP attributes Node.Nodes children = current.getBody(); if (children != null && children.size() > 0) { for (int i = 0; i < children.size(); i++) { Node child = children.getNode(i); if (!(child instanceof Node.NamedAttribute)) { throw new SAXParseException(Localizer.getMessage( "jasper.error.emptybodycontent.nonempty", current.qName), locator); } } } } } if (current.getParent() != null) { current = current.getParent(); } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void comment(char[] buf, int offset, int len) throws SAXException { processChars(); // Flush char buffer and remove white spaces // ignore comments in the DTD if (!inDTD) { startMark = new Mark( ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); new Node.Comment(new String(buf, offset, len), startMark, current); } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void startCDATA() throws SAXException { processChars(); // Flush char buffer and remove white spaces startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void endCDATA() throws SAXException { processChars(); // Flush char buffer and remove white spaces }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void startEntity(String name) throws SAXException { // do nothing }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void endEntity(String name) throws SAXException { // do nothing }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void startDTD(String name, String publicId, String systemId) throws SAXException { if (!isValidating) { fatalError(new EnableDTDValidationException( "jsp.error.enable_dtd_validation", null)); } inDTD = true; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void endDTD() throws SAXException { inDTD = false; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void fatalError(SAXParseException e) throws SAXException { throw e; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void error(SAXParseException e) throws SAXException { throw e; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void startPrefixMapping(String prefix, String uri) throws SAXException { TagLibraryInfo taglibInfo; if (directivesOnly && !(JSP_URI.equals(uri))) { return; } try { taglibInfo = getTaglibInfo(prefix, uri); } catch (JasperException je) { throw new SAXParseException( Localizer.getMessage("jsp.error.could.not.add.taglibraries"), locator, je); } if (taglibInfo != null) { if (pageInfo.getTaglib(uri) == null) { pageInfo.addTaglib(uri, taglibInfo); } pageInfo.pushPrefixMapping(prefix, uri); } else { pageInfo.pushPrefixMapping(prefix, null); } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void endPrefixMapping(String prefix) throws SAXException { if (directivesOnly) { String uri = pageInfo.getURI(prefix); if (!JSP_URI.equals(uri)) { return; } } pageInfo.popPrefixMapping(prefix); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private Node parseStandardAction( String qName, String localName, Attributes nonTaglibAttrs, Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs, Mark start) throws SAXException { Node node = null; if (localName.equals(ROOT_ACTION)) { if (!(current instanceof Node.Root)) { throw new SAXParseException( Localizer.getMessage("jsp.error.nested_jsproot"), locator); } node = new Node.JspRoot( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); if (isTop) { pageInfo.setHasJspRoot(true); } } else if (localName.equals(PAGE_DIRECTIVE_ACTION)) { if (isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.istagfile", localName), locator); } node = new Node.PageDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); String imports = nonTaglibAttrs.getValue("import"); // There can only be one 'import' attribute per page directive if (imports != null) { ((Node.PageDirective)node).addImport(imports); } } else if (localName.equals(INCLUDE_DIRECTIVE_ACTION)) { node = new Node.IncludeDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); processIncludeDirective(nonTaglibAttrs.getValue("file"), node); } else if (localName.equals(DECLARATION_ACTION)) { if (scriptlessBodyNode != null) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException( Localizer.getMessage( "jsp.error.no.scriptlets", localName), locator); } node = new Node.Declaration( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(SCRIPTLET_ACTION)) { if (scriptlessBodyNode != null) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException( Localizer.getMessage( "jsp.error.no.scriptlets", localName), locator); } node = new Node.Scriptlet( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(EXPRESSION_ACTION)) { if (scriptlessBodyNode != null) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException( Localizer.getMessage( "jsp.error.no.scriptlets", localName), locator); } node = new Node.Expression( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(USE_BEAN_ACTION)) { node = new Node.UseBean( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(SET_PROPERTY_ACTION)) { node = new Node.SetProperty( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(GET_PROPERTY_ACTION)) { node = new Node.GetProperty( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(INCLUDE_ACTION)) { node = new Node.IncludeAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(FORWARD_ACTION)) { node = new Node.ForwardAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(PARAM_ACTION)) { node = new Node.ParamAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(PARAMS_ACTION)) { node = new Node.ParamsAction( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(PLUGIN_ACTION)) { node = new Node.PlugIn( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(TEXT_ACTION)) { node = new Node.JspText( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(BODY_ACTION)) { node = new Node.JspBody( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(ATTRIBUTE_ACTION)) { node = new Node.NamedAttribute( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(OUTPUT_ACTION)) { node = new Node.JspOutput( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(TAG_DIRECTIVE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.TagDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); String imports = nonTaglibAttrs.getValue("import"); // There can only be one 'import' attribute per tag directive if (imports != null) { ((Node.TagDirective)node).addImport(imports); } } else if (localName.equals(ATTRIBUTE_DIRECTIVE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.AttributeDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(VARIABLE_DIRECTIVE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.VariableDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(INVOKE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.InvokeAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(DOBODY_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.DoBodyAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(ELEMENT_ACTION)) { node = new Node.JspElement( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(FALLBACK_ACTION)) { node = new Node.FallBackAction( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else { throw new SAXParseException( Localizer.getMessage( "jsp.error.xml.badStandardAction", localName), locator); } return node; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private Node parseCustomAction( String qName, String localName, String uri, Attributes nonTaglibAttrs, Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs, Mark start, Node parent) throws SAXException { // Check if this is a user-defined (custom) tag TagLibraryInfo tagLibInfo = pageInfo.getTaglib(uri); if (tagLibInfo == null) { return null; } TagInfo tagInfo = tagLibInfo.getTag(localName); TagFileInfo tagFileInfo = tagLibInfo.getTagFile(localName); if (tagInfo == null && tagFileInfo == null) { throw new SAXException( Localizer.getMessage("jsp.error.xml.bad_tag", localName, uri)); } Class<?> tagHandlerClass = null; if (tagInfo != null) { String handlerClassName = tagInfo.getTagClassName(); try { tagHandlerClass = ctxt.getClassLoader().loadClass(handlerClassName); } catch (Exception e) { throw new SAXException( Localizer.getMessage("jsp.error.loadclass.taghandler", handlerClassName, qName), e); } } String prefix = getPrefix(qName); Node.CustomTag ret = null; if (tagInfo != null) { ret = new Node.CustomTag( qName, prefix, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, parent, tagInfo, tagHandlerClass); } else { ret = new Node.CustomTag( qName, prefix, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, parent, tagFileInfo); } return ret; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void checkScriptingBody(Node.ScriptingElement scriptingElem) throws SAXException { Node.Nodes body = scriptingElem.getBody(); if (body != null) { int size = body.size(); for (int i = 0; i < size; i++) { Node n = body.getNode(i); if (!(n instanceof Node.TemplateText)) { String elemType = SCRIPTLET_ACTION; if (scriptingElem instanceof Node.Declaration) elemType = DECLARATION_ACTION; if (scriptingElem instanceof Node.Expression) elemType = EXPRESSION_ACTION; String msg = Localizer.getMessage( "jsp.error.parse.xml.scripting.invalid.body", elemType); throw new SAXException(msg); } } } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void processIncludeDirective(String fname, Node parent) throws SAXException { if (fname == null) { return; } try { parserController.parse(fname, parent, null); } catch (FileNotFoundException fnfe) { throw new SAXParseException( Localizer.getMessage("jsp.error.file.not.found", fname), locator, fnfe); } catch (Exception e) { throw new SAXException(e); } }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { for (int i = 0; i < Constants.CACHED_DTD_PUBLIC_IDS.size(); i++) { String cachedDtdPublicId = Constants.CACHED_DTD_PUBLIC_IDS.get(i); if (cachedDtdPublicId.equals(publicId)) { String resourcePath = Constants.CACHED_DTD_RESOURCE_PATHS.get(i); InputStream input = this.getClass().getResourceAsStream( resourcePath); if (input == null) { throw new SAXException(Localizer.getMessage( "jsp.error.internal.filenotfound", resourcePath)); } InputSource isrc = new InputSource(input); return isrc; } } Log log = LogFactory.getLog(MyEntityResolver.class); if (log.isDebugEnabled()) log.debug("Resolve entity failed" + publicId + " " + systemId); log.error(Localizer.getMessage("jsp.error.parse.xml.invalidPublicId", publicId)); return null; }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
Override public void warning(SAXParseException ex) throws SAXException { Log log = LogFactory.getLog(MyErrorHandler.class); if (log.isDebugEnabled()) log.debug("ParserUtils: warning ", ex); // We ignore warnings }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
Override public void error(SAXParseException ex) throws SAXException { throw ex; }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
Override public void fatalError(SAXParseException ex) throws SAXException { throw ex; }
// in java/org/apache/tomcat/util/digester/Digester.java
public XMLReader getXMLReader() throws SAXException { if (reader == null){ reader = getParser().getXMLReader(); } reader.setDTDHandler(this); reader.setContentHandler(this); if (entityResolver == null){ reader.setEntityResolver(this); } else { reader.setEntityResolver(entityResolver); } reader.setErrorHandler(this); return reader; }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void characters(char buffer[], int start, int length) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("characters(" + new String(buffer, start, length) + ")"); } bodyText.append(buffer, start, length); }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void endDocument() throws SAXException { if (saxLog.isDebugEnabled()) { if (getCount() > 1) { saxLog.debug("endDocument(): " + getCount() + " elements left"); } else { saxLog.debug("endDocument()"); } } while (getCount() > 1) { pop(); } // Fire "finish" events for all defined rules Iterator<Rule> rules = getRules().rules().iterator(); while (rules.hasNext()) { Rule rule = rules.next(); try { rule.finish(); } catch (Exception e) { log.error("Finish event threw exception", e); throw createSAXException(e); } catch (Error e) { log.error("Finish event threw error", e); throw e; } } // Perform final cleanup clear(); }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { boolean debug = log.isDebugEnabled(); if (debug) { if (saxLog.isDebugEnabled()) { saxLog.debug("endElement(" + namespaceURI + "," + localName + "," + qName + ")"); } log.debug(" match='" + match + "'"); log.debug(" bodyText='" + bodyText + "'"); } // Parse system properties bodyText = updateBodyText(bodyText); // the actual element name is either in localName or qName, depending // on whether the parser is namespace aware String name = localName; if ((name == null) || (name.length() < 1)) { name = qName; } // Fire "body" events for all relevant rules List<Rule> rules = matches.pop(); if ((rules != null) && (rules.size() > 0)) { String bodyText = this.bodyText.toString(); for (int i = 0; i < rules.size(); i++) { try { Rule rule = rules.get(i); if (debug) { log.debug(" Fire body() for " + rule); } rule.body(namespaceURI, name, bodyText); } catch (Exception e) { log.error("Body event threw exception", e); throw createSAXException(e); } catch (Error e) { log.error("Body event threw error", e); throw e; } } } else { if (debug) { log.debug(" No rules found matching '" + match + "'."); } if (rulesValidation) { log.warn(" No rules found matching '" + match + "'."); } } // Recover the body text from the surrounding element bodyText = bodyTexts.pop(); if (debug) { log.debug(" Popping body text '" + bodyText.toString() + "'"); } // Fire "end" events for all relevant rules in reverse order if (rules != null) { for (int i = 0; i < rules.size(); i++) { int j = (rules.size() - i) - 1; try { Rule rule = rules.get(j); if (debug) { log.debug(" Fire end() for " + rule); } rule.end(namespaceURI, name); } catch (Exception e) { log.error("End event threw exception", e); throw createSAXException(e); } catch (Error e) { log.error("End event threw error", e); throw e; } } } // Recover the previous match expression int slash = match.lastIndexOf('/'); if (slash >= 0) { match = match.substring(0, slash); } else { match = ""; } }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void endPrefixMapping(String prefix) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("endPrefixMapping(" + prefix + ")"); } // Deregister this prefix mapping ArrayStack<String> stack = namespaces.get(prefix); if (stack == null) { return; } try { stack.pop(); if (stack.empty()) namespaces.remove(prefix); } catch (EmptyStackException e) { throw createSAXException("endPrefixMapping popped too many times"); } }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void ignorableWhitespace(char buffer[], int start, int len) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("ignorableWhitespace(" + new String(buffer, start, len) + ")"); } // No processing required }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void processingInstruction(String target, String data) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("processingInstruction('" + target + "','" + data + "')"); } // No processing is required }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void skippedEntity(String name) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("skippedEntity(" + name + ")"); } // No processing required }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void startDocument() throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("startDocument()"); } // ensure that the digester is properly configured, as // the digester could be used as a SAX ContentHandler // rather than via the parse() methods. configure(); }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void startElement(String namespaceURI, String localName, String qName, Attributes list) throws SAXException { boolean debug = log.isDebugEnabled(); if (saxLog.isDebugEnabled()) { saxLog.debug("startElement(" + namespaceURI + "," + localName + "," + qName + ")"); } // Parse system properties list = updateAttributes(list); // Save the body text accumulated for our surrounding element bodyTexts.push(bodyText); if (debug) { log.debug(" Pushing body text '" + bodyText.toString() + "'"); } bodyText = new StringBuilder(); // the actual element name is either in localName or qName, depending // on whether the parser is namespace aware String name = localName; if ((name == null) || (name.length() < 1)) { name = qName; } // Compute the current matching rule StringBuilder sb = new StringBuilder(match); if (match.length() > 0) { sb.append('/'); } sb.append(name); match = sb.toString(); if (debug) { log.debug(" New match='" + match + "'"); } // Fire "begin" events for all relevant rules List<Rule> rules = getRules().match(namespaceURI, match); matches.push(rules); if ((rules != null) && (rules.size() > 0)) { for (int i = 0; i < rules.size(); i++) { try { Rule rule = rules.get(i); if (debug) { log.debug(" Fire begin() for " + rule); } rule.begin(namespaceURI, name, list); } catch (Exception e) { log.error("Begin event threw exception", e); throw createSAXException(e); } catch (Error e) { log.error("Begin event threw error", e); throw e; } } } else { if (debug) { log.debug(" No rules found matching '" + match + "'."); } } }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void startPrefixMapping(String prefix, String namespaceURI) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("startPrefixMapping(" + prefix + "," + namespaceURI + ")"); } // Register this prefix mapping ArrayStack<String> stack = namespaces.get(prefix); if (stack == null) { stack = new ArrayStack<String>(); namespaces.put(prefix, stack); } stack.push(namespaceURI); }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("resolveEntity('" + publicId + "', '" + systemId + "')"); } if (publicId != null) this.publicId = publicId; // Has this system identifier been registered? String entityURL = null; if (publicId != null) { entityURL = entityValidator.get(publicId); } if (entityURL == null) { if (systemId == null) { // cannot resolve if (log.isDebugEnabled()) { log.debug(" Cannot resolve entity: '" + publicId + "'"); } return (null); } else { // try to resolve using system ID if (log.isDebugEnabled()) { log.debug(" Trying to resolve using system ID '" + systemId + "'"); } entityURL = systemId; } } // Return an input source to our alternative URL if (log.isDebugEnabled()) { log.debug(" Resolving to alternate DTD '" + entityURL + "'"); } try { return (new InputSource(entityURL)); } catch (Exception e) { throw createSAXException(e); } }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void error(SAXParseException exception) throws SAXException { log.error("Parse Error at line " + exception.getLineNumber() + " column " + exception.getColumnNumber() + ": " + exception.getMessage(), exception); if (errorHandler != null) { errorHandler.error(exception); } }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void fatalError(SAXParseException exception) throws SAXException { log.error("Parse Fatal Error at line " + exception.getLineNumber() + " column " + exception.getColumnNumber() + ": " + exception.getMessage(), exception); if (errorHandler != null) { errorHandler.fatalError(exception); } }
// in java/org/apache/tomcat/util/digester/Digester.java
Override public void warning(SAXParseException exception) throws SAXException { if (errorHandler != null) { log.warn("Parse Warning Error at line " + exception.getLineNumber() + " column " + exception.getColumnNumber() + ": " + exception.getMessage(), exception); errorHandler.warning(exception); } }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(File file) throws IOException, SAXException { configure(); InputSource input = new InputSource(new FileInputStream(file)); input.setSystemId("file://" + file.getAbsolutePath()); getXMLReader().parse(input); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(InputSource input) throws IOException, SAXException { configure(); getXMLReader().parse(input); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(InputStream input) throws IOException, SAXException { configure(); InputSource is = new InputSource(input); getXMLReader().parse(is); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(Reader reader) throws IOException, SAXException { configure(); InputSource is = new InputSource(reader); getXMLReader().parse(is); return (root); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object parse(String uri) throws IOException, SAXException { configure(); InputSource is = new InputSource(uri); getXMLReader().parse(is); return (root); }
// in java/org/apache/tomcat/util/digester/XercesParser.java
public static SAXParser newSAXParser(Properties properties) throws ParserConfigurationException, SAXException, SAXNotSupportedException { SAXParserFactory factory = (SAXParserFactory)properties.get("SAXParserFactory"); if (versionNumber == null){ versionNumber = getXercesVersion(); version = new Float( versionNumber ).floatValue(); } // Note: 2.2 is completely broken (with XML Schema). if (version > 2.1) { configureXerces(factory); return factory.newSAXParser(); } else { SAXParser parser = factory.newSAXParser(); configureOldXerces(parser,properties); return parser; } }
// in java/org/apache/tomcat/util/digester/ParserFeatureSetterFactory.java
public static SAXParser newSAXParser(Properties properties) throws ParserConfigurationException, SAXException, SAXNotRecognizedException, SAXNotSupportedException { if (isXercesUsed){ return XercesParser.newSAXParser(properties); } else { return GenericParser.newSAXParser(properties); } }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void characters(char[] ch, int start, int length) throws SAXException { try { String str = new String(ch, start, length); if (str.trim().length() > 0) { top.appendChild(doc.createTextNode(str)); } } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { try { if (depth == 0) { getDigester().getXMLReader().setContentHandler( oldContentHandler); getDigester().push(root); getDigester().endElement(namespaceURI, localName, qName); } top = top.getParentNode(); depth--; } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void processingInstruction(String target, String data) throws SAXException { try { top.appendChild(doc.createProcessingInstruction(target, data)); } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/digester/NodeCreateRule.java
Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { try { Node previousTop = top; if ((localName == null) || (localName.length() == 0)) { top = doc.createElement(qName); } else { top = doc.createElementNS(namespaceURI, localName); } for (int i = 0; i < atts.getLength(); i++) { Attr attr = null; if ((atts.getLocalName(i) == null) || (atts.getLocalName(i).length() == 0)) { attr = doc.createAttribute(atts.getQName(i)); attr.setNodeValue(atts.getValue(i)); ((Element)top).setAttributeNode(attr); } else { attr = doc.createAttributeNS(atts.getURI(i), atts.getLocalName(i)); attr.setNodeValue(atts.getValue(i)); ((Element)top).setAttributeNodeNS(attr); } } previousTop.appendChild(top); depth++; } catch (DOMException e) { throw new SAXException(e.getMessage(), e); } }
// in java/org/apache/tomcat/util/digester/GenericParser.java
public static SAXParser newSAXParser(Properties properties) throws ParserConfigurationException, SAXException, SAXNotRecognizedException{ SAXParserFactory factory = (SAXParserFactory)properties.get("SAXParserFactory"); SAXParser parser = factory.newSAXParser(); String schemaLocation = (String)properties.get("schemaLocation"); String schemaLanguage = (String)properties.get("schemaLanguage"); try{ if (schemaLocation != null) { parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage); parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation); } } catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); } return parser; }
// in java/org/apache/catalina/startup/XmlErrorHandler.java
Override public void error(SAXParseException exception) throws SAXException { // Collect non-fatal errors errors.add(exception); }
// in java/org/apache/catalina/startup/XmlErrorHandler.java
Override public void fatalError(SAXParseException exception) throws SAXException { // Re-throw fatal errors throw exception; }
// in java/org/apache/catalina/startup/XmlErrorHandler.java
Override public void warning(SAXParseException exception) throws SAXException { // Collect warnings warnings.add(exception); }
// in java/org/apache/catalina/util/SchemaResolver.java
Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { if (publicId != null) { digester.setPublicId(publicId); } // Has this system identifier been registered? String entityURL = null; if (publicId != null) { entityURL = entityValidator.get(publicId); } // Redirect the schema location to a local destination String key = null; if (entityURL == null && systemId != null) { key = systemId.substring(systemId.lastIndexOf('/')+1); entityURL = entityValidator.get(key); } if (entityURL == null) { return (null); } try { return (new InputSource(entityURL)); } catch (Exception e) { throw new SAXException(e); } }
5
            
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXException sx) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), sx); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (SAXException s) { // Hack - makes exception handling simpler throw new IOException(s); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (SAXException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch(SAXException saxe) { // Parse error - assume invalid content resp.sendError(WebdavStatus.SC_UNSUPPORTED_MEDIA_TYPE); return; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (SAXException e) { lockRequestType = LOCK_REFRESH; }
2
            
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXException sx) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml", location), sx); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (SAXException s) { // Hack - makes exception handling simpler throw new IOException(s); }
0
unknown (Lib) SAXNotRecognizedException 0 0 8
            
// in java/org/apache/tomcat/util/digester/Digester.java
public SAXParserFactory getFactory() throws SAXNotRecognizedException, SAXNotSupportedException, ParserConfigurationException { if (factory == null) { factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(namespaceAware); factory.setValidating(validating); if (validating) { // Enable DTD validation factory.setFeature( "http://xml.org/sax/features/validation", true); // Enable schema validation factory.setFeature( "http://apache.org/xml/features/validation/schema", true); } } return (factory); }
// in java/org/apache/tomcat/util/digester/Digester.java
public boolean getFeature(String feature) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException { return (getFactory().getFeature(feature)); }
// in java/org/apache/tomcat/util/digester/Digester.java
public void setFeature(String feature, boolean value) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException { getFactory().setFeature(feature, value); }
// in java/org/apache/tomcat/util/digester/Digester.java
public Object getProperty(String property) throws SAXNotRecognizedException, SAXNotSupportedException { return (getParser().getProperty(property)); }
// in java/org/apache/tomcat/util/digester/Digester.java
public void setProperty(String property, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { getParser().setProperty(property, value); }
// in java/org/apache/tomcat/util/digester/XercesParser.java
private static void configureXerces(SAXParserFactory factory) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException { factory.setFeature(XERCES_DYNAMIC, true); factory.setFeature(XERCES_SCHEMA, true); }
// in java/org/apache/tomcat/util/digester/ParserFeatureSetterFactory.java
public static SAXParser newSAXParser(Properties properties) throws ParserConfigurationException, SAXException, SAXNotRecognizedException, SAXNotSupportedException { if (isXercesUsed){ return XercesParser.newSAXParser(properties); } else { return GenericParser.newSAXParser(properties); } }
// in java/org/apache/tomcat/util/digester/GenericParser.java
public static SAXParser newSAXParser(Properties properties) throws ParserConfigurationException, SAXException, SAXNotRecognizedException{ SAXParserFactory factory = (SAXParserFactory)properties.get("SAXParserFactory"); SAXParser parser = factory.newSAXParser(); String schemaLocation = (String)properties.get("schemaLocation"); String schemaLanguage = (String)properties.get("schemaLanguage"); try{ if (schemaLocation != null) { parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage); parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation); } } catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); } return parser; }
2
            
// in java/org/apache/tomcat/util/digester/XercesParser.java
catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); }
// in java/org/apache/tomcat/util/digester/GenericParser.java
catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); }
0 0
unknown (Lib) SAXParseException 16
            
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void startElement( String uri, String localName, String qName, Attributes attrs) throws SAXException { AttributesImpl taglibAttrs = null; AttributesImpl nonTaglibAttrs = null; AttributesImpl nonTaglibXmlnsAttrs = null; processChars(); checkPrefixes(uri, qName, attrs); if (directivesOnly && !(JSP_URI.equals(uri) && localName.startsWith(DIRECTIVE_ACTION))) { return; } String currentPrefix = getPrefix(current.getQName()); // jsp:text must not have any subelements if (JSP_URI.equals(uri) && TEXT_ACTION.equals(current.getLocalName()) && "jsp".equals(currentPrefix)) { throw new SAXParseException( Localizer.getMessage("jsp.error.text.has_subelement"), locator); } startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); if (attrs != null) { /* * Notice that due to a bug in the underlying SAX parser, the * attributes must be enumerated in descending order. */ boolean isTaglib = false; for (int i = attrs.getLength() - 1; i >= 0; i--) { isTaglib = false; String attrQName = attrs.getQName(i); if (!attrQName.startsWith("xmlns")) { if (nonTaglibAttrs == null) { nonTaglibAttrs = new AttributesImpl(); } nonTaglibAttrs.addAttribute( attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getValue(i)); } else { if (attrQName.startsWith("xmlns:jsp")) { isTaglib = true; } else { String attrUri = attrs.getValue(i); // TaglibInfo for this uri already established in // startPrefixMapping isTaglib = pageInfo.hasTaglib(attrUri); } if (isTaglib) { if (taglibAttrs == null) { taglibAttrs = new AttributesImpl(); } taglibAttrs.addAttribute( attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getValue(i)); } else { if (nonTaglibXmlnsAttrs == null) { nonTaglibXmlnsAttrs = new AttributesImpl(); } nonTaglibXmlnsAttrs.addAttribute( attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getValue(i)); } } } } Node node = null; if (tagDependentPending && JSP_URI.equals(uri) && localName.equals(BODY_ACTION)) { tagDependentPending = false; tagDependentNesting++; current = parseStandardAction( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark); return; } if (tagDependentPending && JSP_URI.equals(uri) && localName.equals(ATTRIBUTE_ACTION)) { current = parseStandardAction( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark); return; } if (tagDependentPending) { tagDependentPending = false; tagDependentNesting++; } if (tagDependentNesting > 0) { node = new Node.UninterpretedTag( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark, current); } else if (JSP_URI.equals(uri)) { node = parseStandardAction( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark); } else { node = parseCustomAction( qName, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark, current); if (node == null) { node = new Node.UninterpretedTag( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark, current); } else { // custom action String bodyType = getBodyType((Node.CustomTag) node); if (scriptlessBodyNode == null && bodyType.equalsIgnoreCase(TagInfo.BODY_CONTENT_SCRIPTLESS)) { scriptlessBodyNode = node; } else if (TagInfo.BODY_CONTENT_TAG_DEPENDENT.equalsIgnoreCase(bodyType)) { tagDependentPending = true; } } } current = node; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void processChars() throws SAXException { if (charBuffer == null || directivesOnly) { return; } /* * JSP.6.1.1: All textual nodes that have only white space are to be * dropped from the document, except for nodes in a jsp:text element, * and any leading and trailing white-space-only textual nodes in a * jsp:attribute whose 'trim' attribute is set to FALSE, which are to * be kept verbatim. * JSP.6.2.3 defines white space characters. */ boolean isAllSpace = true; if (!(current instanceof Node.JspText) && !(current instanceof Node.NamedAttribute)) { for (int i = 0; i < charBuffer.length(); i++) { if (!(charBuffer.charAt(i) == ' ' || charBuffer.charAt(i) == '\n' || charBuffer.charAt(i) == '\r' || charBuffer.charAt(i) == '\t')) { isAllSpace = false; break; } } } if (!isAllSpace && tagDependentPending) { tagDependentPending = false; tagDependentNesting++; } if (tagDependentNesting > 0) { if (charBuffer.length() > 0) { new Node.TemplateText(charBuffer.toString(), startMark, current); } startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); charBuffer = null; return; } if ((current instanceof Node.JspText) || (current instanceof Node.NamedAttribute) || !isAllSpace) { int line = startMark.getLineNumber(); int column = startMark.getColumnNumber(); CharArrayWriter ttext = new CharArrayWriter(); int lastCh = 0, elType = 0; for (int i = 0; i < charBuffer.length(); i++) { int ch = charBuffer.charAt(i); if (ch == '\n') { column = 1; line++; } else { column++; } if ((lastCh == '$' || lastCh == '#') && ch == '{') { elType = lastCh; if (ttext.size() > 0) { new Node.TemplateText( ttext.toString(), startMark, current); ttext = new CharArrayWriter(); //We subtract two from the column number to //account for the '[$,#]{' that we've already parsed startMark = new Mark(ctxt, path, line, column - 2); } // following "${" || "#{" to first unquoted "}" i++; boolean singleQ = false; boolean doubleQ = false; lastCh = 0; for (;; i++) { if (i >= charBuffer.length()) { throw new SAXParseException( Localizer.getMessage( "jsp.error.unterminated", (char) elType + "{"), locator); } ch = charBuffer.charAt(i); if (ch == '\n') { column = 1; line++; } else { column++; } if (lastCh == '\\' && (singleQ || doubleQ)) { ttext.write(ch); lastCh = 0; continue; } if (ch == '}') { new Node.ELExpression((char) elType, ttext.toString(), startMark, current); ttext = new CharArrayWriter(); startMark = new Mark(ctxt, path, line, column); break; } if (ch == '"') doubleQ = !doubleQ; else if (ch == '\'') singleQ = !singleQ; ttext.write(ch); lastCh = ch; } } else if (lastCh == '\\' && (ch == '$' || ch == '#')) { if (pageInfo.isELIgnored()) { ttext.write('\\'); } ttext.write(ch); ch = 0; // Not start of EL anymore } else { if (lastCh == '$' || lastCh == '#' || lastCh == '\\') { ttext.write(lastCh); } if (ch != '$' && ch != '#' && ch != '\\') { ttext.write(ch); } } lastCh = ch; } if (lastCh == '$' || lastCh == '#' || lastCh == '\\') { ttext.write(lastCh); } if (ttext.size() > 0) { new Node.TemplateText(ttext.toString(), startMark, current); } } startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); charBuffer = null; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void endElement(String uri, String localName, String qName) throws SAXException { processChars(); if (directivesOnly && !(JSP_URI.equals(uri) && localName.startsWith(DIRECTIVE_ACTION))) { return; } if (current instanceof Node.NamedAttribute) { boolean isTrim = ((Node.NamedAttribute)current).isTrim(); Node.Nodes subElems = ((Node.NamedAttribute)current).getBody(); for (int i = 0; subElems != null && i < subElems.size(); i++) { Node subElem = subElems.getNode(i); if (!(subElem instanceof Node.TemplateText)) { continue; } // Ignore any whitespace (including spaces, carriage returns, // line feeds, and tabs, that appear at the beginning and at // the end of the body of the <jsp:attribute> action, if the // action's 'trim' attribute is set to TRUE (default). // In addition, any textual nodes in the <jsp:attribute> that // have only white space are dropped from the document, with // the exception of leading and trailing white-space-only // textual nodes in a <jsp:attribute> whose 'trim' attribute // is set to FALSE, which must be kept verbatim. if (i == 0) { if (isTrim) { ((Node.TemplateText)subElem).ltrim(); } } else if (i == subElems.size() - 1) { if (isTrim) { ((Node.TemplateText)subElem).rtrim(); } } else { if (((Node.TemplateText)subElem).isAllSpace()) { subElems.remove(subElem); } } } } else if (current instanceof Node.ScriptingElement) { checkScriptingBody((Node.ScriptingElement)current); } if ( isTagDependent(current)) { tagDependentNesting--; } if (scriptlessBodyNode != null && current.equals(scriptlessBodyNode)) { scriptlessBodyNode = null; } if (current instanceof Node.CustomTag) { String bodyType = getBodyType((Node.CustomTag) current); if (TagInfo.BODY_CONTENT_EMPTY.equalsIgnoreCase(bodyType)) { // Children - if any - must be JSP attributes Node.Nodes children = current.getBody(); if (children != null && children.size() > 0) { for (int i = 0; i < children.size(); i++) { Node child = children.getNode(i); if (!(child instanceof Node.NamedAttribute)) { throw new SAXParseException(Localizer.getMessage( "jasper.error.emptybodycontent.nonempty", current.qName), locator); } } } } } if (current.getParent() != null) { current = current.getParent(); } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
Override public void startPrefixMapping(String prefix, String uri) throws SAXException { TagLibraryInfo taglibInfo; if (directivesOnly && !(JSP_URI.equals(uri))) { return; } try { taglibInfo = getTaglibInfo(prefix, uri); } catch (JasperException je) { throw new SAXParseException( Localizer.getMessage("jsp.error.could.not.add.taglibraries"), locator, je); } if (taglibInfo != null) { if (pageInfo.getTaglib(uri) == null) { pageInfo.addTaglib(uri, taglibInfo); } pageInfo.pushPrefixMapping(prefix, uri); } else { pageInfo.pushPrefixMapping(prefix, null); } }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private Node parseStandardAction( String qName, String localName, Attributes nonTaglibAttrs, Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs, Mark start) throws SAXException { Node node = null; if (localName.equals(ROOT_ACTION)) { if (!(current instanceof Node.Root)) { throw new SAXParseException( Localizer.getMessage("jsp.error.nested_jsproot"), locator); } node = new Node.JspRoot( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); if (isTop) { pageInfo.setHasJspRoot(true); } } else if (localName.equals(PAGE_DIRECTIVE_ACTION)) { if (isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.istagfile", localName), locator); } node = new Node.PageDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); String imports = nonTaglibAttrs.getValue("import"); // There can only be one 'import' attribute per page directive if (imports != null) { ((Node.PageDirective)node).addImport(imports); } } else if (localName.equals(INCLUDE_DIRECTIVE_ACTION)) { node = new Node.IncludeDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); processIncludeDirective(nonTaglibAttrs.getValue("file"), node); } else if (localName.equals(DECLARATION_ACTION)) { if (scriptlessBodyNode != null) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException( Localizer.getMessage( "jsp.error.no.scriptlets", localName), locator); } node = new Node.Declaration( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(SCRIPTLET_ACTION)) { if (scriptlessBodyNode != null) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException( Localizer.getMessage( "jsp.error.no.scriptlets", localName), locator); } node = new Node.Scriptlet( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(EXPRESSION_ACTION)) { if (scriptlessBodyNode != null) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException( Localizer.getMessage( "jsp.error.no.scriptlets", localName), locator); } node = new Node.Expression( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(USE_BEAN_ACTION)) { node = new Node.UseBean( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(SET_PROPERTY_ACTION)) { node = new Node.SetProperty( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(GET_PROPERTY_ACTION)) { node = new Node.GetProperty( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(INCLUDE_ACTION)) { node = new Node.IncludeAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(FORWARD_ACTION)) { node = new Node.ForwardAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(PARAM_ACTION)) { node = new Node.ParamAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(PARAMS_ACTION)) { node = new Node.ParamsAction( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(PLUGIN_ACTION)) { node = new Node.PlugIn( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(TEXT_ACTION)) { node = new Node.JspText( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(BODY_ACTION)) { node = new Node.JspBody( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(ATTRIBUTE_ACTION)) { node = new Node.NamedAttribute( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(OUTPUT_ACTION)) { node = new Node.JspOutput( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(TAG_DIRECTIVE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.TagDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); String imports = nonTaglibAttrs.getValue("import"); // There can only be one 'import' attribute per tag directive if (imports != null) { ((Node.TagDirective)node).addImport(imports); } } else if (localName.equals(ATTRIBUTE_DIRECTIVE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.AttributeDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(VARIABLE_DIRECTIVE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.VariableDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(INVOKE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.InvokeAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(DOBODY_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.DoBodyAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(ELEMENT_ACTION)) { node = new Node.JspElement( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(FALLBACK_ACTION)) { node = new Node.FallBackAction( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else { throw new SAXParseException( Localizer.getMessage( "jsp.error.xml.badStandardAction", localName), locator); } return node; }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
private void processIncludeDirective(String fname, Node parent) throws SAXException { if (fname == null) { return; } try { parserController.parse(fname, parent, null); } catch (FileNotFoundException fnfe) { throw new SAXParseException( Localizer.getMessage("jsp.error.file.not.found", fname), locator, fnfe); } catch (Exception e) { throw new SAXException(e); } }
2
            
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (JasperException je) { throw new SAXParseException( Localizer.getMessage("jsp.error.could.not.add.taglibraries"), locator, je); }
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (FileNotFoundException fnfe) { throw new SAXParseException( Localizer.getMessage("jsp.error.file.not.found", fname), locator, fnfe); }
0 5
            
// in java/org/apache/jasper/compiler/JspDocumentParser.java
catch (SAXParseException e) { jspDocParser.err.jspError (new Mark(jspDocParser.ctxt, path, e.getLineNumber(), e.getColumnNumber()), e.getMessage()); }
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXParseException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (SAXParseException e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); log.error(sm.getString("contextConfig.defaultPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (SAXParseException e) { log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e); log.error(sm.getString("contextConfig.applicationPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; }
// in java/org/apache/catalina/startup/Catalina.java
catch (SAXParseException spe) { log.warn("Catalina.start using " + getConfigFile() + ": " + spe.getMessage()); return; }
1
            
// in java/org/apache/jasper/xmlparser/ParserUtils.java
catch (SAXParseException ex) { throw new JasperException (Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); }
0
unknown (Lib) SQLException 4
            
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
public Object unwrap(Class<?> iface) throws SQLException { if (iface == DataSource.class) { return ds; } else { throw new SQLException("Not a wrapper of "+iface.getName()); } }
// in java/org/apache/catalina/realm/JDBCRealm.java
protected Connection open() throws SQLException { // Do nothing if there is a database connection already open if (dbConnection != null) return (dbConnection); // Instantiate our database driver if necessary if (driver == null) { try { Class<?> clazz = Class.forName(driverName); driver = (Driver) clazz.newInstance(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); } } // Open a new connection Properties props = new Properties(); if (connectionName != null) props.put("user", connectionName); if (connectionPassword != null) props.put("password", connectionPassword); dbConnection = driver.connect(connectionURL, props); if (dbConnection == null) { throw new SQLException(sm.getString( "jdbcRealm.open.invalidurl",driverName, connectionURL)); } dbConnection.setAutoCommit(false); return (dbConnection); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
protected void open() throws SQLException { // Do nothing if there is a database connection already open if (conn != null) { return ; } // Instantiate our database driver if necessary if (driver == null) { try { Class<?> clazz = Class.forName(driverName); driver = (Driver) clazz.newInstance(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); } } // Open a new connection Properties props = new Properties(); if (connectionName != null) { props.put("user", connectionName); } if (connectionPassword != null) { props.put("password", connectionPassword); } conn = driver.connect(connectionURL, props); conn.setAutoCommit(true); String logPattern = pattern; if (logPattern.equals("common")) { ps = conn.prepareStatement ("INSERT INTO " + tableName + " (" + remoteHostField + ", " + userField + ", " + timestampField +", " + queryField + ", " + statusField + ", " + bytesField + ") VALUES(?, ?, ?, ?, ?, ?)"); } else if (logPattern.equals("combined")) { ps = conn.prepareStatement ("INSERT INTO " + tableName + " (" + remoteHostField + ", " + userField + ", " + timestampField + ", " + queryField + ", " + statusField + ", " + bytesField + ", " + virtualHostField + ", " + methodField + ", " + refererField + ", " + userAgentField + ") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); } }
2
            
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
10
            
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
public Object unwrap(Class<?> iface) throws SQLException { if (iface == DataSource.class) { return ds; } else { throw new SQLException("Not a wrapper of "+iface.getName()); } }
// in java/org/apache/catalina/loader/JdbcLeakPrevention.java
public List<String> clearJdbcDriverRegistrations() throws SQLException { List<String> driverNames = new ArrayList<String>(); /* * DriverManager.getDrivers() has a nasty side-effect of registering * drivers that are visible to this class loader but haven't yet been * loaded. Therefore, the first call to this method a) gets the list * of originally loaded drivers and b) triggers the unwanted * side-effect. The second call gets the complete list of drivers * ensuring that both original drivers and any loaded as a result of the * side-effects are all de-registered. */ HashSet<Driver> originalDrivers = new HashSet<Driver>(); Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { originalDrivers.add(drivers.nextElement()); } drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); // Only unload the drivers this web app loaded if (driver.getClass().getClassLoader() != this.getClass().getClassLoader()) { continue; } // Only report drivers that were originally registered. Skip any // that were registered as a side-effect of this code. if (originalDrivers.contains(driver)) { driverNames.add(driver.getClass().getCanonicalName()); } DriverManager.deregisterDriver(driver); } return driverNames; }
// in java/org/apache/catalina/realm/DataSourceRealm.java
private PreparedStatement credentials(Connection dbConnection, String username) throws SQLException { PreparedStatement credentials = dbConnection.prepareStatement(preparedCredentials); credentials.setString(1, username); return (credentials); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
private PreparedStatement roles(Connection dbConnection, String username) throws SQLException { PreparedStatement roles = dbConnection.prepareStatement(preparedRoles); roles.setString(1, username); return (roles); }
// in java/org/apache/catalina/realm/JDBCRealm.java
protected PreparedStatement credentials(Connection dbConnection, String username) throws SQLException { if (preparedCredentials == null) { StringBuilder sb = new StringBuilder("SELECT "); sb.append(userCredCol); sb.append(" FROM "); sb.append(userTable); sb.append(" WHERE "); sb.append(userNameCol); sb.append(" = ?"); if(containerLog.isDebugEnabled()) { containerLog.debug("credentials query: " + sb.toString()); } preparedCredentials = dbConnection.prepareStatement(sb.toString()); } if (username == null) { preparedCredentials.setNull(1,java.sql.Types.VARCHAR); } else { preparedCredentials.setString(1, username); } return (preparedCredentials); }
// in java/org/apache/catalina/realm/JDBCRealm.java
protected Connection open() throws SQLException { // Do nothing if there is a database connection already open if (dbConnection != null) return (dbConnection); // Instantiate our database driver if necessary if (driver == null) { try { Class<?> clazz = Class.forName(driverName); driver = (Driver) clazz.newInstance(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); } } // Open a new connection Properties props = new Properties(); if (connectionName != null) props.put("user", connectionName); if (connectionPassword != null) props.put("password", connectionPassword); dbConnection = driver.connect(connectionURL, props); if (dbConnection == null) { throw new SQLException(sm.getString( "jdbcRealm.open.invalidurl",driverName, connectionURL)); } dbConnection.setAutoCommit(false); return (dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
protected synchronized PreparedStatement roles(Connection dbConnection, String username) throws SQLException { if (preparedRoles == null) { StringBuilder sb = new StringBuilder("SELECT "); sb.append(roleNameCol); sb.append(" FROM "); sb.append(userRoleTable); sb.append(" WHERE "); sb.append(userNameCol); sb.append(" = ?"); preparedRoles = dbConnection.prepareStatement(sb.toString()); } preparedRoles.setString(1, username); return (preparedRoles); }
// in java/org/apache/catalina/session/JDBCStore.java
private void remove(String id, Connection _conn) throws SQLException { if (preparedRemoveSql == null) { String removeSql = "DELETE FROM " + sessionTable + " WHERE " + sessionIdCol + " = ? AND " + sessionAppCol + " = ?"; preparedRemoveSql = _conn.prepareStatement(removeSql); } preparedRemoveSql.setString(1, id); preparedRemoveSql.setString(2, getName()); preparedRemoveSql.execute(); }
// in java/org/apache/catalina/session/JDBCStore.java
protected Connection open() throws SQLException { // Do nothing if there is a database connection already open if (dbConnection != null) return (dbConnection); if (dataSourceName != null && dataSource == null) { Context initCtx; try { initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); this.dataSource = (DataSource) envCtx.lookup(this.dataSourceName); } catch (NamingException e) { manager.getContainer().getLogger().error( sm.getString(getStoreName() + ".wrongDataSource", this.dataSourceName), e); } } if (dataSource != null) { return dataSource.getConnection(); } // Instantiate our database driver if necessary if (driver == null) { try { Class<?> clazz = Class.forName(driverName); driver = (Driver) clazz.newInstance(); } catch (ClassNotFoundException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); } catch (InstantiationException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); } catch (IllegalAccessException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException", ex.toString())); } } // Open a new connection Properties props = new Properties(); if (connectionName != null) props.put("user", connectionName); if (connectionPassword != null) props.put("password", connectionPassword); dbConnection = driver.connect(connectionURL, props); dbConnection.setAutoCommit(true); return (dbConnection); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
protected void open() throws SQLException { // Do nothing if there is a database connection already open if (conn != null) { return ; } // Instantiate our database driver if necessary if (driver == null) { try { Class<?> clazz = Class.forName(driverName); driver = (Driver) clazz.newInstance(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); } } // Open a new connection Properties props = new Properties(); if (connectionName != null) { props.put("user", connectionName); } if (connectionPassword != null) { props.put("password", connectionPassword); } conn = driver.connect(connectionURL, props); conn.setAutoCommit(true); String logPattern = pattern; if (logPattern.equals("common")) { ps = conn.prepareStatement ("INSERT INTO " + tableName + " (" + remoteHostField + ", " + userField + ", " + timestampField +", " + queryField + ", " + statusField + ", " + bytesField + ") VALUES(?, ?, ?, ?, ?, ?)"); } else if (logPattern.equals("combined")) { ps = conn.prepareStatement ("INSERT INTO " + tableName + " (" + remoteHostField + ", " + userField + ", " + timestampField + ", " + queryField + ", " + statusField + ", " + bytesField + ", " + virtualHostField + ", " + methodField + ", " + refererField + ", " + userAgentField + ") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); } }
29
            
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (SQLException e) { containerLog.error("Exception committing connection before closing:", e); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (SQLException e) { containerLog.error(sm.getString("dataSourceRealm.close"), e); // Just log it here }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch(SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getPassword.exception", username)); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getPassword.exception", username)); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch(SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getRoles.exception", username)); }
// in java/org/apache/catalina/realm/DataSourceRealm.java
catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getRoles.exception", username)); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { // Log the problem for posterity containerLog.error(sm.getString("jdbcRealm.exception"), e); // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { containerLog.warn(sm.getString("jdbcRealm.close"), e); // Just log it here }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { // Log the problem for posterity containerLog.error(sm.getString("jdbcRealm.exception"), e); // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch(SQLException e) { containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet")); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { // Log the problem for posterity containerLog.error(sm.getString("jdbcRealm.exception"), e); // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (SQLException e) { containerLog.error(sm.getString("jdbcRealm.open"), e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); keys = new String[0]; // Close the connection so that it gets reopened next time if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { // Ignore }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { // Ignore }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { // Ignore }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".SQLException", e)); if (dbConnection != null) close(dbConnection); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException ex) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionSQLException", ex.toString())); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".commitSQLException"), e); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".close", e.toString())); // Just log it here }
// in java/org/apache/catalina/session/JDBCStore.java
catch (SQLException e) { // Ignore }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { // Log the problem for posterity container.getLogger().error(sm.getString("jdbcAccessLogValve.exception"), e); // Close the connection so that it gets reopened next time if (conn != null) { close(); } }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { container.getLogger().error(sm.getString("jdbcAccessLogValeve.close"), e); // Just log it here }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { throw new LifecycleException(e); }
1
            
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (SQLException e) { throw new LifecycleException(e); }
0
checked (Domain) SSIStopProcessingException
public class SSIStopProcessingException extends Exception {

    private static final long serialVersionUID = 1L;
    // No specific functionality for this class
}
5
            
// in java/org/apache/catalina/ssi/SSISet.java
Override public long process(SSIMediator ssiMediator, String commandName, String[] paramNames, String[] paramValues, PrintWriter writer) throws SSIStopProcessingException { long lastModified = 0; String errorMessage = ssiMediator.getConfigErrMsg(); String variableName = null; for (int i = 0; i < paramNames.length; i++) { String paramName = paramNames[i]; String paramValue = paramValues[i]; if (paramName.equalsIgnoreCase("var")) { variableName = paramValue; } else if (paramName.equalsIgnoreCase("value")) { if (variableName != null) { String substitutedValue = ssiMediator .substituteVariables(paramValue); ssiMediator.setVariableValue(variableName, substitutedValue); lastModified = System.currentTimeMillis(); } else { ssiMediator.log("#set--no variable specified"); writer.write(errorMessage); throw new SSIStopProcessingException(); } } else { ssiMediator.log("#set--Invalid attribute: " + paramName); writer.write(errorMessage); throw new SSIStopProcessingException(); } } return lastModified; }
// in java/org/apache/catalina/ssi/SSIConditional.java
Override public long process(SSIMediator ssiMediator, String commandName, String[] paramNames, String[] paramValues, PrintWriter writer) throws SSIStopProcessingException { // Assume anything using conditionals was modified by it long lastModified = System.currentTimeMillis(); // Retrieve the current state information SSIConditionalState state = ssiMediator.getConditionalState(); if ("if".equalsIgnoreCase(commandName)) { // Do nothing if we are nested in a false branch // except count it if (state.processConditionalCommandsOnly) { state.nestingCount++; return lastModified; } state.nestingCount = 0; // Evaluate the expression if (evaluateArguments(paramNames, paramValues, ssiMediator)) { // No more branches can be taken for this if block state.branchTaken = true; } else { // Do not process this branch state.processConditionalCommandsOnly = true; state.branchTaken = false; } } else if ("elif".equalsIgnoreCase(commandName)) { // No need to even execute if we are nested in // a false branch if (state.nestingCount > 0) return lastModified; // If a branch was already taken in this if block // then disable output and return if (state.branchTaken) { state.processConditionalCommandsOnly = true; return lastModified; } // Evaluate the expression if (evaluateArguments(paramNames, paramValues, ssiMediator)) { // Turn back on output and mark the branch state.processConditionalCommandsOnly = false; state.branchTaken = true; } else { // Do not process this branch state.processConditionalCommandsOnly = true; state.branchTaken = false; } } else if ("else".equalsIgnoreCase(commandName)) { // No need to even execute if we are nested in // a false branch if (state.nestingCount > 0) return lastModified; // If we've already taken another branch then // disable output otherwise enable it. state.processConditionalCommandsOnly = state.branchTaken; // And in any case, it's safe to say a branch // has been taken. state.branchTaken = true; } else if ("endif".equalsIgnoreCase(commandName)) { // If we are nested inside a false branch then pop out // one level on the nesting count if (state.nestingCount > 0) { state.nestingCount--; return lastModified; } // Turn output back on state.processConditionalCommandsOnly = false; // Reset the branch status for any outer if blocks, // since clearly we took a branch to have gotten here // in the first place. state.branchTaken = true; } else { throw new SSIStopProcessingException(); //throw new SsiCommandException( "Not a conditional command:" + // cmdName ); } return lastModified; }
// in java/org/apache/catalina/ssi/SSIConditional.java
private boolean evaluateArguments(String[] names, String[] values, SSIMediator ssiMediator) throws SSIStopProcessingException { String expr = getExpression(names, values); if (expr == null) { throw new SSIStopProcessingException(); //throw new SsiCommandException( "No expression specified." ); } try { ExpressionParseTree tree = new ExpressionParseTree(expr, ssiMediator); return tree.evaluateTree(); } catch (ParseException e) { //throw new SsiCommandException( "Error parsing expression." ); throw new SSIStopProcessingException(); } }
1
            
// in java/org/apache/catalina/ssi/SSIConditional.java
catch (ParseException e) { //throw new SsiCommandException( "Error parsing expression." ); throw new SSIStopProcessingException(); }
3
            
// in java/org/apache/catalina/ssi/SSISet.java
Override public long process(SSIMediator ssiMediator, String commandName, String[] paramNames, String[] paramValues, PrintWriter writer) throws SSIStopProcessingException { long lastModified = 0; String errorMessage = ssiMediator.getConfigErrMsg(); String variableName = null; for (int i = 0; i < paramNames.length; i++) { String paramName = paramNames[i]; String paramValue = paramValues[i]; if (paramName.equalsIgnoreCase("var")) { variableName = paramValue; } else if (paramName.equalsIgnoreCase("value")) { if (variableName != null) { String substitutedValue = ssiMediator .substituteVariables(paramValue); ssiMediator.setVariableValue(variableName, substitutedValue); lastModified = System.currentTimeMillis(); } else { ssiMediator.log("#set--no variable specified"); writer.write(errorMessage); throw new SSIStopProcessingException(); } } else { ssiMediator.log("#set--Invalid attribute: " + paramName); writer.write(errorMessage); throw new SSIStopProcessingException(); } } return lastModified; }
// in java/org/apache/catalina/ssi/SSIConditional.java
Override public long process(SSIMediator ssiMediator, String commandName, String[] paramNames, String[] paramValues, PrintWriter writer) throws SSIStopProcessingException { // Assume anything using conditionals was modified by it long lastModified = System.currentTimeMillis(); // Retrieve the current state information SSIConditionalState state = ssiMediator.getConditionalState(); if ("if".equalsIgnoreCase(commandName)) { // Do nothing if we are nested in a false branch // except count it if (state.processConditionalCommandsOnly) { state.nestingCount++; return lastModified; } state.nestingCount = 0; // Evaluate the expression if (evaluateArguments(paramNames, paramValues, ssiMediator)) { // No more branches can be taken for this if block state.branchTaken = true; } else { // Do not process this branch state.processConditionalCommandsOnly = true; state.branchTaken = false; } } else if ("elif".equalsIgnoreCase(commandName)) { // No need to even execute if we are nested in // a false branch if (state.nestingCount > 0) return lastModified; // If a branch was already taken in this if block // then disable output and return if (state.branchTaken) { state.processConditionalCommandsOnly = true; return lastModified; } // Evaluate the expression if (evaluateArguments(paramNames, paramValues, ssiMediator)) { // Turn back on output and mark the branch state.processConditionalCommandsOnly = false; state.branchTaken = true; } else { // Do not process this branch state.processConditionalCommandsOnly = true; state.branchTaken = false; } } else if ("else".equalsIgnoreCase(commandName)) { // No need to even execute if we are nested in // a false branch if (state.nestingCount > 0) return lastModified; // If we've already taken another branch then // disable output otherwise enable it. state.processConditionalCommandsOnly = state.branchTaken; // And in any case, it's safe to say a branch // has been taken. state.branchTaken = true; } else if ("endif".equalsIgnoreCase(commandName)) { // If we are nested inside a false branch then pop out // one level on the nesting count if (state.nestingCount > 0) { state.nestingCount--; return lastModified; } // Turn output back on state.processConditionalCommandsOnly = false; // Reset the branch status for any outer if blocks, // since clearly we took a branch to have gotten here // in the first place. state.branchTaken = true; } else { throw new SSIStopProcessingException(); //throw new SsiCommandException( "Not a conditional command:" + // cmdName ); } return lastModified; }
// in java/org/apache/catalina/ssi/SSIConditional.java
private boolean evaluateArguments(String[] names, String[] values, SSIMediator ssiMediator) throws SSIStopProcessingException { String expr = getExpression(names, values); if (expr == null) { throw new SSIStopProcessingException(); //throw new SsiCommandException( "No expression specified." ); } try { ExpressionParseTree tree = new ExpressionParseTree(expr, ssiMediator); return tree.evaluateTree(); } catch (ParseException e) { //throw new SsiCommandException( "Error parsing expression." ); throw new SSIStopProcessingException(); } }
1
            
// in java/org/apache/catalina/ssi/SSIProcessor.java
catch (SSIStopProcessingException e) { //If we are here, then we have already stopped processing, so all // is good }
0 0
unknown (Lib) SSLException 1
            
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
protected void handShake() throws IOException { if( ssl.getWantClientAuth() ) { log.debug(sm.getString("jsseSupport.noCertWant")); } else { ssl.setNeedClientAuth(true); } if (ssl.getEnabledCipherSuites().length == 0) { // Handshake is never going to be successful. // Assume this is because handshakes are disabled log.warn(sm.getString("jsseSupport.serverRenegDisabled")); session.invalidate(); ssl.close(); return; } InputStream in = ssl.getInputStream(); int oldTimeout = ssl.getSoTimeout(); ssl.setSoTimeout(1000); byte[] b = new byte[1]; listener.reset(); ssl.startHandshake(); int maxTries = 60; // 60 * 1000 = example 1 minute time out for (int i = 0; i < maxTries; i++) { if (log.isTraceEnabled()) log.trace("Reading for try #" + i); try { int read = in.read(b); if (read > 0) { // Shouldn't happen as all input should have been swallowed // before trying to do the handshake. If it does, something // went wrong so lets bomb out now. throw new SSLException( sm.getString("jsseSupport.unexpectedData")); } } catch(SSLException sslex) { log.info(sm.getString("jsseSupport.clientCertError"), sslex); throw sslex; } catch (IOException e) { // ignore - presumably the timeout } if (listener.completed) { break; } } ssl.setSoTimeout(oldTimeout); if (listener.completed == false) { throw new SocketException("SSL Cert handshake timeout"); } }
0 0 3
            
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch(SSLException sslex) { log.info(sm.getString("jsseSupport.clientCertError"), sslex); throw sslex; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException e){ throw new SocketException("SSL handshake error" + e.toString()); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException ssle) { // SSL configuration is invalid. Possibly cert doesn't match ciphers IOException ioe = new IOException(sm.getString( "jsse.invalid_ssl_conf", ssle.getMessage())); ioe.initCause(ssle); throw ioe; }
3
            
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch(SSLException sslex) { log.info(sm.getString("jsseSupport.clientCertError"), sslex); throw sslex; }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException e){ throw new SocketException("SSL handshake error" + e.toString()); }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException ssle) { // SSL configuration is invalid. Possibly cert doesn't match ciphers IOException ioe = new IOException(sm.getString( "jsse.invalid_ssl_conf", ssle.getMessage())); ioe.initCause(ssle); throw ioe; }
0
unknown (Lib) SecurityException 4
            
// in java/org/apache/catalina/loader/WebappClassLoader.java
protected Class<?> findClassInternal(String name) throws ClassNotFoundException { if (!validate(name)) throw new ClassNotFoundException(name); String tempPath = name.replace('.', '/'); String classPath = tempPath + ".class"; ResourceEntry entry = null; if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, classPath); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, classPath); } if (entry == null) throw new ClassNotFoundException(name); Class<?> clazz = entry.loadedClass; if (clazz != null) return clazz; synchronized (this) { clazz = entry.loadedClass; if (clazz != null) return clazz; if (entry.binaryContent == null) throw new ClassNotFoundException(name); // Looking up the package String packageName = null; int pos = name.lastIndexOf('.'); if (pos != -1) packageName = name.substring(0, pos); Package pkg = null; if (packageName != null) { pkg = getPackage(packageName); // Define the package (if null) if (pkg == null) { try { if (entry.manifest == null) { definePackage(packageName, null, null, null, null, null, null, null); } else { definePackage(packageName, entry.manifest, entry.codeBase); } } catch (IllegalArgumentException e) { // Ignore: normal error due to dual definition of package } pkg = getPackage(packageName); } } if (securityManager != null) { // Checking sealing if (pkg != null) { boolean sealCheck = true; if (pkg.isSealed()) { sealCheck = pkg.isSealed(entry.codeBase); } else { sealCheck = (entry.manifest == null) || !isPackageSealed(packageName, entry.manifest); } if (!sealCheck) throw new SecurityException ("Sealing violation loading " + name + " : Package " + packageName + " is sealed."); } } try { clazz = defineClass(name, entry.binaryContent, 0, entry.binaryContent.length, new CodeSource(entry.codeBase, entry.certificates)); } catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); } entry.loadedClass = clazz; entry.binaryContent = null; entry.source = null; entry.codeBase = null; entry.manifest = null; entry.certificates = null; } return clazz; }
// in java/org/apache/catalina/connector/Request.java
Override public void setAttribute(String name, Object value) { // Name cannot be null if (name == null) { throw new IllegalArgumentException (sm.getString("coyoteRequest.setAttribute.namenull")); } // Null value is the same as removeAttribute() if (value == null) { removeAttribute(name); return; } // Special attributes SpecialAttributeAdapter adapter = specialAttributes.get(name); if (adapter != null) { adapter.set(this, name, value); return; } // Add or replace the specified attribute // Check for read only attribute // requests are per thread so synchronization unnecessary if (readOnlyAttributes.containsKey(name)) { return; } // Do the security check before any updates are made if (Globals.IS_SECURITY_ENABLED && name.equals(Globals.SENDFILE_FILENAME_ATTR)) { // Use the canonical file name to avoid any possible symlink and // relative path issues String canonicalPath; try { canonicalPath = new File(value.toString()).getCanonicalPath(); } catch (IOException e) { throw new SecurityException(sm.getString( "coyoteRequest.sendfileNotCanonical", value), e); } // Sendfile is performed in Tomcat's security context so need to // check if the web app is permitted to access the file while still // in the web app's security context System.getSecurityManager().checkRead(canonicalPath); // Update the value so the canonical path is used value = canonicalPath; } Object oldValue = attributes.put(name, value); // Pass special attributes to the native layer if (name.startsWith("org.apache.tomcat.")) { coyoteRequest.setAttribute(name, value); } // Notify interested application event listeners notifyAttributeAssigned(name, value, oldValue); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
private void checkAccess(Class<?> clazz) { if (privileged) { return; } if (Filter.class.isAssignableFrom(clazz)) { checkAccess(clazz, restrictedFilters); } else if (Servlet.class.isAssignableFrom(clazz)) { if (ContainerServlet.class.isAssignableFrom(clazz)) { throw new SecurityException("Restricted (ContainerServlet) " + clazz); } checkAccess(clazz, restrictedServlets); } else { checkAccess(clazz, restrictedListeners); } }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
private void checkAccess(Class<?> clazz, Properties restricted) { while (clazz != null) { if ("restricted".equals(restricted.getProperty(clazz.getName()))) { throw new SecurityException("Restricted " + clazz); } clazz = clazz.getSuperclass(); } }
1
            
// in java/org/apache/catalina/connector/Request.java
catch (IOException e) { throw new SecurityException(sm.getString( "coyoteRequest.sendfileNotCanonical", value), e); }
3
            
// in java/org/apache/juli/ClassLoaderLogManager.java
Override public void readConfiguration() throws IOException, SecurityException { checkAccess(); readConfiguration(Thread.currentThread().getContextClassLoader()); }
// in java/org/apache/juli/ClassLoaderLogManager.java
Override public void readConfiguration(InputStream is) throws IOException, SecurityException { checkAccess(); reset(); readConfiguration(is, Thread.currentThread().getContextClassLoader()); }
// in java/org/apache/juli/ClassLoaderLogManager.java
Override public void reset() throws SecurityException { Thread thread = Thread.currentThread(); if (thread.getClass().getName().startsWith( "java.util.logging.LogManager$")) { // Ignore the call from java.util.logging.LogManager.Cleaner, // because we have our own shutdown hook return; } ClassLoader classLoader = thread.getContextClassLoader(); ClassLoaderLogInfo clLogInfo = getClassLoaderInfo(classLoader); resetLoggers(clLogInfo); super.reset(); }
13
            
// in java/org/apache/jasper/servlet/JasperLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; se.printStackTrace(); throw new ClassNotFoundException(error); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (SecurityException ex1) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: SecurityException for " + o.getClass() + " " + name + "=" + value + ")", ex1); }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (SecurityException ex1) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: SecurityException for " + o.getClass() + " " + name + ")", ex1); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { return; }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); }
// in java/org/apache/catalina/deploy/NamingResources.java
catch (SecurityException e) { log.debug(sm.getString("namingResources.cleanupCloseSecurity", closeMethod, name, container)); return; }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch (SecurityException e) { log.error(sm.getString("jreLeakListener.gcDaemonFail"), e); }
// in java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java
catch(SecurityException e) { // Ignore. Don't need call to getPolicy() to be // successful, just need to trigger static initializer. }
// in java/javax/el/ExpressionFactory.java
catch (SecurityException se) { throw new ELException(se); }
3
            
// in java/org/apache/jasper/servlet/JasperLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; se.printStackTrace(); throw new ClassNotFoundException(error); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); }
// in java/javax/el/ExpressionFactory.java
catch (SecurityException se) { throw new ELException(se); }
1
unknown (Lib) ServiceException 2 1
            
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
catch (Exception e) { throw new ServiceException(e); }
2
            
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
private Remote getProxyPortClass(Object[] args) throws ServiceException { Class<?> serviceendpointClass = (Class<?>) args[0]; if (this.portComponentRef == null) return service.getPort(serviceendpointClass); QName portname = this.portComponentRef.get(serviceendpointClass.getName()); if (portname != null) { return service.getPort(portname, serviceendpointClass); } else { return service.getPort(serviceendpointClass); } }
0 0 0
unknown (Lib) ServiceUnavailableException 0 0 0 2
            
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.warn(sm.getString("jndiRealm.exception"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); }
0 0
checked (Domain) ServletException
public class ServletException extends Exception {

    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new servlet exception.
     */
    public ServletException() {
        super();
    }

    /**
     * Constructs a new servlet exception with the specified message. The
     * message can be written to the server log and/or displayed for the user.
     *
     * @param message
     *            a <code>String</code> specifying the text of the exception
     *            message
     */
    public ServletException(String message) {
        super(message);
    }

    /**
     * Constructs a new servlet exception when the servlet needs to throw an
     * exception and include a message about the "root cause" exception that
     * interfered with its normal operation, including a description message.
     *
     * @param message
     *            a <code>String</code> containing the text of the exception
     *            message
     * @param rootCause
     *            the <code>Throwable</code> exception that interfered with the
     *            servlet's normal operation, making this servlet exception
     *            necessary
     */
    public ServletException(String message, Throwable rootCause) {
        super(message, rootCause);
    }

    /**
     * Constructs a new servlet exception when the servlet needs to throw an
     * exception and include a message about the "root cause" exception that
     * interfered with its normal operation. The exception's message is based on
     * the localized message of the underlying exception.
     * <p>
     * This method calls the <code>getLocalizedMessage</code> method on the
     * <code>Throwable</code> exception to get a localized exception message.
     * When subclassing <code>ServletException</code>, this method can be
     * overridden to create an exception message designed for a specific locale.
     *
     * @param rootCause
     *            the <code>Throwable</code> exception that interfered with the
     *            servlet's normal operation, making the servlet exception
     *            necessary
     */
    public ServletException(Throwable rootCause) {
        super(rootCause);
    }

    /**
     * Returns the exception that caused this servlet exception.
     *
     * @return the <code>Throwable</code> that caused this servlet exception
     */
    public Throwable getRootCause() {
        return getCause();
    }
}
58
            
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doHandlePageException(Throwable t) throws IOException, ServletException { if (errorPageURL != null && !errorPageURL.equals("")) { /* * Set request attributes. Do not set the * javax.servlet.error.exception attribute here (instead, set in the * generated servlet code for the error page) in order to prevent * the ErrorReportValve, which is invoked as part of forwarding the * request to the error page, from throwing it if the response has * not been committed (the response will have been committed if the * error page is a JSP page). */ request.setAttribute(PageContext.EXCEPTION, t); request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, ((HttpServletRequest) request).getRequestURI()); request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, config.getServletName()); try { forward(errorPageURL); } catch (IllegalStateException ise) { include(errorPageURL); } // The error page could be inside an include. Object newException = request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); // t==null means the attribute was not set. if ((newException != null) && (newException == t)) { request.removeAttribute(RequestDispatcher.ERROR_EXCEPTION); } // now clear the error code - to prevent double handling. request.removeAttribute(RequestDispatcher.ERROR_STATUS_CODE); request.removeAttribute(RequestDispatcher.ERROR_REQUEST_URI); request.removeAttribute(RequestDispatcher.ERROR_SERVLET_NAME); request.removeAttribute(PageContext.EXCEPTION); } else { // Otherwise throw the exception wrapped inside a ServletException. // Set the exception as the root cause in the ServletException // to get a stack trace for the real problem if (t instanceof IOException) throw (IOException) t; if (t instanceof ServletException) throw (ServletException) t; if (t instanceof RuntimeException) throw (RuntimeException) t; Throwable rootCause = null; if (t instanceof JspException) { rootCause = ((JspException) t).getCause(); } else if (t instanceof ELException) { rootCause = ((ELException) t).getCause(); } if (rootCause != null) { throw new ServletException(t.getClass().getName() + ": " + t.getMessage(), rootCause); } throw new ServletException(t); } }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public void init(ServletConfig config) throws ServletException { super.init(config); this.config = config; this.context = config.getServletContext(); // Initialize the JSP Runtime Context // Check for a custom Options implementation String engineOptionsName = config.getInitParameter("engineOptionsClass"); if (engineOptionsName != null) { // Instantiate the indicated Options implementation try { ClassLoader loader = Thread.currentThread() .getContextClassLoader(); Class<?> engineOptionsClass = loader.loadClass(engineOptionsName); Class<?>[] ctorSig = { ServletConfig.class, ServletContext.class }; Constructor<?> ctor = engineOptionsClass.getConstructor(ctorSig); Object[] args = { config, context }; options = (Options) ctor.newInstance(args); } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); // Need to localize this. log.warn("Failed to load engineOptionsClass", e); // Use the default Options implementation options = new EmbeddedServletOptions(config, context); } } else { // Use the default Options implementation options = new EmbeddedServletOptions(config, context); } rctxt = new JspRuntimeContext(context, options); if (config.getInitParameter("jspFile") != null) { jspFile = config.getInitParameter("jspFile"); try { if (null == context.getResource(jspFile)) { throw new ServletException("missing jspFile"); } } catch (MalformedURLException e) { throw new ServletException("Can not locate jsp file", e); } try { if (SecurityUtil.isPackageProtectionEnabled()){ AccessController.doPrivileged(new PrivilegedExceptionAction<Object>(){ @Override public Object run() throws IOException, ServletException { serviceJspFile(null, null, jspFile, true); return null; } }); } else { serviceJspFile(null, null, jspFile, true); } } catch (IOException e) { throw new ServletException("Could not precompile jsp: " + jspFile, e); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ServletException) throw (ServletException)t; throw new ServletException("Could not precompile jsp: " + jspFile, e); } }
// in java/org/apache/jasper/servlet/JspServlet.java
boolean preCompile(HttpServletRequest request) throws ServletException { String queryString = request.getQueryString(); if (queryString == null) { return (false); } int start = queryString.indexOf(Constants.PRECOMPILE); if (start < 0) { return (false); } queryString = queryString.substring(start + Constants.PRECOMPILE.length()); if (queryString.length() == 0) { return (true); // ?jsp_precompile } if (queryString.startsWith("&")) { return (true); // ?jsp_precompile&foo=bar... } if (!queryString.startsWith("=")) { return (false); // part of some other name or value } int limit = queryString.length(); int ampersand = queryString.indexOf("&"); if (ampersand > 0) { limit = ampersand; } String value = queryString.substring(1, limit); if (value.equals("true")) { return (true); // ?jsp_precompile=true } else if (value.equals("false")) { // Spec says if jsp_precompile=false, the request should not // be delivered to the JSP page; the easiest way to implement // this is to set the flag to true, and precompile the page anyway. // This still conforms to the spec, since it says the // precompilation request can be ignored. return (true); // ?jsp_precompile=false } else { throw new ServletException("Cannot have request parameter " + Constants.PRECOMPILE + " set to " + value); } }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //jspFile may be configured as an init-param for this servlet instance String jspUri = jspFile; if (jspUri == null) { // JSP specified via <jsp-file> in <servlet> declaration and supplied through //custom servlet container code jspUri = (String) request.getAttribute(Constants.JSP_FILE); } if (jspUri == null) { /* * Check to see if the requested JSP has been the target of a * RequestDispatcher.include() */ jspUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); if (jspUri != null) { /* * Requested JSP has been target of * RequestDispatcher.include(). Its path is assembled from the * relevant javax.servlet.include.* request attributes */ String pathInfo = (String) request.getAttribute( RequestDispatcher.INCLUDE_PATH_INFO); if (pathInfo != null) { jspUri += pathInfo; } } else { /* * Requested JSP has not been the target of a * RequestDispatcher.include(). Reconstruct its path from the * request's getServletPath() and getPathInfo() */ jspUri = request.getServletPath(); String pathInfo = request.getPathInfo(); if (pathInfo != null) { jspUri += pathInfo; } } } if (log.isDebugEnabled()) { log.debug("JspEngine --> " + jspUri); log.debug("\t ServletPath: " + request.getServletPath()); log.debug("\t PathInfo: " + request.getPathInfo()); log.debug("\t RealPath: " + context.getRealPath(jspUri)); log.debug("\t RequestURI: " + request.getRequestURI()); log.debug("\t QueryString: " + request.getQueryString()); } try { boolean precompile = preCompile(request); serviceJspFile(request, response, jspUri, precompile); } catch (RuntimeException e) { throw e; } catch (ServletException e) { throw e; } catch (IOException e) { throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException(e); } }
// in java/org/apache/jasper/servlet/JspServlet.java
private void handleMissingResource(HttpServletRequest request, HttpServletResponse response, String jspUri) throws ServletException, IOException { String includeRequestUri = (String)request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored String msg = Localizer.getMessage("jsp.error.file.not.found",jspUri); // Strictly, filtering this is an application // responsibility but just in case... throw new ServletException(SecurityUtil.filter(msg)); } else { try { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); } catch (IllegalStateException ise) { log.error(Localizer.getMessage("jsp.error.file.not.found", jspUri)); } } return; }
// in java/org/apache/catalina/startup/Tomcat.java
Override public synchronized Servlet loadServlet() throws ServletException { if (singleThreadModel) { Servlet instance; try { instance = existing.getClass().newInstance(); } catch (InstantiationException e) { throw new ServletException(e); } catch (IllegalAccessException e) { throw new ServletException(e); } instance.init(facade); return instance; } else { if (!init) { existing.init(facade); init = true; } return existing; } }
// in java/org/apache/catalina/filters/FilterBase.java
Override public void init(FilterConfig filterConfig) throws ServletException { Enumeration<String> paramNames = filterConfig.getInitParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); if (!IntrospectionUtils.setProperty(this, paramName, filterConfig.getInitParameter(paramName))) { String msg = sm.getString("filterbase.noSuchProperty", paramName, this.getClass().getName()); if (isConfigProblemFatal()) { throw new ServletException(msg); } else { getLogger().warn(msg); } } } }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { for (Enumeration<String> names = filterConfig.getInitParameterNames(); names.hasMoreElements();) { String name = names.nextElement(); String value = filterConfig.getInitParameter(name); try { if (name.startsWith(PARAMETER_EXPIRES_BY_TYPE)) { String contentType = name.substring( PARAMETER_EXPIRES_BY_TYPE.length()).trim(); ExpiresConfiguration expiresConfiguration = parseExpiresConfiguration(value); this.expiresConfigurationByContentType.put(contentType, expiresConfiguration); } else if (name.equalsIgnoreCase(PARAMETER_EXPIRES_DEFAULT)) { ExpiresConfiguration expiresConfiguration = parseExpiresConfiguration(value); this.defaultExpiresConfiguration = expiresConfiguration; } else if (name.equalsIgnoreCase(PARAMETER_EXPIRES_EXCLUDED_RESPONSE_STATUS_CODES)) { this.excludedResponseStatusCodes = commaDelimitedListToIntArray(value); } else { log.warn(sm.getString( "expiresFilter.unknownParameterIgnored", name, value)); } } catch (RuntimeException e) { throw new ServletException(sm.getString( "expiresFilter.exceptionProcessingParameter", name, value), e); } } log.debug(sm.getString("expiresFilter.filterInitialized", this.toString())); }
// in java/org/apache/catalina/websocket/WebSocketServlet.java
private String getWebSocketAccept(String key) throws ServletException { MessageDigest sha1Helper = sha1Helpers.poll(); if (sha1Helper == null) { try { sha1Helper = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new ServletException(e); } } sha1Helper.reset(); sha1Helper.update(key.getBytes(B2CConverter.ISO_8859_1)); String result = Base64.encode(sha1Helper.digest(WS_ACCEPT)); sha1Helpers.add(sha1Helper); return result; }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // mode is flag for HTML or XML output int mode = 0; // if ?XML=true, set the mode to XML if (request.getParameter("XML") != null && request.getParameter("XML").equals("true")) { mode = 1; } StatusTransformer.setContentType(response, mode); PrintWriter writer = response.getWriter(); boolean completeStatus = false; if ((request.getPathInfo() != null) && (request.getPathInfo().equals("/all"))) { completeStatus = true; } // use StatusTransformer to output status Object[] args = new Object[1]; args[0] = request.getContextPath(); StatusTransformer.writeHeader(writer,args,mode); // Body Header Section args = new Object[2]; args[0] = request.getContextPath(); if (completeStatus) { args[1] = sm.getString("statusServlet.complete"); } else { args[1] = sm.getString("statusServlet.title"); } // use StatusTransformer to output status StatusTransformer.writeBody(writer,args,mode); // Manager Section args = new Object[9]; args[0] = sm.getString("htmlManagerServlet.manager"); args[1] = response.encodeURL(request.getContextPath() + "/html/list"); args[2] = sm.getString("htmlManagerServlet.list"); args[3] = response.encodeURL (request.getContextPath() + "/" + sm.getString("htmlManagerServlet.helpHtmlManagerFile")); args[4] = sm.getString("htmlManagerServlet.helpHtmlManager"); args[5] = response.encodeURL (request.getContextPath() + "/" + sm.getString("htmlManagerServlet.helpManagerFile")); args[6] = sm.getString("htmlManagerServlet.helpManager"); if (completeStatus) { args[7] = response.encodeURL (request.getContextPath() + "/status"); args[8] = sm.getString("statusServlet.title"); } else { args[7] = response.encodeURL (request.getContextPath() + "/status/all"); args[8] = sm.getString("statusServlet.complete"); } // use StatusTransformer to output status StatusTransformer.writeManager(writer,args,mode); // Server Header Section args = new Object[9]; args[0] = sm.getString("htmlManagerServlet.serverTitle"); args[1] = sm.getString("htmlManagerServlet.serverVersion"); args[2] = sm.getString("htmlManagerServlet.serverJVMVersion"); args[3] = sm.getString("htmlManagerServlet.serverJVMVendor"); args[4] = sm.getString("htmlManagerServlet.serverOSName"); args[5] = sm.getString("htmlManagerServlet.serverOSVersion"); args[6] = sm.getString("htmlManagerServlet.serverOSArch"); args[7] = sm.getString("htmlManagerServlet.serverHostname"); args[8] = sm.getString("htmlManagerServlet.serverIPAddress"); // use StatusTransformer to output status StatusTransformer.writePageHeading(writer,args,mode); // Server Row Section args = new Object[8]; args[0] = ServerInfo.getServerInfo(); args[1] = System.getProperty("java.runtime.version"); args[2] = System.getProperty("java.vm.vendor"); args[3] = System.getProperty("os.name"); args[4] = System.getProperty("os.version"); args[5] = System.getProperty("os.arch"); try { InetAddress address = InetAddress.getLocalHost(); args[6] = address.getHostName(); args[7] = address.getHostAddress(); } catch (UnknownHostException e) { args[6] = "-"; args[7] = "-"; } // use StatusTransformer to output status StatusTransformer.writeServerInfo(writer, args, mode); try { // Display operating system statistics using APR if available StatusTransformer.writeOSState(writer,mode); // Display virtual machine statistics StatusTransformer.writeVMState(writer,mode); Enumeration<ObjectName> enumeration = threadPools.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); String name = objectName.getKeyProperty("name"); // use StatusTransformer to output status StatusTransformer.writeConnectorState (writer, objectName, name, mBeanServer, globalRequestProcessors, requestProcessors, mode); } if ((request.getPathInfo() != null) && (request.getPathInfo().equals("/all"))) { // Note: Retrieving the full status is much slower // use StatusTransformer to output status StatusTransformer.writeDetailedState (writer, mBeanServer, mode); } } catch (Exception e) { throw new ServletException(e); } // use StatusTransformer to output status StatusTransformer.writeFooter(writer, mode); }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
protected Principal doLogin(Request request, String username, String password) throws ServletException { Principal p = context.getRealm().authenticate(username, password); if (p == null) { throw new ServletException(sm.getString("authenticator.loginFail")); } return p; }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override public void init() throws ServletException { if (getServletConfig().getInitParameter("debug") != null) debug = Integer.parseInt(getServletConfig().getInitParameter("debug")); if (getServletConfig().getInitParameter("input") != null) input = Integer.parseInt(getServletConfig().getInitParameter("input")); if (getServletConfig().getInitParameter("output") != null) output = Integer.parseInt(getServletConfig().getInitParameter("output")); listings = Boolean.parseBoolean(getServletConfig().getInitParameter("listings")); if (getServletConfig().getInitParameter("readonly") != null) readOnly = Boolean.parseBoolean(getServletConfig().getInitParameter("readonly")); if (getServletConfig().getInitParameter("sendfileSize") != null) sendfileSize = Integer.parseInt(getServletConfig().getInitParameter("sendfileSize")) * 1024; fileEncoding = getServletConfig().getInitParameter("fileEncoding"); globalXsltFile = getServletConfig().getInitParameter("globalXsltFile"); contextXsltFile = getServletConfig().getInitParameter("contextXsltFile"); localXsltFile = getServletConfig().getInitParameter("localXsltFile"); readmeFile = getServletConfig().getInitParameter("readmeFile"); if (getServletConfig().getInitParameter("useAcceptRanges") != null) useAcceptRanges = Boolean.parseBoolean(getServletConfig().getInitParameter("useAcceptRanges")); // Sanity check on the specified buffer sizes if (input < 256) input = 256; if (output < 256) output = 256; if (debug > 0) { log("DefaultServlet.init: input buffer size=" + input + ", output buffer size=" + output); } // Load the proxy dir context. resources = (ProxyDirContext) getServletContext() .getAttribute(Globals.RESOURCES_ATTR); if (resources == null) { try { resources = (ProxyDirContext) new InitialContext() .lookup(RESOURCES_JNDI_NAME); } catch (NamingException e) { // Failed throw new ServletException("No resources", e); } } if (resources == null) { throw new UnavailableException("No resources"); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream renderXml(String contextPath, CacheEntry cacheEntry, InputStream xsltInputStream) throws IOException, ServletException { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<listing "); sb.append(" contextPath='"); sb.append(contextPath); sb.append("'"); sb.append(" directory='"); sb.append(cacheEntry.name); sb.append("' "); sb.append(" hasParent='").append(!cacheEntry.name.equals("/")); sb.append("'>"); sb.append("<entries>"); try { // Render the directory entries within this directory NamingEnumeration<NameClassPair> enumeration = resources.list(cacheEntry.name); // rewriteUrl(contextPath) is expensive. cache result for later reuse String rewrittenContextPath = rewriteUrl(contextPath); while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String resourceName = ncPair.getName(); String trimmed = resourceName/*.substring(trim)*/; if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF") || trimmed.equalsIgnoreCase(localXsltFile)) continue; if ((cacheEntry.name + trimmed).equals(contextXsltFile)) continue; CacheEntry childCacheEntry = resources.lookupCache(cacheEntry.name + resourceName); if (!childCacheEntry.exists) { continue; } sb.append("<entry"); sb.append(" type='") .append((childCacheEntry.context != null)?"dir":"file") .append("'"); sb.append(" urlPath='") .append(rewrittenContextPath) .append(rewriteUrl(cacheEntry.name + resourceName)) .append((childCacheEntry.context != null)?"/":"") .append("'"); if (childCacheEntry.resource != null) { sb.append(" size='") .append(renderSize(childCacheEntry.attributes.getContentLength())) .append("'"); } sb.append(" date='") .append(childCacheEntry.attributes.getLastModifiedHttp()) .append("'"); sb.append(">"); sb.append(RequestUtil.filter(trimmed)); if (childCacheEntry.context != null) sb.append("/"); sb.append("</entry>"); } } catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); } sb.append("</entries>"); String readme = getReadme(cacheEntry.context); if (readme!=null) { sb.append("<readme><![CDATA["); sb.append(readme); sb.append("]]></readme>"); } sb.append("</listing>"); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Source xmlSource = new StreamSource(new StringReader(sb.toString())); Source xslSource = new StreamSource(xsltInputStream); Transformer transformer = tFactory.newTransformer(xslSource); ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8"); StreamResult out = new StreamResult(osWriter); transformer.transform(xmlSource, out); osWriter.flush(); return (new ByteArrayInputStream(stream.toByteArray())); } catch (TransformerException e) { throw new ServletException("XSL transformer error", e); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream renderHtml(String contextPath, CacheEntry cacheEntry) throws IOException, ServletException { String name = cacheEntry.name; // Prepare a writer to a buffered area ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8"); PrintWriter writer = new PrintWriter(osWriter); StringBuilder sb = new StringBuilder(); // rewriteUrl(contextPath) is expensive. cache result for later reuse String rewrittenContextPath = rewriteUrl(contextPath); // Render the page header sb.append("<html>\r\n"); sb.append("<head>\r\n"); sb.append("<title>"); sb.append(sm.getString("directory.title", name)); sb.append("</title>\r\n"); sb.append("<STYLE><!--"); sb.append(org.apache.catalina.util.TomcatCSS.TOMCAT_CSS); sb.append("--></STYLE> "); sb.append("</head>\r\n"); sb.append("<body>"); sb.append("<h1>"); sb.append(sm.getString("directory.title", name)); // Render the link to our parent (if required) String parentDirectory = name; if (parentDirectory.endsWith("/")) { parentDirectory = parentDirectory.substring(0, parentDirectory.length() - 1); } int slash = parentDirectory.lastIndexOf('/'); if (slash >= 0) { String parent = name.substring(0, slash); sb.append(" - <a href=\""); sb.append(rewrittenContextPath); if (parent.equals("")) parent = "/"; sb.append(rewriteUrl(parent)); if (!parent.endsWith("/")) sb.append("/"); sb.append("\">"); sb.append("<b>"); sb.append(sm.getString("directory.parent", parent)); sb.append("</b>"); sb.append("</a>"); } sb.append("</h1>"); sb.append("<HR size=\"1\" noshade=\"noshade\">"); sb.append("<table width=\"100%\" cellspacing=\"0\"" + " cellpadding=\"5\" align=\"center\">\r\n"); // Render the column headings sb.append("<tr>\r\n"); sb.append("<td align=\"left\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.filename")); sb.append("</strong></font></td>\r\n"); sb.append("<td align=\"center\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.size")); sb.append("</strong></font></td>\r\n"); sb.append("<td align=\"right\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.lastModified")); sb.append("</strong></font></td>\r\n"); sb.append("</tr>"); try { // Render the directory entries within this directory NamingEnumeration<NameClassPair> enumeration = resources.list(cacheEntry.name); boolean shade = false; while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String resourceName = ncPair.getName(); String trimmed = resourceName/*.substring(trim)*/; if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF")) continue; CacheEntry childCacheEntry = resources.lookupCache(cacheEntry.name + resourceName); if (!childCacheEntry.exists) { continue; } sb.append("<tr"); if (shade) sb.append(" bgcolor=\"#eeeeee\""); sb.append(">\r\n"); shade = !shade; sb.append("<td align=\"left\">&nbsp;&nbsp;\r\n"); sb.append("<a href=\""); sb.append(rewrittenContextPath); resourceName = rewriteUrl(name + resourceName); sb.append(resourceName); if (childCacheEntry.context != null) sb.append("/"); sb.append("\"><tt>"); sb.append(RequestUtil.filter(trimmed)); if (childCacheEntry.context != null) sb.append("/"); sb.append("</tt></a></td>\r\n"); sb.append("<td align=\"right\"><tt>"); if (childCacheEntry.context != null) sb.append("&nbsp;"); else sb.append(renderSize(childCacheEntry.attributes.getContentLength())); sb.append("</tt></td>\r\n"); sb.append("<td align=\"right\"><tt>"); sb.append(childCacheEntry.attributes.getLastModifiedHttp()); sb.append("</tt></td>\r\n"); sb.append("</tr>\r\n"); } } catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); } // Render the page footer sb.append("</table>\r\n"); sb.append("<HR size=\"1\" noshade=\"noshade\">"); String readme = getReadme(cacheEntry.context); if (readme!=null) { sb.append(readme); sb.append("<HR size=\"1\" noshade=\"noshade\">"); } sb.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>"); sb.append("</body>\r\n"); sb.append("</html>\r\n"); // Return an input stream to the underlying bytes writer.write(sb.toString()); writer.flush(); return (new ByteArrayInputStream(stream.toByteArray())); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected DocumentBuilder getDocumentBuilder() throws ServletException { DocumentBuilder documentBuilder = null; DocumentBuilderFactory documentBuilderFactory = null; try { documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setExpandEntityReferences(false); documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setEntityResolver( new WebdavResolver(this.getServletContext())); } catch(ParserConfigurationException e) { throw new ServletException (sm.getString("webdavservlet.jaxpfailed")); } return documentBuilder; }
// in java/org/apache/catalina/connector/Request.java
Override public void login(String username, String password) throws ServletException { if (getAuthType() != null || getRemoteUser() != null || getUserPrincipal() != null) { throw new ServletException( sm.getString("coyoteRequest.alreadyAuthenticated")); } if (context.getAuthenticator() == null) { throw new ServletException("no authenticator"); } context.getAuthenticator().login(username, password, this); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; try { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<Void>() { @Override public Void run() throws ServletException, IOException { internalDoFilter(req,res); return null; } } ); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
private void internalDoFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { // Call the next filter if there is one if (pos < n) { ApplicationFilterConfig filterConfig = filters[pos++]; Filter filter = null; try { filter = filterConfig.getFilter(); support.fireInstanceEvent(InstanceEvent.BEFORE_FILTER_EVENT, filter, request, response); if (request.isAsyncSupported() && "false".equalsIgnoreCase( filterConfig.getFilterDef().getAsyncSupported())) { request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE); } if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; Principal principal = ((HttpServletRequest) req).getUserPrincipal(); Object[] args = new Object[]{req, res, this}; SecurityUtil.doAsPrivilege ("doFilter", filter, classType, args, principal); } else { filter.doFilter(request, response, this); } support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response); } catch (IOException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (ServletException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (RuntimeException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); } return; } // We fell off the end of the chain -- call the servlet instance try { if (ApplicationDispatcher.WRAP_SAME_OBJECT) { lastServicedRequest.set(request); lastServicedResponse.set(response); } support.fireInstanceEvent(InstanceEvent.BEFORE_SERVICE_EVENT, servlet, request, response); if (request.isAsyncSupported() && !support.getWrapper().isAsyncSupported()) { request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE); } // Use potentially wrapped request from this point if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) { if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; Principal principal = ((HttpServletRequest) req).getUserPrincipal(); Object[] args = new Object[]{req, res}; SecurityUtil.doAsPrivilege("service", servlet, classTypeUsedInService, args, principal); } else { servlet.service(request, response); } } else { servlet.service(request, response); } support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response); } catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); } finally { if (ApplicationDispatcher.WRAP_SAME_OBJECT) { lastServicedRequest.set(null); lastServicedResponse.set(null); } } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public void doFilterEvent(CometEvent event) throws IOException, ServletException { if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; try { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<Void>() { @Override public Void run() throws ServletException, IOException { internalDoFilterEvent(ev); return null; } } ); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
private void internalDoFilterEvent(CometEvent event) throws IOException, ServletException { // Call the next filter if there is one if (pos < n) { ApplicationFilterConfig filterConfig = filters[pos++]; CometFilter filter = null; try { filter = (CometFilter) filterConfig.getFilter(); // FIXME: No instance listener processing for events for now /* support.fireInstanceEvent(InstanceEvent.BEFORE_FILTER_EVENT, filter, event); */ if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; Principal principal = ev.getHttpServletRequest().getUserPrincipal(); Object[] args = new Object[]{ev, this}; SecurityUtil.doAsPrivilege("doFilterEvent", filter, cometClassType, args, principal); } else { filter.doFilterEvent(event, this); } /*support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event);*/ } catch (IOException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (ServletException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (RuntimeException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); } return; } // We fell off the end of the chain -- call the servlet instance try { /* support.fireInstanceEvent(InstanceEvent.BEFORE_SERVICE_EVENT, servlet, request, response); */ if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; Principal principal = ev.getHttpServletRequest().getUserPrincipal(); Object[] args = new Object[]{ ev }; SecurityUtil.doAsPrivilege("event", servlet, classTypeUsedInEvent, args, principal); } else { ((CometProcessor) servlet).event(event); } /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response);*/ } catch (IOException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (ServletException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (RuntimeException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw new ServletException (sm.getString("filterChain.servlet"), e); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends Filter> T createFilter(Class<T> c) throws ServletException { try { @SuppressWarnings("unchecked") T filter = (T) context.getInstanceManager().newInstance(c.getName()); return filter; } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends Servlet> T createServlet(Class<T> c) throws ServletException { try { @SuppressWarnings("unchecked") T servlet = (T) context.getInstanceManager().newInstance(c.getName()); context.dynamicServletCreated(servlet); return servlet; } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends EventListener> T createListener(Class<T> c) throws ServletException { try { @SuppressWarnings("unchecked") T listener = (T) context.getInstanceManager().newInstance(c.getName()); if (listener instanceof ServletContextListener || listener instanceof ServletContextAttributeListener || listener instanceof ServletRequestListener || listener instanceof ServletRequestAttributeListener || listener instanceof HttpSessionListener || listener instanceof HttpSessionAttributeListener) { return listener; } throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", listener.getClass().getName())); } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } }
// in java/org/apache/catalina/core/AsyncContextImpl.java
protected void doInternalDispatch() throws ServletException, IOException { if (log.isDebugEnabled()) { logDebug("intDispatch"); } try { dispatch.run(); if (!request.isAsync()) { fireOnComplete(); } } catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); } }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public Servlet allocate() throws ServletException { // If we are currently unloading this servlet, throw an exception if (unloading) throw new ServletException (sm.getString("standardWrapper.unloading", getName())); boolean newInstance = false; // If not SingleThreadedModel, return the same instance every time if (!singleThreadModel) { // Load and initialize our instance if necessary if (instance == null) { synchronized (this) { if (instance == null) { try { if (log.isDebugEnabled()) log.debug("Allocating non-STM instance"); instance = loadServlet(); if (!singleThreadModel) { // For non-STM, increment here to prevent a race // condition with unload. Bug 43683, test case // #3 newInstance = true; countAllocated.incrementAndGet(); } } catch (ServletException e) { throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); } } } } if (!instanceInitialized) { initServlet(instance); } if (singleThreadModel) { if (newInstance) { // Have to do this outside of the sync above to prevent a // possible deadlock synchronized (instancePool) { instancePool.push(instance); nInstances++; } } } else { if (log.isTraceEnabled()) log.trace(" Returning non-STM instance"); // For new instances, count will have been incremented at the // time of creation if (!newInstance) { countAllocated.incrementAndGet(); } return (instance); } } synchronized (instancePool) { while (countAllocated.get() >= nInstances) { // Allocate a new instance if possible, or else wait if (nInstances < maxInstances) { try { instancePool.push(loadServlet()); nInstances++; } catch (ServletException e) { throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); } } else { try { instancePool.wait(); } catch (InterruptedException e) { // Ignore } } } if (log.isTraceEnabled()) log.trace(" Returning allocated STM instance"); countAllocated.incrementAndGet(); return instancePool.pop(); } }
// in java/org/apache/catalina/core/StandardWrapper.java
public synchronized Servlet loadServlet() throws ServletException { // Nothing to do if we already have an instance or an instance pool if (!singleThreadModel && (instance != null)) return instance; PrintStream out = System.out; if (swallowOutput) { SystemLogHandler.startCapture(); } Servlet servlet; try { long t1=System.currentTimeMillis(); // Complain if no servlet class has been specified if (servletClass == null) { unavailable(null); throw new ServletException (sm.getString("standardWrapper.notClass", getName())); } InstanceManager instanceManager = ((StandardContext)getParent()).getInstanceManager(); try { servlet = (Servlet) instanceManager.newInstance(servletClass); } catch (ClassCastException e) { unavailable(null); // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.notServlet", servletClass), e); } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); } if (multipartConfigElement == null) { MultipartConfig annotation = servlet.getClass().getAnnotation(MultipartConfig.class); if (annotation != null) { multipartConfigElement = new MultipartConfigElement(annotation); } } processServletSecurityAnnotation(servlet.getClass()); // Special handling for ContainerServlet instances if ((servlet instanceof ContainerServlet) && (isContainerProvidedServlet(servletClass) || ((Context) getParent()).getPrivileged() )) { ((ContainerServlet) servlet).setWrapper(this); } classLoadTime=(int) (System.currentTimeMillis() -t1); if (servlet instanceof SingleThreadModel) { if (instancePool == null) { instancePool = new Stack<Servlet>(); } singleThreadModel = true; } initServlet(servlet); fireContainerEvent("load", this); loadTime=System.currentTimeMillis() -t1; } finally { if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } } return servlet; }
// in java/org/apache/catalina/core/StandardWrapper.java
private synchronized void initServlet(Servlet servlet) throws ServletException { if (instanceInitialized && !singleThreadModel) return; // Call the initialization method of this servlet try { instanceSupport.fireInstanceEvent(InstanceEvent.BEFORE_INIT_EVENT, servlet); if( Globals.IS_SECURITY_ENABLED) { Object[] args = new Object[]{(facade)}; SecurityUtil.doAsPrivilege("init", servlet, classType, args); args = null; } else { servlet.init(facade); } instanceInitialized = true; instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet); } catch (UnavailableException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); unavailable(f); throw f; } catch (ServletException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw f; } catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); } }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public synchronized void unload() throws ServletException { // Nothing to do if we have never loaded the instance if (!singleThreadModel && (instance == null)) return; unloading = true; // Loaf a while if the current instance is allocated // (possibly more than once if non-STM) if (countAllocated.get() > 0) { int nRetries = 0; long delay = unloadDelay / 20; while ((nRetries < 21) && (countAllocated.get() > 0)) { if ((nRetries % 10) == 0) { log.info(sm.getString("standardWrapper.waiting", countAllocated.toString())); } try { Thread.sleep(delay); } catch (InterruptedException e) { // Ignore } nRetries++; } } if (instanceInitialized) { PrintStream out = System.out; if (swallowOutput) { SystemLogHandler.startCapture(); } // Call the servlet destroy() method try { instanceSupport.fireInstanceEvent (InstanceEvent.BEFORE_DESTROY_EVENT, instance); if( Globals.IS_SECURITY_ENABLED) { SecurityUtil.doAsPrivilege("destroy", instance); SecurityUtil.remove(instance); } else { instance.destroy(); } instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance); // Annotation processing if (!((Context) getParent()).getIgnoreAnnotations()) { ((StandardContext)getParent()).getInstanceManager().destroyInstance(instance); } } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); } finally { // Write captured output if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } } } // Deregister the destroyed instance instance = null; if (isJspServlet && jspMonitorON != null ) { Registry.getRegistry(null, null).unregisterComponent(jspMonitorON); } if (singleThreadModel && (instancePool != null)) { try { while (!instancePool.isEmpty()) { Servlet s = instancePool.pop(); if (Globals.IS_SECURITY_ENABLED) { SecurityUtil.doAsPrivilege("destroy", s); SecurityUtil.remove(instance); } else { s.destroy(); } // Annotation processing if (!((Context) getParent()).getIgnoreAnnotations()) { ((StandardContext)getParent()).getInstanceManager().destroyInstance(s); } } } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); } instancePool = null; nInstances = 0; } singleThreadModel = false; unloading = false; fireContainerEvent("unload", this); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void checkSameObjects(ServletRequest appRequest, ServletResponse appResponse) throws ServletException { ServletRequest originalRequest = ApplicationFilterChain.getLastServicedRequest(); ServletResponse originalResponse = ApplicationFilterChain.getLastServicedResponse(); // Some forwards, eg from valves will not set original values if (originalRequest == null || originalResponse == null) { return; } boolean same = false; ServletRequest dispatchedRequest = appRequest; //find the request that was passed into the service method while (originalRequest instanceof ServletRequestWrapper && ((ServletRequestWrapper) originalRequest).getRequest()!=null ) { originalRequest = ((ServletRequestWrapper) originalRequest).getRequest(); } //compare with the dispatched request while (!same) { if (originalRequest.equals(dispatchedRequest)) { same = true; } if (!same && dispatchedRequest instanceof ServletRequestWrapper) { dispatchedRequest = ((ServletRequestWrapper) dispatchedRequest).getRequest(); } else { break; } } if (!same) { throw new ServletException(sm.getString( "applicationDispatcher.specViolation.request")); } same = false; ServletResponse dispatchedResponse = appResponse; //find the response that was passed into the service method while (originalResponse instanceof ServletResponseWrapper && ((ServletResponseWrapper) originalResponse).getResponse() != null ) { originalResponse = ((ServletResponseWrapper) originalResponse).getResponse(); } //compare with the dispatched response while (!same) { if (originalResponse.equals(dispatchedResponse)) { same = true; } if (!same && dispatchedResponse instanceof ServletResponseWrapper) { dispatchedResponse = ((ServletResponseWrapper) dispatchedResponse).getResponse(); } else { break; } } if (!same) { throw new ServletException(sm.getString( "applicationDispatcher.specViolation.response")); } }
// in java/org/apache/catalina/security/SecurityUtil.java
private static void execute(final Method method, final Object targetObject, final Object[] targetArguments, Principal principal) throws java.lang.Exception{ try{ Subject subject = null; PrivilegedExceptionAction<Void> pea = new PrivilegedExceptionAction<Void>(){ @Override public Void run() throws Exception{ method.invoke(targetObject, targetArguments); return null; } }; // The first argument is always the request object if (targetArguments != null && targetArguments[0] instanceof HttpServletRequest){ HttpServletRequest request = (HttpServletRequest)targetArguments[0]; boolean hasSubject = false; HttpSession session = request.getSession(false); if (session != null){ subject = (Subject)session.getAttribute(Globals.SUBJECT_ATTR); hasSubject = (subject != null); } if (subject == null){ subject = new Subject(); if (principal != null){ subject.getPrincipals().add(principal); } } if (session != null && !hasSubject) { session.setAttribute(Globals.SUBJECT_ATTR, subject); } } Subject.doAsPrivileged(subject, pea, null); } catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/javax/servlet/http/HttpServlet.java
Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request; HttpServletResponse response; try { request = (HttpServletRequest) req; response = (HttpServletResponse) res; } catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); } service(request, response); }
45
            
// in java/org/apache/jasper/servlet/JspServlet.java
catch (MalformedURLException e) { throw new ServletException("Can not locate jsp file", e); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (IOException e) { throw new ServletException("Could not precompile jsp: " + jspFile, e); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ServletException) throw (ServletException)t; throw new ServletException("Could not precompile jsp: " + jspFile, e); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException(e); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/startup/Tomcat.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
catch (RuntimeException e) { throw new ServletException(sm.getString( "expiresFilter.exceptionProcessingParameter", name, value), e); }
// in java/org/apache/catalina/websocket/WebSocketServlet.java
catch (NoSuchAlgorithmException e) { throw new ServletException(e); }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
catch (Exception e) { throw new ServletException(e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Failed throw new ServletException("No resources", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (TransformerException e) { throw new ServletException("XSL transformer error", e); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch(ParserConfigurationException e) { throw new ServletException (sm.getString("webdavservlet.jaxpfailed")); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (IllegalAccessException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (NamingException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (InstantiationException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ClassNotFoundException e) { throw new ServletException(e); }
// in java/org/apache/catalina/core/AsyncContextImpl.java
catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ClassCastException e) { unavailable(null); // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.notServlet", servletClass), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/security/SecurityUtil.java
catch( PrivilegedActionException pe) { Throwable e; if (pe.getException() instanceof InvocationTargetException) { e = pe.getException().getCause(); ExceptionUtils.handleThrowable(e); } else { e = pe; } if (log.isDebugEnabled()){ log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e); } if (e instanceof UnavailableException) throw (UnavailableException) e; else if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); }
// in java/javax/servlet/http/HttpServlet.java
catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); }
189
            
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void forward(String relativeUrlPath) throws ServletException, IOException { invokingJspCtxt.forward(relativeUrlPath); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void include(String relativeUrlPath) throws ServletException, IOException { invokingJspCtxt.include(relativeUrlPath); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void include(String relativeUrlPath, boolean flush) throws ServletException, IOException { invokingJspCtxt.include(relativeUrlPath, false); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void handlePageException(Exception ex) throws IOException, ServletException { // Should never be called since handleException() called with a // Throwable in the generated servlet. handlePageException((Throwable) ex); }
// in java/org/apache/jasper/runtime/JspContextWrapper.java
Override public void handlePageException(Throwable t) throws IOException, ServletException { invokingJspCtxt.handlePageException(t); }
// in java/org/apache/jasper/runtime/HttpJspBase.java
Override public final void init(ServletConfig config) throws ServletException { super.init(config); jspInit(); _jspInit(); }
// in java/org/apache/jasper/runtime/HttpJspBase.java
Override public final void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { _jspService(request, response); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void include(String relativeUrlPath) throws ServletException, IOException { JspRuntimeLibrary .include(request, response, relativeUrlPath, out, true); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void include(final String relativeUrlPath, final boolean flush) throws ServletException, IOException { if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doInclude(relativeUrlPath, flush); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doInclude(String relativeUrlPath, boolean flush) throws ServletException, IOException { JspRuntimeLibrary.include(request, response, relativeUrlPath, out, flush); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void forward(final String relativeUrlPath) throws ServletException, IOException { if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doForward(relativeUrlPath); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doForward(String relativeUrlPath) throws ServletException, IOException { // JSP.4.5 If the buffer was flushed, throw IllegalStateException try { out.clear(); } catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer .getMessage("jsp.error.attempt_to_clear_flushed_buffer")); ise.initCause(ex); throw ise; } // Make sure that the response object is not the wrapper for include while (response instanceof ServletResponseWrapperInclude) { response = ((ServletResponseWrapperInclude) response).getResponse(); } final String path = getAbsolutePathRelativeToContext(relativeUrlPath); String includeUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); if (includeUri != null) request.removeAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH); try { context.getRequestDispatcher(path).forward(request, response); } finally { if (includeUri != null) request.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH, includeUri); } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void handlePageException(Exception ex) throws IOException, ServletException { // Should never be called since handleException() called with a // Throwable in the generated servlet. handlePageException((Throwable) ex); }
// in java/org/apache/jasper/runtime/PageContextImpl.java
Override public void handlePageException(final Throwable t) throws IOException, ServletException { if (t == null) throw new NullPointerException("null Throwable"); if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doHandlePageException(t); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } }
// in java/org/apache/jasper/runtime/PageContextImpl.java
private void doHandlePageException(Throwable t) throws IOException, ServletException { if (errorPageURL != null && !errorPageURL.equals("")) { /* * Set request attributes. Do not set the * javax.servlet.error.exception attribute here (instead, set in the * generated servlet code for the error page) in order to prevent * the ErrorReportValve, which is invoked as part of forwarding the * request to the error page, from throwing it if the response has * not been committed (the response will have been committed if the * error page is a JSP page). */ request.setAttribute(PageContext.EXCEPTION, t); request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, ((HttpServletRequest) request).getRequestURI()); request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, config.getServletName()); try { forward(errorPageURL); } catch (IllegalStateException ise) { include(errorPageURL); } // The error page could be inside an include. Object newException = request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); // t==null means the attribute was not set. if ((newException != null) && (newException == t)) { request.removeAttribute(RequestDispatcher.ERROR_EXCEPTION); } // now clear the error code - to prevent double handling. request.removeAttribute(RequestDispatcher.ERROR_STATUS_CODE); request.removeAttribute(RequestDispatcher.ERROR_REQUEST_URI); request.removeAttribute(RequestDispatcher.ERROR_SERVLET_NAME); request.removeAttribute(PageContext.EXCEPTION); } else { // Otherwise throw the exception wrapped inside a ServletException. // Set the exception as the root cause in the ServletException // to get a stack trace for the real problem if (t instanceof IOException) throw (IOException) t; if (t instanceof ServletException) throw (ServletException) t; if (t instanceof RuntimeException) throw (RuntimeException) t; Throwable rootCause = null; if (t instanceof JspException) { rootCause = ((JspException) t).getCause(); } else if (t instanceof ELException) { rootCause = ((ELException) t).getCause(); } if (rootCause != null) { throw new ServletException(t.getClass().getName() + ": " + t.getMessage(), rootCause); } throw new ServletException(t); } }
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
public static void include(ServletRequest request, ServletResponse response, String relativePath, JspWriter out, boolean flush) throws IOException, ServletException { if (flush && !(out instanceof BodyContent)) out.flush(); // FIXME - It is tempting to use request.getRequestDispatcher() to // resolve a relative path directly, but Catalina currently does not // take into account whether the caller is inside a RequestDispatcher // include or not. Whether Catalina *should* take that into account // is a spec issue currently under review. In the mean time, // replicate Jasper's previous behavior String resourcePath = getContextRelativePath(request, relativePath); RequestDispatcher rd = request.getRequestDispatcher(resourcePath); rd.include(request, new ServletResponseWrapperInclude(response, out)); }
// in java/org/apache/jasper/servlet/JspCServletContext.java
Override public <T extends Filter> T createFilter(Class<T> c) throws ServletException { return null; }
// in java/org/apache/jasper/servlet/JspCServletContext.java
Override public <T extends Servlet> T createServlet(Class<T> c) throws ServletException { return null; }
// in java/org/apache/jasper/servlet/JspCServletContext.java
Override public <T extends EventListener> T createListener(Class<T> c) throws ServletException { return null; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public Servlet getServlet() throws ServletException { // DCL on 'reload' requires that 'reload' be volatile // (this also forces a read memory barrier, ensuring the // new servlet object is read consistently) if (reload) { synchronized (this) { // Synchronizing on jsw enables simultaneous loading // of different pages, but not the same page. if (reload) { // This is to maintain the original protocol. destroy(); final Servlet servlet; try { InstanceManager instanceManager = InstanceManagerFactory.getInstanceManager(config); servlet = (Servlet) instanceManager.newInstance(ctxt.getFQCN(), ctxt.getJspLoader()); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); throw new JasperException(t); } servlet.init(config); if (!firstTime) { ctxt.getRuntimeContext().incrementJspReloadCount(); } theServlet = servlet; reload = false; // Volatile 'reload' forces in order write of 'theServlet' and new servlet object } } } return theServlet; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile) throws ServletException, IOException, FileNotFoundException { Servlet servlet; try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if ((available > 0L) && (available < Long.MAX_VALUE)) { if (available > System.currentTimeMillis()) { response.setDateHeader("Retry-After", available); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, Localizer.getMessage("jsp.error.unavailable")); return; } // Wait period has expired. Reset. available = 0; } /* * (1) Compile */ if (options.getDevelopment() || firstTime ) { synchronized (this) { firstTime = false; // The following sets reload to true, if necessary ctxt.compile(); } } else { if (compileException != null) { // Throw cached compilation exception throw compileException; } } /* * (2) (Re)load servlet class file */ servlet = getServlet(); // If a page is to be precompiled only, return. if (precompile) { return; } } catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; } catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } try { /* * (3) Handle limitation of number of loaded Jsps */ if (unloadAllowed) { synchronized(this) { if (unloadByCount) { if (unloadHandle == null) { unloadHandle = ctxt.getRuntimeContext().push(this); } else if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { ctxt.getRuntimeContext().makeYoungest(unloadHandle); lastUsageTime = System.currentTimeMillis(); } } else { if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { lastUsageTime = System.currentTimeMillis(); } } } } /* * (4) Service request */ if (servlet instanceof SingleThreadModel) { // sync on the wrapper so that the freshness // of the page is determined right before servicing synchronized (this) { servlet.service(request, response); } } else { servlet.service(request, response); } } catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); } catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IOException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public void init(ServletConfig config) throws ServletException { super.init(config); this.config = config; this.context = config.getServletContext(); // Initialize the JSP Runtime Context // Check for a custom Options implementation String engineOptionsName = config.getInitParameter("engineOptionsClass"); if (engineOptionsName != null) { // Instantiate the indicated Options implementation try { ClassLoader loader = Thread.currentThread() .getContextClassLoader(); Class<?> engineOptionsClass = loader.loadClass(engineOptionsName); Class<?>[] ctorSig = { ServletConfig.class, ServletContext.class }; Constructor<?> ctor = engineOptionsClass.getConstructor(ctorSig); Object[] args = { config, context }; options = (Options) ctor.newInstance(args); } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); // Need to localize this. log.warn("Failed to load engineOptionsClass", e); // Use the default Options implementation options = new EmbeddedServletOptions(config, context); } } else { // Use the default Options implementation options = new EmbeddedServletOptions(config, context); } rctxt = new JspRuntimeContext(context, options); if (config.getInitParameter("jspFile") != null) { jspFile = config.getInitParameter("jspFile"); try { if (null == context.getResource(jspFile)) { throw new ServletException("missing jspFile"); } } catch (MalformedURLException e) { throw new ServletException("Can not locate jsp file", e); } try { if (SecurityUtil.isPackageProtectionEnabled()){ AccessController.doPrivileged(new PrivilegedExceptionAction<Object>(){ @Override public Object run() throws IOException, ServletException { serviceJspFile(null, null, jspFile, true); return null; } }); } else { serviceJspFile(null, null, jspFile, true); } } catch (IOException e) { throw new ServletException("Could not precompile jsp: " + jspFile, e); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ServletException) throw (ServletException)t; throw new ServletException("Could not precompile jsp: " + jspFile, e); } }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public Object run() throws IOException, ServletException { serviceJspFile(null, null, jspFile, true); return null; }
// in java/org/apache/jasper/servlet/JspServlet.java
boolean preCompile(HttpServletRequest request) throws ServletException { String queryString = request.getQueryString(); if (queryString == null) { return (false); } int start = queryString.indexOf(Constants.PRECOMPILE); if (start < 0) { return (false); } queryString = queryString.substring(start + Constants.PRECOMPILE.length()); if (queryString.length() == 0) { return (true); // ?jsp_precompile } if (queryString.startsWith("&")) { return (true); // ?jsp_precompile&foo=bar... } if (!queryString.startsWith("=")) { return (false); // part of some other name or value } int limit = queryString.length(); int ampersand = queryString.indexOf("&"); if (ampersand > 0) { limit = ampersand; } String value = queryString.substring(1, limit); if (value.equals("true")) { return (true); // ?jsp_precompile=true } else if (value.equals("false")) { // Spec says if jsp_precompile=false, the request should not // be delivered to the JSP page; the easiest way to implement // this is to set the flag to true, and precompile the page anyway. // This still conforms to the spec, since it says the // precompilation request can be ignored. return (true); // ?jsp_precompile=false } else { throw new ServletException("Cannot have request parameter " + Constants.PRECOMPILE + " set to " + value); } }
// in java/org/apache/jasper/servlet/JspServlet.java
Override public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //jspFile may be configured as an init-param for this servlet instance String jspUri = jspFile; if (jspUri == null) { // JSP specified via <jsp-file> in <servlet> declaration and supplied through //custom servlet container code jspUri = (String) request.getAttribute(Constants.JSP_FILE); } if (jspUri == null) { /* * Check to see if the requested JSP has been the target of a * RequestDispatcher.include() */ jspUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); if (jspUri != null) { /* * Requested JSP has been target of * RequestDispatcher.include(). Its path is assembled from the * relevant javax.servlet.include.* request attributes */ String pathInfo = (String) request.getAttribute( RequestDispatcher.INCLUDE_PATH_INFO); if (pathInfo != null) { jspUri += pathInfo; } } else { /* * Requested JSP has not been the target of a * RequestDispatcher.include(). Reconstruct its path from the * request's getServletPath() and getPathInfo() */ jspUri = request.getServletPath(); String pathInfo = request.getPathInfo(); if (pathInfo != null) { jspUri += pathInfo; } } } if (log.isDebugEnabled()) { log.debug("JspEngine --> " + jspUri); log.debug("\t ServletPath: " + request.getServletPath()); log.debug("\t PathInfo: " + request.getPathInfo()); log.debug("\t RealPath: " + context.getRealPath(jspUri)); log.debug("\t RequestURI: " + request.getRequestURI()); log.debug("\t QueryString: " + request.getQueryString()); } try { boolean precompile = preCompile(request); serviceJspFile(request, response, jspUri, precompile); } catch (RuntimeException e) { throw e; } catch (ServletException e) { throw e; } catch (IOException e) { throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException(e); } }
// in java/org/apache/jasper/servlet/JspServlet.java
private void serviceJspFile(HttpServletRequest request, HttpServletResponse response, String jspUri, boolean precompile) throws ServletException, IOException { JspServletWrapper wrapper = rctxt.getWrapper(jspUri); if (wrapper == null) { synchronized(this) { wrapper = rctxt.getWrapper(jspUri); if (wrapper == null) { // Check if the requested JSP page exists, to avoid // creating unnecessary directories and files. if (null == context.getResource(jspUri)) { handleMissingResource(request, response, jspUri); return; } wrapper = new JspServletWrapper(config, options, jspUri, rctxt); rctxt.addWrapper(jspUri,wrapper); } } } try { wrapper.service(request, response, precompile); } catch (FileNotFoundException fnfe) { handleMissingResource(request, response, jspUri); } }
// in java/org/apache/jasper/servlet/JspServlet.java
private void handleMissingResource(HttpServletRequest request, HttpServletResponse response, String jspUri) throws ServletException, IOException { String includeRequestUri = (String)request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored String msg = Localizer.getMessage("jsp.error.file.not.found",jspUri); // Strictly, filtering this is an application // responsibility but just in case... throw new ServletException(SecurityUtil.filter(msg)); } else { try { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); } catch (IllegalStateException ise) { log.error(Localizer.getMessage("jsp.error.file.not.found", jspUri)); } } return; }
// in java/org/apache/catalina/startup/Tomcat.java
public Context addWebapp(String contextPath, String baseDir) throws ServletException { return addWebapp(getHost(), contextPath, baseDir); }
// in java/org/apache/catalina/startup/Tomcat.java
Override public synchronized Servlet loadServlet() throws ServletException { if (singleThreadModel) { Servlet instance; try { instance = existing.getClass().newInstance(); } catch (InstantiationException e) { throw new ServletException(e); } catch (IllegalAccessException e) { throw new ServletException(e); } instance.init(facade); return instance; } else { if (!init) { existing.init(facade); init = true; } return existing; } }
// in java/org/apache/catalina/filters/SetCharacterEncodingFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Conditionally select and set the character encoding to be used if (ignore || (request.getCharacterEncoding() == null)) { String characterEncoding = selectEncoding(request); if (characterEncoding != null) { request.setCharacterEncoding(characterEncoding); } } // Pass control on to the next filter chain.doFilter(request, response); }
// in java/org/apache/catalina/filters/FilterBase.java
Override public void init(FilterConfig filterConfig) throws ServletException { Enumeration<String> paramNames = filterConfig.getInitParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); if (!IntrospectionUtils.setProperty(this, paramName, filterConfig.getInitParameter(paramName))) { String msg = sm.getString("filterbase.noSuchProperty", paramName, this.getClass().getName()); if (isConfigProblemFatal()) { throw new ServletException(msg); } else { getLogger().warn(msg); } } } }
// in java/org/apache/catalina/filters/RequestDumperFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest hRequest = null; HttpServletResponse hResponse = null; if (request instanceof HttpServletRequest) { hRequest = (HttpServletRequest) request; } if (response instanceof HttpServletResponse) { hResponse = (HttpServletResponse) response; } // Log pre-service information doLog("START TIME ", getTimestamp()); if (hRequest == null) { doLog(" requestURI", NON_HTTP_REQ_MSG); doLog(" authType", NON_HTTP_REQ_MSG); } else { doLog(" requestURI", hRequest.getRequestURI()); doLog(" authType", hRequest.getAuthType()); } doLog(" characterEncoding", request.getCharacterEncoding()); doLog(" contentLength", Integer.valueOf(request.getContentLength()).toString()); doLog(" contentType", request.getContentType()); if (hRequest == null) { doLog(" contextPath", NON_HTTP_REQ_MSG); doLog(" cookie", NON_HTTP_REQ_MSG); doLog(" header", NON_HTTP_REQ_MSG); } else { doLog(" contextPath", hRequest.getContextPath()); Cookie cookies[] = hRequest.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { doLog(" cookie", cookies[i].getName() + "=" + cookies[i].getValue()); } } Enumeration<String> hnames = hRequest.getHeaderNames(); while (hnames.hasMoreElements()) { String hname = hnames.nextElement(); Enumeration<String> hvalues = hRequest.getHeaders(hname); while (hvalues.hasMoreElements()) { String hvalue = hvalues.nextElement(); doLog(" header", hname + "=" + hvalue); } } } doLog(" locale", request.getLocale().toString()); if (hRequest == null) { doLog(" method", NON_HTTP_REQ_MSG); } else { doLog(" method", hRequest.getMethod()); } Enumeration<String> pnames = request.getParameterNames(); while (pnames.hasMoreElements()) { String pname = pnames.nextElement(); String pvalues[] = request.getParameterValues(pname); StringBuilder result = new StringBuilder(pname); result.append('='); for (int i = 0; i < pvalues.length; i++) { if (i > 0) { result.append(", "); } result.append(pvalues[i]); } doLog(" parameter", result.toString()); } if (hRequest == null) { doLog(" pathInfo", NON_HTTP_REQ_MSG); } else { doLog(" pathInfo", hRequest.getPathInfo()); } doLog(" protocol", request.getProtocol()); if (hRequest == null) { doLog(" queryString", NON_HTTP_REQ_MSG); } else { doLog(" queryString", hRequest.getQueryString()); } doLog(" remoteAddr", request.getRemoteAddr()); doLog(" remoteHost", request.getRemoteHost()); if (hRequest == null) { doLog(" remoteUser", NON_HTTP_REQ_MSG); doLog("requestedSessionId", NON_HTTP_REQ_MSG); } else { doLog(" remoteUser", hRequest.getRemoteUser()); doLog("requestedSessionId", hRequest.getRequestedSessionId()); } doLog(" scheme", request.getScheme()); doLog(" serverName", request.getServerName()); doLog(" serverPort", Integer.valueOf(request.getServerPort()).toString()); if (hRequest == null) { doLog(" servletPath", NON_HTTP_REQ_MSG); } else { doLog(" servletPath", hRequest.getServletPath()); } doLog(" isSecure", Boolean.valueOf(request.isSecure()).toString()); doLog("------------------", "--------------------------------------------"); // Perform the request chain.doFilter(request, response); // Log post-service information doLog("------------------", "--------------------------------------------"); if (hRequest == null) { doLog(" authType", NON_HTTP_REQ_MSG); } else { doLog(" authType", hRequest.getAuthType()); } doLog(" contentType", response.getContentType()); if (hResponse == null) { doLog(" header", NON_HTTP_RES_MSG); } else { Iterable<String> rhnames = hResponse.getHeaderNames(); for (String rhname : rhnames) { Iterable<String> rhvalues = hResponse.getHeaders(rhname); for (String rhvalue : rhvalues) { doLog(" header", rhname + "=" + rhvalue); } } } if (hRequest == null) { doLog(" remoteUser", NON_HTTP_REQ_MSG); } else { doLog(" remoteUser", hRequest.getRemoteUser()); } if (hResponse == null) { doLog(" remoteUser", NON_HTTP_RES_MSG); } else { doLog(" status", Integer.valueOf(hResponse.getStatus()).toString()); } doLog("END TIME ", getTimestamp()); doLog("==================", "============================================"); }
// in java/org/apache/catalina/filters/RequestDumperFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { // NOOP }
// in java/org/apache/catalina/filters/RequestFilter.java
protected void process(String property, ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (isAllowed(property)) { chain.doFilter(request, response); } else { if (response instanceof HttpServletResponse) { ((HttpServletResponse) response).sendError(denyStatus); } else { sendErrorWhenNotHttp(response); } } }
// in java/org/apache/catalina/filters/RequestFilter.java
protected void processCometEvent(String property, CometEvent event, CometFilterChain chain) throws IOException, ServletException { HttpServletResponse response = event.getHttpServletResponse(); if (isAllowed(property)) { chain.doFilterEvent(event); } else { response.sendError(denyStatus); event.close(); } }
// in java/org/apache/catalina/filters/AddDefaultCharsetFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { super.init(filterConfig); if (encoding == null || encoding.length() == 0 || encoding.equalsIgnoreCase("default")) { encoding = DEFAULT_ENCODING; } else if (encoding.equalsIgnoreCase("system")) { encoding = Charset.defaultCharset().name(); } else if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException(sm.getString( "addDefaultCharset.unsupportedCharset", encoding)); } }
// in java/org/apache/catalina/filters/AddDefaultCharsetFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Wrap the response if (response instanceof HttpServletResponse) { ResponseWrapper wrapped = new ResponseWrapper((HttpServletResponse)response, encoding); chain.doFilter(request, wrapped); } else { chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/RemoteHostFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { process(request.getRemoteHost(), request, response, chain); }
// in java/org/apache/catalina/filters/RemoteHostFilter.java
Override public void doFilterEvent(CometEvent event, CometFilterChain chain) throws IOException, ServletException { processCometEvent(event.getHttpServletRequest().getRemoteHost(), event, chain); }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (response.isCommitted()) { if (log.isDebugEnabled()) { log.debug(sm.getString( "expiresFilter.responseAlreadyCommited", httpRequest.getRequestURL())); } chain.doFilter(request, response); } else { XHttpServletResponse xResponse = new XHttpServletResponse( httpRequest, httpResponse); chain.doFilter(request, xResponse); if (!xResponse.isWriteResponseBodyStarted()) { // Empty response, manually trigger // onBeforeWriteResponseBody() onBeforeWriteResponseBody(httpRequest, xResponse); } } } else { chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/ExpiresFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { for (Enumeration<String> names = filterConfig.getInitParameterNames(); names.hasMoreElements();) { String name = names.nextElement(); String value = filterConfig.getInitParameter(name); try { if (name.startsWith(PARAMETER_EXPIRES_BY_TYPE)) { String contentType = name.substring( PARAMETER_EXPIRES_BY_TYPE.length()).trim(); ExpiresConfiguration expiresConfiguration = parseExpiresConfiguration(value); this.expiresConfigurationByContentType.put(contentType, expiresConfiguration); } else if (name.equalsIgnoreCase(PARAMETER_EXPIRES_DEFAULT)) { ExpiresConfiguration expiresConfiguration = parseExpiresConfiguration(value); this.defaultExpiresConfiguration = expiresConfiguration; } else if (name.equalsIgnoreCase(PARAMETER_EXPIRES_EXCLUDED_RESPONSE_STATUS_CODES)) { this.excludedResponseStatusCodes = commaDelimitedListToIntArray(value); } else { log.warn(sm.getString( "expiresFilter.unknownParameterIgnored", name, value)); } } catch (RuntimeException e) { throw new ServletException(sm.getString( "expiresFilter.exceptionProcessingParameter", name, value), e); } } log.debug(sm.getString("expiresFilter.filterInitialized", this.toString())); }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (internalProxies != null && internalProxies.matcher(request.getRemoteAddr()).matches()) { String remoteIp = null; // In java 6, proxiesHeaderValue should be declared as a java.util.Deque LinkedList<String> proxiesHeaderValue = new LinkedList<String>(); StringBuilder concatRemoteIpHeaderValue = new StringBuilder(); for (Enumeration<String> e = request.getHeaders(remoteIpHeader); e.hasMoreElements();) { if (concatRemoteIpHeaderValue.length() > 0) { concatRemoteIpHeaderValue.append(", "); } concatRemoteIpHeaderValue.append(e.nextElement()); } String[] remoteIpHeaderValue = commaDelimitedListToStringArray(concatRemoteIpHeaderValue.toString()); int idx; // loop on remoteIpHeaderValue to find the first trusted remote ip and to build the proxies chain for (idx = remoteIpHeaderValue.length - 1; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; remoteIp = currentRemoteIp; if (internalProxies.matcher(currentRemoteIp).matches()) { // do nothing, internalProxies IPs are not appended to the } else if (trustedProxies != null && trustedProxies.matcher(currentRemoteIp).matches()) { proxiesHeaderValue.addFirst(currentRemoteIp); } else { idx--; // decrement idx because break statement doesn't do it break; } } // continue to loop on remoteIpHeaderValue to build the new value of the remoteIpHeader LinkedList<String> newRemoteIpHeaderValue = new LinkedList<String>(); for (; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; newRemoteIpHeaderValue.addFirst(currentRemoteIp); } XForwardedRequest xRequest = new XForwardedRequest(request); if (remoteIp != null) { xRequest.setRemoteAddr(remoteIp); xRequest.setRemoteHost(remoteIp); if (proxiesHeaderValue.size() == 0) { xRequest.removeHeader(proxiesHeader); } else { String commaDelimitedListOfProxies = listToCommaDelimitedString(proxiesHeaderValue); xRequest.setHeader(proxiesHeader, commaDelimitedListOfProxies); } if (newRemoteIpHeaderValue.size() == 0) { xRequest.removeHeader(remoteIpHeader); } else { String commaDelimitedRemoteIpHeaderValue = listToCommaDelimitedString(newRemoteIpHeaderValue); xRequest.setHeader(remoteIpHeader, commaDelimitedRemoteIpHeaderValue); } } if (protocolHeader != null) { String protocolHeaderValue = request.getHeader(protocolHeader); if (protocolHeaderValue == null) { // don't modify the secure,scheme and serverPort attributes of the request } else if (protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue)) { xRequest.setSecure(true); xRequest.setScheme("https"); setPorts(xRequest, httpsServerPort); } else { xRequest.setSecure(false); xRequest.setScheme("http"); setPorts(xRequest, httpServerPort); } } if (log.isDebugEnabled()) { log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "', originalRemoteHost='" + request.getRemoteHost() + "', originalSecure='" + request.isSecure() + "', originalScheme='" + request.getScheme() + "', original[" + remoteIpHeader + "]='" + concatRemoteIpHeaderValue + "', original[" + protocolHeader + "]='" + (protocolHeader == null ? null : request.getHeader(protocolHeader)) + "' will be seen as newRemoteAddr='" + xRequest.getRemoteAddr() + "', newRemoteHost='" + xRequest.getRemoteHost() + "', newScheme='" + xRequest.getScheme() + "', newSecure='" + xRequest.isSecure() + "', new[" + remoteIpHeader + "]='" + xRequest.getHeader(remoteIpHeader) + "', new[" + proxiesHeader + "]='" + xRequest.getHeader(proxiesHeader) + "'"); } if (requestAttributesEnabled) { request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE, request.getRemoteAddr()); request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE, request.getRemoteHost()); request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE, request.getProtocol()); request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE, Integer.valueOf(request.getServerPort())); } chain.doFilter(xRequest, response); } else { if (log.isDebugEnabled()) { log.debug("Skip RemoteIpFilter for request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "'"); } chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { doFilter((HttpServletRequest)request, (HttpServletResponse)response, chain); } else { chain.doFilter(request, response); } }
// in java/org/apache/catalina/filters/RemoteIpFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { if (filterConfig.getInitParameter(INTERNAL_PROXIES_PARAMETER) != null) { setInternalProxies(filterConfig.getInitParameter(INTERNAL_PROXIES_PARAMETER)); } if (filterConfig.getInitParameter(PROTOCOL_HEADER_PARAMETER) != null) { setProtocolHeader(filterConfig.getInitParameter(PROTOCOL_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER) != null) { setProtocolHeaderHttpsValue(filterConfig.getInitParameter(PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER)); } if (filterConfig.getInitParameter(PORT_HEADER_PARAMETER) != null) { setPortHeader(filterConfig.getInitParameter(PORT_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(CHANGE_LOCAL_PORT_PARAMETER) != null) { setChangeLocalPort(Boolean.parseBoolean(filterConfig.getInitParameter(CHANGE_LOCAL_PORT_PARAMETER))); } if (filterConfig.getInitParameter(PROXIES_HEADER_PARAMETER) != null) { setProxiesHeader(filterConfig.getInitParameter(PROXIES_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(REMOTE_IP_HEADER_PARAMETER) != null) { setRemoteIpHeader(filterConfig.getInitParameter(REMOTE_IP_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(TRUSTED_PROXIES_PARAMETER) != null) { setTrustedProxies(filterConfig.getInitParameter(TRUSTED_PROXIES_PARAMETER)); } if (filterConfig.getInitParameter(HTTP_SERVER_PORT_PARAMETER) != null) { try { setHttpServerPort(Integer.parseInt(filterConfig.getInitParameter(HTTP_SERVER_PORT_PARAMETER))); } catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTP_SERVER_PORT_PARAMETER + " : " + e.getMessage()); } } if (filterConfig.getInitParameter(HTTPS_SERVER_PORT_PARAMETER) != null) { try { setHttpsServerPort(Integer.parseInt(filterConfig.getInitParameter(HTTPS_SERVER_PORT_PARAMETER))); } catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTPS_SERVER_PORT_PARAMETER + " : " + e.getMessage()); } } }
// in java/org/apache/catalina/filters/WebdavFixFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { // NOOP }
// in java/org/apache/catalina/filters/WebdavFixFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { chain.doFilter(request, response); return; } HttpServletRequest httpRequest = ((HttpServletRequest) request); HttpServletResponse httpResponse = ((HttpServletResponse) response); String ua = httpRequest.getHeader("User-Agent"); if (ua == null || ua.length() == 0 || !ua.startsWith(UA_MINIDIR_START)) { // No UA or starts with non MS value // Hope everything just works... chain.doFilter(request, response); } else if (ua.startsWith(UA_MINIDIR_5_1_2600)) { // XP 32-bit SP3 - needs redirect with explicit port httpResponse.sendRedirect(buildRedirect(httpRequest)); } else if (ua.startsWith(UA_MINIDIR_5_2_3790)) { // XP 64-bit SP2 if (!"".equals(httpRequest.getContextPath())) { log(request, "XP-x64-SP2 clients only work with the root context"); } // Namespace issue maybe // see http://greenbytes.de/tech/webdav/webdav-redirector-list.html log(request, "XP-x64-SP2 is known not to work with WebDAV Servlet"); chain.doFilter(request, response); } else { // Don't know which MS client it is - try the redirect with an // explicit port in the hope that it moves the client to a different // WebDAV implementation that works httpResponse.sendRedirect(buildRedirect(httpRequest)); } }
// in java/org/apache/catalina/filters/RemoteAddrFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { process(request.getRemoteAddr(), request, response, chain); }
// in java/org/apache/catalina/filters/RemoteAddrFilter.java
Override public void doFilterEvent(CometEvent event, CometFilterChain chain) throws IOException, ServletException { processCometEvent(event.getHttpServletRequest().getRemoteAddr(), event, chain); }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
Override public void init(FilterConfig filterConfig) throws ServletException { // Set the parameters super.init(filterConfig); try { Class<?> clazz = Class.forName(randomClass); randomSource = (Random) clazz.newInstance(); } catch (ClassNotFoundException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; } catch (InstantiationException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; } catch (IllegalAccessException e) { ServletException se = new ServletException(sm.getString( "csrfPrevention.invalidRandomClass", randomClass), e); throw se; } }
// in java/org/apache/catalina/filters/CsrfPreventionFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ServletResponse wResponse = null; if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; boolean skipNonceCheck = false; if (Constants.METHOD_GET.equals(req.getMethod())) { String path = req.getServletPath(); if (req.getPathInfo() != null) { path = path + req.getPathInfo(); } if (entryPoints.contains(path)) { skipNonceCheck = true; } } @SuppressWarnings("unchecked") LruCache<String> nonceCache = (LruCache<String>) req.getSession(true).getAttribute( Constants.CSRF_NONCE_SESSION_ATTR_NAME); if (!skipNonceCheck) { String previousNonce = req.getParameter(Constants.CSRF_NONCE_REQUEST_PARAM); if (nonceCache != null && !nonceCache.contains(previousNonce)) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } if (nonceCache == null) { nonceCache = new LruCache<String>(nonceCacheSize); req.getSession().setAttribute( Constants.CSRF_NONCE_SESSION_ATTR_NAME, nonceCache); } String newNonce = generateNonce(); nonceCache.add(newNonce); wResponse = new CsrfResponseWrapper(res, newNonce); } else { wResponse = response; } chain.doFilter(request, wResponse); }
// in java/org/apache/catalina/filters/FailedRequestFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!isGoodRequest(request)) { ((HttpServletResponse) response) .sendError(HttpServletResponse.SC_BAD_REQUEST); return; } chain.doFilter(request, response); }
// in java/org/apache/catalina/filters/FailedRequestFilter.java
Override public void doFilterEvent(CometEvent event, CometFilterChain chain) throws IOException, ServletException { if (event.getEventType() == CometEvent.EventType.BEGIN && !isGoodRequest(event.getHttpServletRequest())) { event.getHttpServletResponse().sendError( HttpServletResponse.SC_BAD_REQUEST); event.close(); return; } chain.doFilterEvent(event); }
// in java/org/apache/catalina/websocket/WebSocketServlet.java
Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Information required to send the server handshake message String key; String subProtocol = null; List<String> extensions = Collections.emptyList(); if (!headerContainsToken(req, "upgrade", "websocket")) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (!headerContainsToken(req, "connection", "upgrade")) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (!headerContainsToken(req, "sec-websocket-version", "13")) { resp.setStatus(426); resp.setHeader("Sec-WebSocket-Version", "13"); return; } key = req.getHeader("Sec-WebSocket-Key"); if (key == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } String origin = req.getHeader("Origin"); if (!verifyOrigin(origin)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } List<String> subProtocols = getTokensFromHeader(req, "Sec-WebSocket-Protocol-Client"); if (!subProtocols.isEmpty()) { subProtocol = selectSubProtocol(subProtocols); } // TODO Read client handshake - Sec-WebSocket-Extensions // TODO Extensions require the ability to specify something (API TBD) // that can be passed to the Tomcat internals and process extension // data present when the frame is fragmented. // If we got this far, all is good. Accept the connection. resp.setHeader("Upgrade", "websocket"); resp.setHeader("Connection", "upgrade"); resp.setHeader("Sec-WebSocket-Accept", getWebSocketAccept(key)); if (subProtocol != null) { resp.setHeader("Sec-WebSocket-Protocol", subProtocol); } if (!extensions.isEmpty()) { // TODO } // Small hack until the Servlet API provides a way to do this. StreamInbound inbound = createWebSocketInbound(subProtocol); ((RequestFacade) req).doUpgrade(inbound); }
// in java/org/apache/catalina/websocket/WebSocketServlet.java
private String getWebSocketAccept(String key) throws ServletException { MessageDigest sha1Helper = sha1Helpers.poll(); if (sha1Helper == null) { try { sha1Helper = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new ServletException(e); } } sha1Helper.reset(); sha1Helper.update(key.getBytes(B2CConverter.ISO_8859_1)); String result = Base64.encode(sha1Helper.digest(WS_ACCEPT)); sha1Helpers.add(sha1Helper); return result; }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need // By obtaining the command from the pathInfo, per-command security can // be configured in web.xml String command = request.getPathInfo(); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Process the requested command if (command == null || command.equals("/")) { // No command == list } else if (command.equals("/list")) { // List always displayed - nothing to do here } else if (command.equals("/sessions")) { try { doSessions(cn, request, response, smClient); return; } catch (Exception e) { log("HTMLManagerServlet.sessions[" + cn + "]", e); message = smClient.getString("managerServlet.exception", e.toString()); } } else if (command.equals("/upload") || command.equals("/deploy") || command.equals("/reload") || command.equals("/undeploy") || command.equals("/expire") || command.equals("/start") || command.equals("/stop")) { message = smClient.getString("managerServlet.postCommand", command); } else { message = smClient.getString("managerServlet.unknownCommand", command); } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need // By obtaining the command from the pathInfo, per-command security can // be configured in web.xml String command = request.getPathInfo(); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } String deployPath = request.getParameter("deployPath"); ContextName deployCn = null; if (deployPath != null) { deployCn = new ContextName(deployPath, request.getParameter("deployVersion")); } String deployConfig = request.getParameter("deployConfig"); String deployWar = request.getParameter("deployWar"); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; if (command == null || command.length() == 0) { // No command == list // List always displayed -> do nothing } else if (command.equals("/upload")) { message = upload(request, smClient); } else if (command.equals("/deploy")) { message = deployInternal(deployConfig, deployCn, deployWar, smClient); } else if (command.equals("/reload")) { message = reload(cn, smClient); } else if (command.equals("/undeploy")) { message = undeploy(cn, smClient); } else if (command.equals("/expire")) { message = expireSessions(cn, request, smClient); } else if (command.equals("/start")) { message = start(cn, smClient); } else if (command.equals("/stop")) { message = stop(cn, smClient); } else if (command.equals("/findleaks")) { message = findleaks(smClient); } else { // Try GET doGet(request,response); return; } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected String upload(HttpServletRequest request, StringManager smClient) throws IOException, ServletException { String message = ""; Part warPart = null; String filename = null; Collection<Part> parts = request.getParts(); Iterator<Part> iter = parts.iterator(); try { while (iter.hasNext()) { Part part = iter.next(); if (part.getName().equals("deployWar") && warPart == null) { warPart = part; } else { part.delete(); } } while (true) { if (warPart == null) { message = smClient.getString( "htmlManagerServlet.deployUploadNoFile"); break; } filename = extractFilename(warPart.getHeader("Content-Disposition")); if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) { message = smClient.getString( "htmlManagerServlet.deployUploadNotWar", filename); break; } // Get the filename if uploaded name includes a path if (filename.lastIndexOf('\\') >= 0) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (filename.lastIndexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } // Identify the appBase of the owning Host of this Context // (if any) File file = new File(host.getAppBaseFile(), filename); if (file.exists()) { message = smClient.getString( "htmlManagerServlet.deployUploadWarExists", filename); break; } ContextName cn = new ContextName(filename); String name = cn.getName(); if ((host.findChild(name) != null) && !isDeployed(name)) { message = smClient.getString( "htmlManagerServlet.deployUploadInServerXml", filename); break; } if (!isServiced(name)) { addServiced(name); try { warPart.write(file.getAbsolutePath()); // Perform new deployment check(name); } finally { removeServiced(name); } } break; } } catch(Exception e) { message = smClient.getString ("htmlManagerServlet.deployUploadFail", e.getMessage()); log(message, e); } finally { if (warPart != null) { warPart.delete(); } warPart = null; } return message; }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
Override public void init() throws ServletException { super.init(); // Set our properties from the initialization parameters String value = null; value = getServletConfig().getInitParameter("showProxySessions"); showProxySessions = Boolean.parseBoolean(value); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected void doSessions(ContextName cn, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { req.setAttribute("path", cn.getPath()); req.setAttribute("version", cn.getVersion()); String action = req.getParameter("action"); if (debug >= 1) { log("sessions: Session action '" + action + "' for web application '" + cn.getDisplayName() + "'"); } if ("sessionDetail".equals(action)) { String sessionId = req.getParameter("sessionId"); displaySessionDetailPage(req, resp, cn, sessionId, smClient); return; } else if ("invalidateSessions".equals(action)) { String[] sessionIds = req.getParameterValues("sessionIds"); int i = invalidateSessions(cn, sessionIds, smClient); req.setAttribute(APPLICATION_MESSAGE, "" + i + " sessions invalidated."); } else if ("removeSessionAttribute".equals(action)) { String sessionId = req.getParameter("sessionId"); String name = req.getParameter("attributeName"); boolean removed = removeSessionAttribute(cn, sessionId, name, smClient); String outMessage = removed ? "Session attribute '" + name + "' removed." : "Session did not contain any attribute named '" + name + "'"; req.setAttribute(APPLICATION_MESSAGE, outMessage); displaySessionDetailPage(req, resp, cn, sessionId, smClient); return; } // else displaySessionsListPage(cn, req, resp, smClient); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected void displaySessionsListPage(ContextName cn, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { List<Session> sessions = getSessionsForName(cn, smClient); String sortBy = req.getParameter("sort"); String orderBy = null; if (null != sortBy && !"".equals(sortBy.trim())) { Comparator<Session> comparator = getComparator(sortBy); if (comparator != null) { orderBy = req.getParameter("order"); if ("DESC".equalsIgnoreCase(orderBy)) { comparator = new ReverseComparator(comparator); orderBy = "ASC"; } else { orderBy = "DESC"; } try { Collections.sort(sessions, comparator); } catch (IllegalStateException ise) { // at least 1 of the sessions is invalidated req.setAttribute(APPLICATION_ERROR, "Can't sort session list: one session is invalidated"); } } else { log("WARNING: unknown sort order: " + sortBy); } } // keep sort order req.setAttribute("sort", sortBy); req.setAttribute("order", orderBy); req.setAttribute("activeSessions", sessions); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now getServletContext().getRequestDispatcher(sessionsListJspPath).include(req, resp); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
protected void displaySessionDetailPage(HttpServletRequest req, HttpServletResponse resp, ContextName cn, String sessionId, StringManager smClient) throws ServletException, IOException { Session session = getSessionForNameAndId(cn, sessionId, smClient); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now req.setAttribute("currentSession", session); getServletContext().getRequestDispatcher(resp.encodeURL(sessionDetailJspPath)).include(req, resp); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
Override public void init() throws ServletException { // Retrieve the MBean server registry = Registry.getRegistry(null, null); mBeanServer = Registry.getRegistry(null, null).getMBeanServer(); }
// in java/org/apache/catalina/manager/JMXProxyServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); PrintWriter writer = response.getWriter(); if( mBeanServer==null ) { writer.println("Error - No mbean server"); return; } String qry=request.getParameter("set"); if( qry!= null ) { String name=request.getParameter("att"); String val=request.getParameter("val"); setAttribute( writer, qry, name, val ); return; } qry=request.getParameter("get"); if( qry!= null ) { String name=request.getParameter("att"); getAttribute( writer, qry, name, request.getParameter("key") ); return; } qry = request.getParameter("invoke"); if(qry != null) { String opName=request.getParameter("op"); String ps = request.getParameter("ps"); String[] valuesStr; if (ps == null) { valuesStr = new String[0]; } else { valuesStr = ps.split(","); } invokeOperation( writer, qry, opName,valuesStr ); return; } qry=request.getParameter("qry"); if( qry == null ) { qry = "*:*"; } listBeans( writer, qry ); }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null) command = request.getServletPath(); String name = request.getParameter("name"); // Prepare our output writer to generate the response message response.setContentType("text/plain; charset=" + Constants.CHARSET); PrintWriter writer = response.getWriter(); // Process the requested command if (command == null) { writer.println(sm.getString("hostManagerServlet.noCommand")); } else if (command.equals("/add")) { add(request, writer, name, false, smClient); } else if (command.equals("/remove")) { remove(writer, name, smClient); } else if (command.equals("/list")) { list(writer, smClient); } else if (command.equals("/start")) { start(writer, name, smClient); } else if (command.equals("/stop")) { stop(writer, name, smClient); } else { writer.println(sm.getString("hostManagerServlet.unknownCommand", command)); } // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
Override public void init() throws ServletException { // Ensure that our ContainerServlet properties have been set if ((wrapper == null) || (context == null)) throw new UnavailableException (sm.getString("hostManagerServlet.noWrapper")); // Set our properties from the initialization parameters String value = null; try { value = getServletConfig().getInitParameter("debug"); debug = Integer.parseInt(value); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } }
// in java/org/apache/catalina/manager/host/HTMLHostManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Process the requested command if (command == null) { // No command == list } else if (command.equals("/list")) { // Nothing to do - always generate list } else if (command.equals("/add") || command.equals("/remove") || command.equals("/start") || command.equals("/stop")) { message = smClient.getString( "hostManagerServlet.postCommand", command); } else { message = smClient.getString( "hostManagerServlet.unknownCommand", command); } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/host/HTMLHostManagerServlet.java
Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); String name = request.getParameter("name"); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Process the requested command if (command == null) { // No command == list } else if (command.equals("/add")) { message = add(request, name, smClient); } else if (command.equals("/remove")) { message = remove(name, smClient); } else if (command.equals("/start")) { message = start(name, smClient); } else if (command.equals("/stop")) { message = stop(name, smClient); } else { //Try GET doGet(request, response); } list(request, response, message, smClient); }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
Override public void init() throws ServletException { // Retrieve the MBean server mBeanServer = Registry.getRegistry(null, null).getMBeanServer(); try { // Query protocol handlers String onStr = "*:type=ProtocolHandler,*"; ObjectName objectName = new ObjectName(onStr); Set<ObjectInstance> set = mBeanServer.queryMBeans(objectName, null); Iterator<ObjectInstance> iterator = set.iterator(); while (iterator.hasNext()) { ObjectInstance oi = iterator.next(); protocolHandlers.addElement(oi.getObjectName()); } // Query Thread Pools onStr = "*:type=ThreadPool,*"; objectName = new ObjectName(onStr); set = mBeanServer.queryMBeans(objectName, null); iterator = set.iterator(); while (iterator.hasNext()) { ObjectInstance oi = iterator.next(); threadPools.addElement(oi.getObjectName()); } // Query Global Request Processors onStr = "*:type=GlobalRequestProcessor,*"; objectName = new ObjectName(onStr); set = mBeanServer.queryMBeans(objectName, null); iterator = set.iterator(); while (iterator.hasNext()) { ObjectInstance oi = iterator.next(); globalRequestProcessors.addElement(oi.getObjectName()); } // Query Request Processors onStr = "*:type=RequestProcessor,*"; objectName = new ObjectName(onStr); set = mBeanServer.queryMBeans(objectName, null); iterator = set.iterator(); while (iterator.hasNext()) { ObjectInstance oi = iterator.next(); requestProcessors.addElement(oi.getObjectName()); } // Register with MBean server onStr = "JMImplementation:type=MBeanServerDelegate"; objectName = new ObjectName(onStr); mBeanServer.addNotificationListener(objectName, this, null, null); } catch (Exception e) { e.printStackTrace(); } }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // mode is flag for HTML or XML output int mode = 0; // if ?XML=true, set the mode to XML if (request.getParameter("XML") != null && request.getParameter("XML").equals("true")) { mode = 1; } StatusTransformer.setContentType(response, mode); PrintWriter writer = response.getWriter(); boolean completeStatus = false; if ((request.getPathInfo() != null) && (request.getPathInfo().equals("/all"))) { completeStatus = true; } // use StatusTransformer to output status Object[] args = new Object[1]; args[0] = request.getContextPath(); StatusTransformer.writeHeader(writer,args,mode); // Body Header Section args = new Object[2]; args[0] = request.getContextPath(); if (completeStatus) { args[1] = sm.getString("statusServlet.complete"); } else { args[1] = sm.getString("statusServlet.title"); } // use StatusTransformer to output status StatusTransformer.writeBody(writer,args,mode); // Manager Section args = new Object[9]; args[0] = sm.getString("htmlManagerServlet.manager"); args[1] = response.encodeURL(request.getContextPath() + "/html/list"); args[2] = sm.getString("htmlManagerServlet.list"); args[3] = response.encodeURL (request.getContextPath() + "/" + sm.getString("htmlManagerServlet.helpHtmlManagerFile")); args[4] = sm.getString("htmlManagerServlet.helpHtmlManager"); args[5] = response.encodeURL (request.getContextPath() + "/" + sm.getString("htmlManagerServlet.helpManagerFile")); args[6] = sm.getString("htmlManagerServlet.helpManager"); if (completeStatus) { args[7] = response.encodeURL (request.getContextPath() + "/status"); args[8] = sm.getString("statusServlet.title"); } else { args[7] = response.encodeURL (request.getContextPath() + "/status/all"); args[8] = sm.getString("statusServlet.complete"); } // use StatusTransformer to output status StatusTransformer.writeManager(writer,args,mode); // Server Header Section args = new Object[9]; args[0] = sm.getString("htmlManagerServlet.serverTitle"); args[1] = sm.getString("htmlManagerServlet.serverVersion"); args[2] = sm.getString("htmlManagerServlet.serverJVMVersion"); args[3] = sm.getString("htmlManagerServlet.serverJVMVendor"); args[4] = sm.getString("htmlManagerServlet.serverOSName"); args[5] = sm.getString("htmlManagerServlet.serverOSVersion"); args[6] = sm.getString("htmlManagerServlet.serverOSArch"); args[7] = sm.getString("htmlManagerServlet.serverHostname"); args[8] = sm.getString("htmlManagerServlet.serverIPAddress"); // use StatusTransformer to output status StatusTransformer.writePageHeading(writer,args,mode); // Server Row Section args = new Object[8]; args[0] = ServerInfo.getServerInfo(); args[1] = System.getProperty("java.runtime.version"); args[2] = System.getProperty("java.vm.vendor"); args[3] = System.getProperty("os.name"); args[4] = System.getProperty("os.version"); args[5] = System.getProperty("os.arch"); try { InetAddress address = InetAddress.getLocalHost(); args[6] = address.getHostName(); args[7] = address.getHostAddress(); } catch (UnknownHostException e) { args[6] = "-"; args[7] = "-"; } // use StatusTransformer to output status StatusTransformer.writeServerInfo(writer, args, mode); try { // Display operating system statistics using APR if available StatusTransformer.writeOSState(writer,mode); // Display virtual machine statistics StatusTransformer.writeVMState(writer,mode); Enumeration<ObjectName> enumeration = threadPools.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); String name = objectName.getKeyProperty("name"); // use StatusTransformer to output status StatusTransformer.writeConnectorState (writer, objectName, name, mBeanServer, globalRequestProcessors, requestProcessors, mode); } if ((request.getPathInfo() != null) && (request.getPathInfo().equals("/all"))) { // Note: Retrieving the full status is much slower // use StatusTransformer to output status StatusTransformer.writeDetailedState (writer, mBeanServer, mode); } } catch (Exception e) { throw new ServletException(e); } // use StatusTransformer to output status StatusTransformer.writeFooter(writer, mode); }
// in java/org/apache/catalina/manager/ManagerServlet.java
Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null) command = request.getServletPath(); String config = request.getParameter("config"); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } String type = request.getParameter("type"); String war = request.getParameter("war"); String tag = request.getParameter("tag"); boolean update = false; if ((request.getParameter("update") != null) && (request.getParameter("update").equals("true"))) { update = true; } boolean statusLine = false; if ("true".equals(request.getParameter("statusLine"))) { statusLine = true; } // Prepare our output writer to generate the response message response.setContentType("text/plain; charset=" + Constants.CHARSET); PrintWriter writer = response.getWriter(); // Process the requested command (note - "/deploy" is not listed here) if (command == null) { writer.println(smClient.getString("managerServlet.noCommand")); } else if (command.equals("/deploy")) { if (war != null || config != null) { deploy(writer, config, cn, war, update, smClient); } else { deploy(writer, cn, tag, smClient); } } else if (command.equals("/list")) { list(writer, smClient); } else if (command.equals("/reload")) { reload(writer, cn, smClient); } else if (command.equals("/resources")) { resources(writer, type, smClient); } else if (command.equals("/save")) { save(writer, path, smClient); } else if (command.equals("/serverinfo")) { serverinfo(writer, smClient); } else if (command.equals("/sessions")) { expireSessions(writer, cn, request, smClient); } else if (command.equals("/expire")) { expireSessions(writer, cn, request, smClient); } else if (command.equals("/start")) { start(writer, cn, smClient); } else if (command.equals("/stop")) { stop(writer, cn, smClient); } else if (command.equals("/undeploy")) { undeploy(writer, cn, smClient); } else if (command.equals("/findleaks")) { findleaks(statusLine, writer, smClient); } else { writer.println(smClient.getString("managerServlet.unknownCommand", command)); } // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
Override public void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null) command = request.getServletPath(); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } String tag = request.getParameter("tag"); boolean update = false; if ((request.getParameter("update") != null) && (request.getParameter("update").equals("true"))) { update = true; } // Prepare our output writer to generate the response message response.setContentType("text/plain;charset="+Constants.CHARSET); PrintWriter writer = response.getWriter(); // Process the requested command if (command == null) { writer.println(smClient.getString("managerServlet.noCommand")); } else if (command.equals("/deploy")) { deploy(writer, cn, tag, update, request, smClient); } else { writer.println(smClient.getString("managerServlet.unknownCommand", command)); } // Finish up the response writer.flush(); writer.close(); }
// in java/org/apache/catalina/manager/ManagerServlet.java
Override public void init() throws ServletException { // Ensure that our ContainerServlet properties have been set if ((wrapper == null) || (context == null)) throw new UnavailableException( sm.getString("managerServlet.noWrapper")); // Set our properties from the initialization parameters String value = null; try { value = getServletConfig().getInitParameter("debug"); debug = Integer.parseInt(value); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } // Acquire global JNDI resources if available Server server = ((Engine)host.getParent()).getService().getServer(); if (server != null) { global = server.getGlobalNamingContext(); } // Calculate the directory into which we will be deploying applications versioned = (File) getServletContext().getAttribute (ServletContext.TEMPDIR); // Identify the appBase of the owning Host of this Context // (if any) deployed = ((Host) context.getParent()).getAppBaseFile(); configBase = new File(context.getCatalinaBase(), "conf"); Container container = context; Container host = null; Container engine = null; while (container != null) { if (container instanceof Host) host = container; if (container instanceof Engine) engine = container; container = container.getParent(); } if (engine != null) { configBase = new File(configBase, engine.getName()); } if (host != null) { configBase = new File(configBase, host.getName()); } // Note: The directory must exist for this to work. // Log debugging messages as necessary if (debug >= 1) { log("init: Associated with Deployer '" + oname + "'"); if (global != null) { log("init: Global resources are available"); } } }
// in java/org/apache/catalina/valves/RequestFilterValve.java
protected void process(String property, Request request, Response response) throws IOException, ServletException { if (isAllowed(property)) { getNext().invoke(request, response); return; } // Deny this request denyRequest(request, response); }
// in java/org/apache/catalina/valves/RequestFilterValve.java
protected void denyRequest(Request request, Response response) throws IOException, ServletException { response.sendError(denyStatus); }
// in java/org/apache/catalina/valves/RemoteHostValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { process(request.getRequest().getRemoteHost(), request, response); }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { // Perform the request getNext().invoke(request, response); if (request.isComet() && !response.isClosed()) { // Start tracking this connection, since this is a // begin event, and Comet mode is on HttpSession session = request.getSession(true); // Track the connection for webapp reload cometRequests.add(request); // Track the connection for session expiration synchronized (session) { Request[] requests = (Request[]) session.getAttribute(cometRequestsAttribute); if (requests == null) { requests = new Request[1]; requests[0] = request; session.setAttribute(cometRequestsAttribute, requests); } else { Request[] newRequests = new Request[requests.length + 1]; for (int i = 0; i < requests.length; i++) { newRequests[i] = requests[i]; } newRequests[requests.length] = request; session.setAttribute(cometRequestsAttribute, newRequests); } } } }
// in java/org/apache/catalina/valves/CometConnectionManagerValve.java
Override public void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Perform the request boolean ok = false; try { getNext().event(request, response, event); ok = true; } finally { if (!ok || response.isClosed() || (event.getEventType() == CometEvent.EventType.END) || (event.getEventType() == CometEvent.EventType.ERROR && !(event.getEventSubType() == CometEvent.EventSubType.TIMEOUT))) { // Remove the connection from webapp reload tracking cometRequests.remove(request); // Remove connection from session expiration tracking // Note: can't get the session if it has been invalidated but // OK since session listener will have done clean-up HttpSession session = request.getSession(false); if (session != null) { synchronized (session) { Request[] reqs = null; try { reqs = (Request[]) session.getAttribute(cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } if (reqs != null) { boolean found = false; for (int i = 0; !found && (i < reqs.length); i++) { found = (reqs[i] == request); } if (found) { if (reqs.length > 1) { Request[] newConnectionInfos = new Request[reqs.length - 1]; int pos = 0; for (int i = 0; i < reqs.length; i++) { if (reqs[i] != request) { newConnectionInfos[pos++] = reqs[i]; } } try { session.setAttribute( cometRequestsAttribute, newConnectionInfos); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } else { try { session.removeAttribute( cometRequestsAttribute); } catch (IllegalStateException ise) { // Ignore - session has been invalidated // Listener will have cleaned up } } } } } } } } }
// in java/org/apache/catalina/valves/CrawlerSessionManagerValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { boolean isBot = false; String sessionId = null; String clientIp = null; if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": ClientIp=" + request.getRemoteAddr() + ", RequestedSessionId=" + request.getRequestedSessionId()); } // If the incoming request has a valid session ID, no action is required if (request.getSession(false) == null) { // Is this a crawler - check the UA headers Enumeration<String> uaHeaders = request.getHeaders("user-agent"); String uaHeader = null; if (uaHeaders.hasMoreElements()) { uaHeader = uaHeaders.nextElement(); } // If more than one UA header - assume not a bot if (uaHeader != null && !uaHeaders.hasMoreElements()) { if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": UserAgent=" + uaHeader); } if (uaPattern.matcher(uaHeader).matches()) { isBot = true; if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": Bot found. UserAgent=" + uaHeader); } } } // If this is a bot, is the session ID known? if (isBot) { clientIp = request.getRemoteAddr(); sessionId = clientIpSessionId.get(clientIp); if (sessionId != null) { request.setRequestedSessionId(sessionId); if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": SessionID=" + sessionId); } } } } getNext().invoke(request, response); if (isBot) { if (sessionId == null) { // Has bot just created a session, if so make a note of it HttpSession s = request.getSession(false); if (s != null) { clientIpSessionId.put(clientIp, s.getId()); sessionIdClientIp.put(s.getId(), clientIp); // #valueUnbound() will be called on session expiration s.setAttribute(this.getClass().getName(), this); s.setMaxInactiveInterval(sessionInactiveInterval); if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": New bot session. SessionID=" + s.getId()); } } } else { if (log.isDebugEnabled()) { log.debug(request.hashCode() + ": Bot session accessed. SessionID=" + sessionId); } } } }
// in java/org/apache/catalina/valves/RemoteAddrValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { process(request.getRequest().getRemoteAddr(), request, response); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { getNext().invoke(request, response); }
// in java/org/apache/catalina/valves/StuckThreadDetectionValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (threshold <= 0) { // short-circuit if not monitoring stuck threads getNext().invoke(request, response); return; } // Save the thread/runnable // Keeping a reference to the thread object here does not prevent // GC'ing, as the reference is removed from the Map in the finally clause Long key = Long.valueOf(Thread.currentThread().getId()); StringBuffer requestUrl = request.getRequestURL(); if(request.getQueryString()!=null) { requestUrl.append("?"); requestUrl.append(request.getQueryString()); } MonitoredThread monitoredThread = new MonitoredThread(Thread.currentThread(), requestUrl.toString()); activeThreads.put(key, monitoredThread); try { getNext().invoke(request, response); } finally { activeThreads.remove(key); if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) { completedStuckThreadsQueue.add( new CompletedStuckThread(monitoredThread.getThread().getName(), monitoredThread.getActiveTimeInMillis())); } } }
// in java/org/apache/catalina/valves/SSLValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { /* mod_header converts the '\n' into ' ' so we have to rebuild the client certificate */ String strcert0 = mygetHeader(request, "ssl_client_cert"); if (strcert0 != null && strcert0.length()>28) { String strcert1 = strcert0.replace(' ', '\n'); String strcert2 = strcert1.substring(28, strcert1.length()-26); String strcert3 = "-----BEGIN CERTIFICATE-----\n"; String strcert4 = strcert3.concat(strcert2); String strcerts = strcert4.concat("\n-----END CERTIFICATE-----\n"); // ByteArrayInputStream bais = new ByteArrayInputStream(strcerts.getBytes("UTF-8")); ByteArrayInputStream bais = new ByteArrayInputStream( strcerts.getBytes(B2CConverter.ISO_8859_1)); X509Certificate jsseCerts[] = null; String providerName = (String) request.getConnector().getProperty( "clientCertProvider"); try { CertificateFactory cf; if (providerName == null) { cf = CertificateFactory.getInstance("X.509"); } else { cf = CertificateFactory.getInstance("X.509", providerName); } X509Certificate cert = (X509Certificate) cf.generateCertificate(bais); jsseCerts = new X509Certificate[1]; jsseCerts[0] = cert; } catch (java.security.cert.CertificateException e) { log.warn(sm.getString("sslValve.certError", strcerts), e); } catch (NoSuchProviderException e) { log.error(sm.getString( "sslValve.invalidProvider", providerName), e); } request.setAttribute(Globals.CERTIFICATES_ATTR, jsseCerts); } strcert0 = mygetHeader(request, "ssl_cipher"); if (strcert0 != null) { request.setAttribute(Globals.CIPHER_SUITE_ATTR, strcert0); } strcert0 = mygetHeader(request, "ssl_session_id"); if (strcert0 != null) { request.setAttribute(Globals.SSL_SESSION_ID_ATTR, strcert0); } strcert0 = mygetHeader(request, "ssl_cipher_usekeysize"); if (strcert0 != null) { request.setAttribute(Globals.KEY_SIZE_ATTR, Integer.valueOf(strcert0)); } getNext().invoke(request, response); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { // Perform the request getNext().invoke(request, response); if (response.isCommitted()) { return; } Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); if (request.isAsyncStarted() && response.getStatus() < 400 && throwable == null) { return; } if (throwable != null) { // The response is an error response.setError(); // Reset the response (if possible) try { response.reset(); } catch (IllegalStateException e) { // Ignore } response.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } response.setSuspended(false); try { report(request, response, throwable); } catch (Throwable tt) { ExceptionUtils.handleThrowable(tt); } if (request.isAsyncStarted()) { request.getAsyncContext().complete(); } }
// in java/org/apache/catalina/valves/SemaphoreValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (controlConcurrency(request, response)) { boolean shouldRelease = true; try { if (block) { if (interruptible) { try { semaphore.acquire(); } catch (InterruptedException e) { shouldRelease = false; permitDenied(request, response); return; } } else { semaphore.acquireUninterruptibly(); } } else { if (!semaphore.tryAcquire()) { shouldRelease = false; permitDenied(request, response); return; } } getNext().invoke(request, response); } finally { if (shouldRelease) { semaphore.release(); } } } else { getNext().invoke(request, response); } }
// in java/org/apache/catalina/valves/SemaphoreValve.java
public void permitDenied(Request request, Response response) throws IOException, ServletException { // NO-OP by default }
// in java/org/apache/catalina/valves/PersistentValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { // Select the Context to be used for this Request Context context = request.getContext(); if (context == null) { response.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, sm.getString("standardHost.noContext")); return; } // Bind the context CL to the current thread Thread.currentThread().setContextClassLoader (context.getLoader().getClassLoader()); // Update the session last access time for our session (if any) String sessionId = request.getRequestedSessionId(); Manager manager = context.getManager(); if (sessionId != null && manager != null) { if (manager instanceof StoreManager) { Store store = ((StoreManager) manager).getStore(); if (store != null) { Session session = null; try { session = store.load(sessionId); } catch (Exception e) { container.getLogger().error("deserializeError"); } if (session != null) { if (!session.isValid() || isSessionStale(session, System.currentTimeMillis())) { if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("session swapped in is invalid or expired"); } session.expire(); store.remove(sessionId); } else { session.setManager(manager); // session.setId(sessionId); Only if new ??? manager.add(session); // ((StandardSession)session).activate(); session.access(); session.endAccess(); } } } } } if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("sessionId: " + sessionId); } // Ask the next valve to process the request. getNext().invoke(request, response); // If still processing async, don't try to store the session // TODO: Are there some async states where it is would be safe to store // the session? if (!request.isAsync()) { // Read the sessionid after the response. // HttpSession hsess = hreq.getSession(false); Session hsess; try { hsess = request.getSessionInternal(); } catch (Exception ex) { hsess = null; } String newsessionId = null; if (hsess!=null) { newsessionId = hsess.getIdInternal(); } if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("newsessionId: " + newsessionId); } if (newsessionId!=null) { /* store the session and remove it from the manager */ if (manager instanceof StoreManager) { Session session = manager.findSession(newsessionId); Store store = ((StoreManager) manager).getStore(); if (store != null && session!=null && session.isValid() && !isSessionStale(session, System.currentTimeMillis())) { // ((StandardSession)session).passivate(); store.save(session); ((StoreManager) manager).removeSuper(session); session.recycle(); } else { if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("newsessionId store: " + store + " session: " + session + " valid: " + (session == null ? "N/A" : Boolean.toString( session.isValid())) + " stale: " + isSessionStale(session, System.currentTimeMillis())); } } } else { if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("newsessionId Manager: " + manager); } } } } }
// in java/org/apache/catalina/valves/AccessLogValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { getNext().invoke(request, response); }
// in java/org/apache/catalina/valves/RemoteIpValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { final String originalRemoteAddr = request.getRemoteAddr(); final String originalRemoteHost = request.getRemoteHost(); final String originalScheme = request.getScheme(); final boolean originalSecure = request.isSecure(); final int originalServerPort = request.getServerPort(); if (internalProxies !=null && internalProxies.matcher(originalRemoteAddr).matches()) { String remoteIp = null; // In java 6, proxiesHeaderValue should be declared as a java.util.Deque LinkedList<String> proxiesHeaderValue = new LinkedList<String>(); StringBuilder concatRemoteIpHeaderValue = new StringBuilder(); for (Enumeration<String> e = request.getHeaders(remoteIpHeader); e.hasMoreElements();) { if (concatRemoteIpHeaderValue.length() > 0) { concatRemoteIpHeaderValue.append(", "); } concatRemoteIpHeaderValue.append(e.nextElement()); } String[] remoteIpHeaderValue = commaDelimitedListToStringArray(concatRemoteIpHeaderValue.toString()); int idx; // loop on remoteIpHeaderValue to find the first trusted remote ip and to build the proxies chain for (idx = remoteIpHeaderValue.length - 1; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; remoteIp = currentRemoteIp; if (internalProxies.matcher(currentRemoteIp).matches()) { // do nothing, internalProxies IPs are not appended to the } else if (trustedProxies != null && trustedProxies.matcher(currentRemoteIp).matches()) { proxiesHeaderValue.addFirst(currentRemoteIp); } else { idx--; // decrement idx because break statement doesn't do it break; } } // continue to loop on remoteIpHeaderValue to build the new value of the remoteIpHeader LinkedList<String> newRemoteIpHeaderValue = new LinkedList<String>(); for (; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; newRemoteIpHeaderValue.addFirst(currentRemoteIp); } if (remoteIp != null) { request.setRemoteAddr(remoteIp); request.setRemoteHost(remoteIp); // use request.coyoteRequest.mimeHeaders.setValue(str).setString(str) because request.addHeader(str, str) is no-op in Tomcat // 6.0 if (proxiesHeaderValue.size() == 0) { request.getCoyoteRequest().getMimeHeaders().removeHeader(proxiesHeader); } else { String commaDelimitedListOfProxies = listToCommaDelimitedString(proxiesHeaderValue); request.getCoyoteRequest().getMimeHeaders().setValue(proxiesHeader).setString(commaDelimitedListOfProxies); } if (newRemoteIpHeaderValue.size() == 0) { request.getCoyoteRequest().getMimeHeaders().removeHeader(remoteIpHeader); } else { String commaDelimitedRemoteIpHeaderValue = listToCommaDelimitedString(newRemoteIpHeaderValue); request.getCoyoteRequest().getMimeHeaders().setValue(remoteIpHeader).setString(commaDelimitedRemoteIpHeaderValue); } } if (protocolHeader != null) { String protocolHeaderValue = request.getHeader(protocolHeader); if (protocolHeaderValue == null) { // don't modify the secure,scheme and serverPort attributes // of the request } else if (protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue)) { request.setSecure(true); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString("https"); setPorts(request, httpsServerPort); } else { request.setSecure(false); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString("http"); setPorts(request, httpServerPort); } } if (log.isDebugEnabled()) { log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr '" + originalRemoteAddr + "', originalRemoteHost='" + originalRemoteHost + "', originalSecure='" + originalSecure + "', originalScheme='" + originalScheme + "' will be seen as newRemoteAddr='" + request.getRemoteAddr() + "', newRemoteHost='" + request.getRemoteHost() + "', newScheme='" + request.getScheme() + "', newSecure='" + request.isSecure() + "'"); } } else { if (log.isDebugEnabled()) { log.debug("Skip RemoteIpValve for request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "'"); } } if (requestAttributesEnabled) { request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE, request.getRemoteAddr()); request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE, request.getRemoteHost()); request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE, request.getProtocol()); request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE, Integer.valueOf(request.getServerPort())); } try { getNext().invoke(request, response); } finally { request.setRemoteAddr(originalRemoteAddr); request.setRemoteHost(originalRemoteHost); request.setSecure(originalSecure); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString(originalScheme); request.setServerPort(originalServerPort); } }
// in java/org/apache/catalina/valves/ValveBase.java
Override public void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Perform the request getNext().event(request, response, event); }
// in java/org/apache/catalina/authenticator/SingleSignOn.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { request.removeNote(Constants.REQ_SSOID_NOTE); // Has a valid user already been authenticated? if (containerLog.isDebugEnabled()) { containerLog.debug("Process request for '" + request.getRequestURI() + "'"); } if (request.getUserPrincipal() != null) { if (containerLog.isDebugEnabled()) { containerLog.debug(" Principal '" + request.getUserPrincipal().getName() + "' has already been authenticated"); } getNext().invoke(request, response); return; } // Check for the single sign on cookie if (containerLog.isDebugEnabled()) { containerLog.debug(" Checking for SSO cookie"); } Cookie cookie = null; Cookie cookies[] = request.getCookies(); if (cookies == null) { cookies = new Cookie[0]; } for (int i = 0; i < cookies.length; i++) { if (Constants.SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) { cookie = cookies[i]; break; } } if (cookie == null) { if (containerLog.isDebugEnabled()) { containerLog.debug(" SSO cookie is not present"); } getNext().invoke(request, response); return; } // Look up the cached Principal associated with this cookie value if (containerLog.isDebugEnabled()) { containerLog.debug(" Checking for cached principal for " + cookie.getValue()); } SingleSignOnEntry entry = lookup(cookie.getValue()); if (entry != null) { if (containerLog.isDebugEnabled()) { containerLog.debug(" Found cached principal '" + (entry.getPrincipal() != null ? entry.getPrincipal().getName() : "") + "' with auth type '" + entry.getAuthType() + "'"); } request.setNote(Constants.REQ_SSOID_NOTE, cookie.getValue()); // Only set security elements if reauthentication is not required if (!getRequireReauthentication()) { request.setAuthType(entry.getAuthType()); request.setUserPrincipal(entry.getPrincipal()); } } else { if (containerLog.isDebugEnabled()) { containerLog.debug(" No cached principal found, erasing SSO cookie"); } cookie.setMaxAge(0); response.addCookie(cookie); } // Invoke the next Valve in our pipeline getNext().invoke(request, response); }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (log.isDebugEnabled()) { log.debug("Security checking request " + request.getMethod() + " " + request.getRequestURI()); } // Have we got a cached authenticated Principal to record? if (cache) { Principal principal = request.getUserPrincipal(); if (principal == null) { Session session = request.getSessionInternal(false); if (session != null) { principal = session.getPrincipal(); if (principal != null) { if (log.isDebugEnabled()) { log.debug("We have cached auth type " + session.getAuthType() + " for principal " + session.getPrincipal()); } request.setAuthType(session.getAuthType()); request.setUserPrincipal(principal); } } } } // Special handling for form-based logins to deal with the case // where the login form (and therefore the "j_security_check" URI // to which it submits) might be outside the secured area String contextPath = this.context.getPath(); String requestURI = request.getDecodedRequestURI(); if (requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION)) { if (!authenticate(request, response)) { if (log.isDebugEnabled()) { log.debug(" Failed authenticate() test ??" + requestURI ); } return; } } // The Servlet may specify security constraints through annotations. // Ensure that they have been processed before constraints are checked Wrapper wrapper = (Wrapper) request.getMappingData().wrapper; if (wrapper != null) { wrapper.servletSecurityAnnotationScan(); } Realm realm = this.context.getRealm(); // Is this request URI subject to a security constraint? SecurityConstraint [] constraints = realm.findSecurityConstraints(request, this.context); if (constraints == null && !context.getPreemptiveAuthentication()) { if (log.isDebugEnabled()) { log.debug(" Not subject to any constraint"); } getNext().invoke(request, response); return; } // Make sure that constrained resources are not cached by web proxies // or browsers as caching can provide a security hole if (constraints != null && disableProxyCaching && !"POST".equalsIgnoreCase(request.getMethod())) { if (securePagesWithPragma) { // Note: These can cause problems with downloading files with IE response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); } else { response.setHeader("Cache-Control", "private"); } response.setHeader("Expires", DATE_ONE); } int i; if (constraints != null) { // Enforce any user data constraint for this security constraint if (log.isDebugEnabled()) { log.debug(" Calling hasUserDataPermission()"); } if (!realm.hasUserDataPermission(request, response, constraints)) { if (log.isDebugEnabled()) { log.debug(" Failed hasUserDataPermission() test"); } /* * ASSERT: Authenticator already set the appropriate * HTTP status code, so we do not have to do anything special */ return; } } // Since authenticate modifies the response on failure, // we have to check for allow-from-all first. boolean authRequired; if (constraints == null) { authRequired = false; } else { authRequired = true; for(i=0; i < constraints.length && authRequired; i++) { if(!constraints[i].getAuthConstraint()) { authRequired = false; } else if(!constraints[i].getAllRoles()) { String [] roles = constraints[i].findAuthRoles(); if(roles == null || roles.length == 0) { authRequired = false; } } } } if (!authRequired && context.getPreemptiveAuthentication()) { authRequired = request.getCoyoteRequest().getMimeHeaders().getValue( "authorization") != null; } if (!authRequired && context.getPreemptiveAuthentication()) { X509Certificate[] certs = (X509Certificate[]) request.getAttribute( Globals.CERTIFICATES_ATTR); authRequired = certs != null && certs.length > 0; } if(authRequired) { if (log.isDebugEnabled()) { log.debug(" Calling authenticate()"); } if (!authenticate(request, response)) { if (log.isDebugEnabled()) { log.debug(" Failed authenticate() test"); } /* * ASSERT: Authenticator already set the appropriate * HTTP status code, so we do not have to do anything * special */ return; } } if (constraints != null) { if (log.isDebugEnabled()) { log.debug(" Calling accessControl()"); } if (!realm.hasResourcePermission(request, response, constraints, this.context)) { if (log.isDebugEnabled()) { log.debug(" Failed accessControl() test"); } /* * ASSERT: AccessControl method has already set the * appropriate HTTP status code, so we do not have to do * anything special */ return; } } // Any and all specified constraints have been satisfied if (log.isDebugEnabled()) { log.debug(" Successfully passed all security constraints"); } getNext().invoke(request, response); }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
Override public void login(String username, String password, Request request) throws ServletException { Principal principal = doLogin(request, username, password); register(request, request.getResponse(), principal, getAuthMethod(), username, password); }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
protected Principal doLogin(Request request, String username, String password) throws ServletException { Principal p = context.getRealm().authenticate(username, password); if (p == null) { throw new ServletException(sm.getString("authenticator.loginFail")); } return p; }
// in java/org/apache/catalina/authenticator/AuthenticatorBase.java
Override public void logout(Request request) throws ServletException { register(request, request.getResponse(), null, null, null, null); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override public void init() throws ServletException { if (getServletConfig().getInitParameter("debug") != null) debug = Integer.parseInt(getServletConfig().getInitParameter("debug")); if (getServletConfig().getInitParameter("input") != null) input = Integer.parseInt(getServletConfig().getInitParameter("input")); if (getServletConfig().getInitParameter("output") != null) output = Integer.parseInt(getServletConfig().getInitParameter("output")); listings = Boolean.parseBoolean(getServletConfig().getInitParameter("listings")); if (getServletConfig().getInitParameter("readonly") != null) readOnly = Boolean.parseBoolean(getServletConfig().getInitParameter("readonly")); if (getServletConfig().getInitParameter("sendfileSize") != null) sendfileSize = Integer.parseInt(getServletConfig().getInitParameter("sendfileSize")) * 1024; fileEncoding = getServletConfig().getInitParameter("fileEncoding"); globalXsltFile = getServletConfig().getInitParameter("globalXsltFile"); contextXsltFile = getServletConfig().getInitParameter("contextXsltFile"); localXsltFile = getServletConfig().getInitParameter("localXsltFile"); readmeFile = getServletConfig().getInitParameter("readmeFile"); if (getServletConfig().getInitParameter("useAcceptRanges") != null) useAcceptRanges = Boolean.parseBoolean(getServletConfig().getInitParameter("useAcceptRanges")); // Sanity check on the specified buffer sizes if (input < 256) input = 256; if (output < 256) output = 256; if (debug > 0) { log("DefaultServlet.init: input buffer size=" + input + ", output buffer size=" + output); } // Load the proxy dir context. resources = (ProxyDirContext) getServletContext() .getAttribute(Globals.RESOURCES_ATTR); if (resources == null) { try { resources = (ProxyDirContext) new InitialContext() .lookup(RESOURCES_JNDI_NAME); } catch (NamingException e) { // Failed throw new ServletException("No resources", e); } } if (resources == null) { throw new UnavailableException("No resources"); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Serve the requested resource, including the data content serveResource(request, response, true); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doHead(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Serve the requested resource, without the data content serveResource(request, response, false); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { StringBuilder allow = new StringBuilder(); // There is a doGet method allow.append("GET, HEAD"); // There is a doPost allow.append(", POST"); // There is a doPut allow.append(", PUT"); // There is a doDelete allow.append(", DELETE"); // Trace - assume disabled unless we can prove otherwise if (req instanceof RequestFacade && ((RequestFacade) req).getAllowTrace()) { allow.append(", TRACE"); } // Always allow options allow.append(", OPTIONS"); resp.setHeader("Allow", allow.toString()); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String path = getRelativePath(req); boolean exists = true; try { resources.lookup(path); } catch (NamingException e) { exists = false; } boolean result = true; // Temp. content file used to support partial PUT File contentFile = null; Range range = parseContentRange(req, resp); InputStream resourceInputStream = null; // Append data specified in ranges to existing content for this // resource - create a temp. file on the local filesystem to // perform this operation // Assume just one range is specified for now if (range != null) { contentFile = executePartialPut(req, range, path); resourceInputStream = new FileInputStream(contentFile); } else { resourceInputStream = req.getInputStream(); } try { Resource newResource = new Resource(resourceInputStream); // FIXME: Add attributes if (exists) { resources.rebind(path, newResource); } else { resources.bind(path, newResource); } } catch(NamingException e) { result = false; } if (result) { if (exists) { resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { resp.setStatus(HttpServletResponse.SC_CREATED); } } else { resp.sendError(HttpServletResponse.SC_CONFLICT); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String path = getRelativePath(req); boolean exists = true; try { resources.lookup(path); } catch (NamingException e) { exists = false; } if (exists) { boolean result = true; try { resources.unbind(path); } catch (NamingException e) { result = false; } if (result) { resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException { boolean serveContent = content; // Identify the requested resource path String path = getRelativePath(request); if (debug > 0) { if (serveContent) log("DefaultServlet.serveResource: Serving resource '" + path + "' headers and data"); else log("DefaultServlet.serveResource: Serving resource '" + path + "' headers only"); } CacheEntry cacheEntry = resources.lookupCache(path); if (!cacheEntry.exists) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } else { // We're included // SRV.9.3 says we must throw a FNFE throw new FileNotFoundException( sm.getString("defaultServlet.missingResource", requestUri)); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } // If the resource is not a collection, and the resource path // ends with "/" or "\", return NOT FOUND if (cacheEntry.context == null) { if (path.endsWith("/") || (path.endsWith("\\"))) { // Check if we're included so we can return the appropriate // missing resource name in the error String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { requestUri = request.getRequestURI(); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); return; } } boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST; // Check if the conditions specified in the optional If headers are // satisfied. if (cacheEntry.context == null) { // Checking If headers boolean included = (request.getAttribute( RequestDispatcher.INCLUDE_CONTEXT_PATH) != null); if (!included && !isError && !checkIfHeaders(request, response, cacheEntry.attributes)) { return; } } // Find content type. String contentType = cacheEntry.attributes.getMimeType(); if (contentType == null) { contentType = getServletContext().getMimeType(cacheEntry.name); cacheEntry.attributes.setMimeType(contentType); } ArrayList<Range> ranges = null; long contentLength = -1L; if (cacheEntry.context != null) { // Skip directory listings if we have been configured to // suppress them if (!listings) { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); return; } contentType = "text/html;charset=UTF-8"; } else { if (!isError) { if (useAcceptRanges) { // Accept ranges header response.setHeader("Accept-Ranges", "bytes"); } // Parse range specifier ranges = parseRange(request, response, cacheEntry.attributes); // ETag header response.setHeader("ETag", cacheEntry.attributes.getETag()); // Last-Modified header response.setHeader("Last-Modified", cacheEntry.attributes.getLastModifiedHttp()); } // Get content length contentLength = cacheEntry.attributes.getContentLength(); // Special case for zero length files, which would cause a // (silent) ISE when setting the output buffer size if (contentLength == 0L) { serveContent = false; } } ServletOutputStream ostream = null; PrintWriter writer = null; if (serveContent) { // Trying to retrieve the servlet output stream try { ostream = response.getOutputStream(); } catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if ( (contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")) ) { writer = response.getWriter(); // Cannot reliably serve partial content with a Writer ranges = FULL; } else { throw e; } } } // Check to see if a Filter, Valve of wrapper has written some content. // If it has, disable range requests and setting of a content length // since neither can be done reliably. ServletResponse r = response; long contentWritten = 0; while (r instanceof ServletResponseWrapper) { r = ((ServletResponseWrapper) r).getResponse(); } if (r instanceof ResponseFacade) { contentWritten = ((ResponseFacade) r).getContentWritten(); } if (contentWritten > 0) { ranges = FULL; } if ( (cacheEntry.context != null) || isError || ( ((ranges == null) || (ranges.isEmpty())) && (request.getHeader("Range") == null) ) || (ranges == FULL) ) { // Set the appropriate output headers if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if ((cacheEntry.resource != null) && (contentLength >= 0) && (!serveContent || ostream != null)) { if (debug > 0) log("DefaultServlet.serveFile: contentLength=" + contentLength); // Don't set a content length if something else has already // written to the response. if (contentWritten == 0) { if (contentLength < Integer.MAX_VALUE) { response.setContentLength((int) contentLength); } else { // Set the content-length as String to be able to use a // long response.setHeader("content-length", "" + contentLength); } } } InputStream renderResult = null; if (cacheEntry.context != null) { if (serveContent) { // Serve the directory browser renderResult = render(getPathPrefix(request), cacheEntry); } } // Copy the input stream to our output stream (if requested) if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, contentLength, null)) copy(cacheEntry, renderResult, ostream); } else { copy(cacheEntry, renderResult, writer); } } } else { if ((ranges == null) || (ranges.isEmpty())) return; // Partial content response. response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); if (ranges.size() == 1) { Range range = ranges.get(0); response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; if (length < Integer.MAX_VALUE) { response.setContentLength((int) length); } else { // Set the content-length as String to be able to use a long response.setHeader("content-length", "" + length); } if (contentType != null) { if (debug > 0) log("DefaultServlet.serveFile: contentType='" + contentType + "'"); response.setContentType(contentType); } if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { if (!checkSendfile(request, response, cacheEntry, range.end - range.start + 1, range)) copy(cacheEntry, ostream, range); } else { // we should not get here throw new IllegalStateException(); } } } else { response.setContentType("multipart/byteranges; boundary=" + mimeSeparation); if (serveContent) { try { response.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } if (ostream != null) { copy(cacheEntry, ostream, ranges.iterator(), contentType); } else { // we should not get here throw new IllegalStateException(); } } } } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream render(String contextPath, CacheEntry cacheEntry) throws IOException, ServletException { InputStream xsltInputStream = findXsltInputStream(cacheEntry.context); if (xsltInputStream==null) { return renderHtml(contextPath, cacheEntry); } return renderXml(contextPath, cacheEntry, xsltInputStream); }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream renderXml(String contextPath, CacheEntry cacheEntry, InputStream xsltInputStream) throws IOException, ServletException { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<listing "); sb.append(" contextPath='"); sb.append(contextPath); sb.append("'"); sb.append(" directory='"); sb.append(cacheEntry.name); sb.append("' "); sb.append(" hasParent='").append(!cacheEntry.name.equals("/")); sb.append("'>"); sb.append("<entries>"); try { // Render the directory entries within this directory NamingEnumeration<NameClassPair> enumeration = resources.list(cacheEntry.name); // rewriteUrl(contextPath) is expensive. cache result for later reuse String rewrittenContextPath = rewriteUrl(contextPath); while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String resourceName = ncPair.getName(); String trimmed = resourceName/*.substring(trim)*/; if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF") || trimmed.equalsIgnoreCase(localXsltFile)) continue; if ((cacheEntry.name + trimmed).equals(contextXsltFile)) continue; CacheEntry childCacheEntry = resources.lookupCache(cacheEntry.name + resourceName); if (!childCacheEntry.exists) { continue; } sb.append("<entry"); sb.append(" type='") .append((childCacheEntry.context != null)?"dir":"file") .append("'"); sb.append(" urlPath='") .append(rewrittenContextPath) .append(rewriteUrl(cacheEntry.name + resourceName)) .append((childCacheEntry.context != null)?"/":"") .append("'"); if (childCacheEntry.resource != null) { sb.append(" size='") .append(renderSize(childCacheEntry.attributes.getContentLength())) .append("'"); } sb.append(" date='") .append(childCacheEntry.attributes.getLastModifiedHttp()) .append("'"); sb.append(">"); sb.append(RequestUtil.filter(trimmed)); if (childCacheEntry.context != null) sb.append("/"); sb.append("</entry>"); } } catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); } sb.append("</entries>"); String readme = getReadme(cacheEntry.context); if (readme!=null) { sb.append("<readme><![CDATA["); sb.append(readme); sb.append("]]></readme>"); } sb.append("</listing>"); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Source xmlSource = new StreamSource(new StringReader(sb.toString())); Source xslSource = new StreamSource(xsltInputStream); Transformer transformer = tFactory.newTransformer(xslSource); ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8"); StreamResult out = new StreamResult(osWriter); transformer.transform(xmlSource, out); osWriter.flush(); return (new ByteArrayInputStream(stream.toByteArray())); } catch (TransformerException e) { throw new ServletException("XSL transformer error", e); } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
protected InputStream renderHtml(String contextPath, CacheEntry cacheEntry) throws IOException, ServletException { String name = cacheEntry.name; // Prepare a writer to a buffered area ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8"); PrintWriter writer = new PrintWriter(osWriter); StringBuilder sb = new StringBuilder(); // rewriteUrl(contextPath) is expensive. cache result for later reuse String rewrittenContextPath = rewriteUrl(contextPath); // Render the page header sb.append("<html>\r\n"); sb.append("<head>\r\n"); sb.append("<title>"); sb.append(sm.getString("directory.title", name)); sb.append("</title>\r\n"); sb.append("<STYLE><!--"); sb.append(org.apache.catalina.util.TomcatCSS.TOMCAT_CSS); sb.append("--></STYLE> "); sb.append("</head>\r\n"); sb.append("<body>"); sb.append("<h1>"); sb.append(sm.getString("directory.title", name)); // Render the link to our parent (if required) String parentDirectory = name; if (parentDirectory.endsWith("/")) { parentDirectory = parentDirectory.substring(0, parentDirectory.length() - 1); } int slash = parentDirectory.lastIndexOf('/'); if (slash >= 0) { String parent = name.substring(0, slash); sb.append(" - <a href=\""); sb.append(rewrittenContextPath); if (parent.equals("")) parent = "/"; sb.append(rewriteUrl(parent)); if (!parent.endsWith("/")) sb.append("/"); sb.append("\">"); sb.append("<b>"); sb.append(sm.getString("directory.parent", parent)); sb.append("</b>"); sb.append("</a>"); } sb.append("</h1>"); sb.append("<HR size=\"1\" noshade=\"noshade\">"); sb.append("<table width=\"100%\" cellspacing=\"0\"" + " cellpadding=\"5\" align=\"center\">\r\n"); // Render the column headings sb.append("<tr>\r\n"); sb.append("<td align=\"left\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.filename")); sb.append("</strong></font></td>\r\n"); sb.append("<td align=\"center\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.size")); sb.append("</strong></font></td>\r\n"); sb.append("<td align=\"right\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.lastModified")); sb.append("</strong></font></td>\r\n"); sb.append("</tr>"); try { // Render the directory entries within this directory NamingEnumeration<NameClassPair> enumeration = resources.list(cacheEntry.name); boolean shade = false; while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String resourceName = ncPair.getName(); String trimmed = resourceName/*.substring(trim)*/; if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF")) continue; CacheEntry childCacheEntry = resources.lookupCache(cacheEntry.name + resourceName); if (!childCacheEntry.exists) { continue; } sb.append("<tr"); if (shade) sb.append(" bgcolor=\"#eeeeee\""); sb.append(">\r\n"); shade = !shade; sb.append("<td align=\"left\">&nbsp;&nbsp;\r\n"); sb.append("<a href=\""); sb.append(rewrittenContextPath); resourceName = rewriteUrl(name + resourceName); sb.append(resourceName); if (childCacheEntry.context != null) sb.append("/"); sb.append("\"><tt>"); sb.append(RequestUtil.filter(trimmed)); if (childCacheEntry.context != null) sb.append("/"); sb.append("</tt></a></td>\r\n"); sb.append("<td align=\"right\"><tt>"); if (childCacheEntry.context != null) sb.append("&nbsp;"); else sb.append(renderSize(childCacheEntry.attributes.getContentLength())); sb.append("</tt></td>\r\n"); sb.append("<td align=\"right\"><tt>"); sb.append(childCacheEntry.attributes.getLastModifiedHttp()); sb.append("</tt></td>\r\n"); sb.append("</tr>\r\n"); } } catch (NamingException e) { // Something went wrong throw new ServletException("Error accessing resource", e); } // Render the page footer sb.append("</table>\r\n"); sb.append("<HR size=\"1\" noshade=\"noshade\">"); String readme = getReadme(cacheEntry.context); if (readme!=null) { sb.append(readme); sb.append("<HR size=\"1\" noshade=\"noshade\">"); } sb.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>"); sb.append("</body>\r\n"); sb.append("</html>\r\n"); // Return an input stream to the underlying bytes writer.write(sb.toString()); writer.flush(); return (new ByteArrayInputStream(stream.toByteArray())); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override public void init() throws ServletException { super.init(); if (getServletConfig().getInitParameter("secret") != null) secret = getServletConfig().getInitParameter("secret"); if (getServletConfig().getInitParameter("maxDepth") != null) maxDepth = Integer.parseInt( getServletConfig().getInitParameter("maxDepth")); if (getServletConfig().getInitParameter("allowSpecialPaths") != null) allowSpecialPaths = Boolean.parseBoolean( getServletConfig().getInitParameter("allowSpecialPaths")); // Load the MD5 helper used to calculate signatures. try { md5Helper = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new UnavailableException("No MD5"); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected DocumentBuilder getDocumentBuilder() throws ServletException { DocumentBuilder documentBuilder = null; DocumentBuilderFactory documentBuilderFactory = null; try { documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setExpandEntityReferences(false); documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setEntityResolver( new WebdavResolver(this.getServletContext())); } catch(ParserConfigurationException e) { throw new ServletException (sm.getString("webdavservlet.jaxpfailed")); } return documentBuilder; }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final String path = getRelativePath(req); // Block access to special subdirectories. // DefaultServlet assumes it services resources from the root of the web app // and doesn't add any special path protection // WebdavServlet remounts the webapp under a new path, so this check is // necessary on all methods (including GET). if (isSpecialPath(path)) { resp.sendError(WebdavStatus.SC_NOT_FOUND); return; } final String method = req.getMethod(); if (debug > 0) { log("[" + method + "] " + path); } if (method.equals(METHOD_PROPFIND)) { doPropfind(req, resp); } else if (method.equals(METHOD_PROPPATCH)) { doProppatch(req, resp); } else if (method.equals(METHOD_MKCOL)) { doMkcol(req, resp); } else if (method.equals(METHOD_COPY)) { doCopy(req, resp); } else if (method.equals(METHOD_MOVE)) { doMove(req, resp); } else if (method.equals(METHOD_LOCK)) { doLock(req, resp); } else if (method.equals(METHOD_UNLOCK)) { doUnlock(req, resp); } else { // DefaultServlet processing super.service(req, resp); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("DAV", "1,2"); StringBuilder methodsAllowed = determineMethodsAllowed(resources, req); resp.addHeader("Allow", methodsAllowed.toString()); resp.addHeader("MS-Author-Via", "DAV"); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doPropfind(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (!listings) { // Get allowed methods StringBuilder methodsAllowed = determineMethodsAllowed(resources, req); resp.addHeader("Allow", methodsAllowed.toString()); resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED); return; } String path = getRelativePath(req); if (path.endsWith("/")) path = path.substring(0, path.length() - 1); // Properties which are to be displayed. Vector<String> properties = null; // Propfind depth int depth = maxDepth; // Propfind type int type = FIND_ALL_PROP; String depthStr = req.getHeader("Depth"); if (depthStr == null) { depth = maxDepth; } else { if (depthStr.equals("0")) { depth = 0; } else if (depthStr.equals("1")) { depth = 1; } else if (depthStr.equals("infinity")) { depth = maxDepth; } } Node propNode = null; if (req.getContentLength() > 0) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse (new InputSource(req.getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); NodeList childList = rootElement.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: if (currentNode.getNodeName().endsWith("prop")) { type = FIND_BY_PROPERTY; propNode = currentNode; } if (currentNode.getNodeName().endsWith("propname")) { type = FIND_PROPERTY_NAMES; } if (currentNode.getNodeName().endsWith("allprop")) { type = FIND_ALL_PROP; } break; } } } catch (SAXException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); } catch (IOException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); } } if (type == FIND_BY_PROPERTY) { properties = new Vector<String>(); // propNode must be non-null if type == FIND_BY_PROPERTY @SuppressWarnings("null") NodeList childList = propNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String nodeName = currentNode.getNodeName(); String propertyName = null; if (nodeName.indexOf(':') != -1) { propertyName = nodeName.substring (nodeName.indexOf(':') + 1); } else { propertyName = nodeName; } // href is a live property which is handled differently properties.addElement(propertyName); break; } } } boolean exists = true; Object object = null; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } } if (!exists) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, path); return; } resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); if (depth == 0) { parseProperties(req, generatedXML, path, type, properties); } else { // The stack always contains the object of the current level Stack<String> stack = new Stack<String>(); stack.push(path); // Stack of the objects one level below Stack<String> stackBelow = new Stack<String>(); while ((!stack.isEmpty()) && (depth >= 0)) { String currentPath = stack.pop(); parseProperties(req, generatedXML, currentPath, type, properties); try { object = resources.lookup(currentPath); } catch (NamingException e) { continue; } if ((object instanceof DirContext) && (depth > 0)) { try { NamingEnumeration<NameClassPair> enumeration = resources.list(currentPath); while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String newPath = currentPath; if (!(newPath.endsWith("/"))) newPath += "/"; newPath += ncPair.getName(); stackBelow.push(newPath); } } catch (NamingException e) { resp.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } // Displaying the lock-null resources present in that // collection String lockPath = currentPath; if (lockPath.endsWith("/")) lockPath = lockPath.substring(0, lockPath.length() - 1); Vector<String> currentLockNullResources = lockNullResources.get(lockPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); } } } if (stack.isEmpty()) { depth--; stack = stackBelow; stackBelow = new Stack<String>(); } generatedXML.sendData(); } } generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doMkcol(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } String path = getRelativePath(req); boolean exists = true; try { resources.lookup(path); } catch (NamingException e) { exists = false; } // Can't create a collection if a resource already exists at the given // path if (exists) { // Get allowed methods StringBuilder methodsAllowed = determineMethodsAllowed(resources, req); resp.addHeader("Allow", methodsAllowed.toString()); resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED); return; } if (req.getContentLength() > 0) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { // Document document = documentBuilder.parse(new InputSource(req.getInputStream())); // TODO : Process this request body resp.sendError(WebdavStatus.SC_NOT_IMPLEMENTED); return; } catch(SAXException saxe) { // Parse error - assume invalid content resp.sendError(WebdavStatus.SC_UNSUPPORTED_MEDIA_TYPE); return; } } boolean result = true; try { resources.createSubcontext(path); } catch (NamingException e) { result = false; } if (!result) { resp.sendError(WebdavStatus.SC_CONFLICT, WebdavStatus.getStatusText (WebdavStatus.SC_CONFLICT)); } else { resp.setStatus(WebdavStatus.SC_CREATED); // Removing any lock-null resource which would be present lockNullResources.remove(path); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } deleteResource(req, resp); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } super.doPut(req, resp); String path = getRelativePath(req); // Removing any lock-null resource which would be present lockNullResources.remove(path); }
// in java/org/apache/catalina/servlets/WebdavServlet.java
protected void doLock(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } LockInfo lock = new LockInfo(); // Parsing lock request // Parsing depth header String depthStr = req.getHeader("Depth"); if (depthStr == null) { lock.depth = maxDepth; } else { if (depthStr.equals("0")) { lock.depth = 0; } else { lock.depth = maxDepth; } } // Parsing timeout header int lockDuration = DEFAULT_TIMEOUT; String lockDurationStr = req.getHeader("Timeout"); if (lockDurationStr == null) { lockDuration = DEFAULT_TIMEOUT; } else { int commaPos = lockDurationStr.indexOf(","); // If multiple timeouts, just use the first if (commaPos != -1) { lockDurationStr = lockDurationStr.substring(0,commaPos); } if (lockDurationStr.startsWith("Second-")) { lockDuration = (new Integer(lockDurationStr.substring(7))).intValue(); } else { if (lockDurationStr.equalsIgnoreCase("infinity")) { lockDuration = MAX_TIMEOUT; } else { try { lockDuration = (new Integer(lockDurationStr)).intValue(); } catch (NumberFormatException e) { lockDuration = MAX_TIMEOUT; } } } if (lockDuration == 0) { lockDuration = DEFAULT_TIMEOUT; } if (lockDuration > MAX_TIMEOUT) { lockDuration = MAX_TIMEOUT; } } lock.expiresAt = System.currentTimeMillis() + (lockDuration * 1000); int lockRequestType = LOCK_CREATION; Node lockInfoNode = null; DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse(new InputSource (req.getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); lockInfoNode = rootElement; } catch (IOException e) { lockRequestType = LOCK_REFRESH; } catch (SAXException e) { lockRequestType = LOCK_REFRESH; } if (lockInfoNode != null) { // Reading lock information NodeList childList = lockInfoNode.getChildNodes(); StringWriter strWriter = null; DOMWriter domWriter = null; Node lockScopeNode = null; Node lockTypeNode = null; Node lockOwnerNode = null; for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String nodeName = currentNode.getNodeName(); if (nodeName.endsWith("lockscope")) { lockScopeNode = currentNode; } if (nodeName.endsWith("locktype")) { lockTypeNode = currentNode; } if (nodeName.endsWith("owner")) { lockOwnerNode = currentNode; } break; } } if (lockScopeNode != null) { childList = lockScopeNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String tempScope = currentNode.getNodeName(); if (tempScope.indexOf(':') != -1) { lock.scope = tempScope.substring (tempScope.indexOf(':') + 1); } else { lock.scope = tempScope; } break; } } if (lock.scope == null) { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } } else { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } if (lockTypeNode != null) { childList = lockTypeNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String tempType = currentNode.getNodeName(); if (tempType.indexOf(':') != -1) { lock.type = tempType.substring(tempType.indexOf(':') + 1); } else { lock.type = tempType; } break; } } if (lock.type == null) { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } } else { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } if (lockOwnerNode != null) { childList = lockOwnerNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: lock.owner += currentNode.getNodeValue(); break; case Node.ELEMENT_NODE: strWriter = new StringWriter(); domWriter = new DOMWriter(strWriter, true); domWriter.setQualifiedNames(false); domWriter.print(currentNode); lock.owner += strWriter.toString(); break; } } if (lock.owner == null) { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } } else { lock.owner = ""; } } String path = getRelativePath(req); lock.path = path; boolean exists = true; Object object = null; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; } Enumeration<LockInfo> locksList = null; if (lockRequestType == LOCK_CREATION) { // Generating lock id String lockTokenStr = req.getServletPath() + "-" + lock.type + "-" + lock.scope + "-" + req.getUserPrincipal() + "-" + lock.depth + "-" + lock.owner + "-" + lock.tokens + "-" + lock.expiresAt + "-" + System.currentTimeMillis() + "-" + secret; String lockToken = md5Encoder.encode(md5Helper.digest( lockTokenStr.getBytes(B2CConverter.ISO_8859_1))); if ( (exists) && (object instanceof DirContext) && (lock.depth == maxDepth) ) { // Locking a collection (and all its member resources) // Checking if a child resource of this collection is // already locked Vector<String> lockPaths = new Vector<String>(); locksList = collectionLocks.elements(); while (locksList.hasMoreElements()) { LockInfo currentLock = locksList.nextElement(); if (currentLock.hasExpired()) { resourceLocks.remove(currentLock.path); continue; } if ( (currentLock.path.startsWith(lock.path)) && ((currentLock.isExclusive()) || (lock.isExclusive())) ) { // A child collection of this collection is locked lockPaths.addElement(currentLock.path); } } locksList = resourceLocks.elements(); while (locksList.hasMoreElements()) { LockInfo currentLock = locksList.nextElement(); if (currentLock.hasExpired()) { resourceLocks.remove(currentLock.path); continue; } if ( (currentLock.path.startsWith(lock.path)) && ((currentLock.isExclusive()) || (lock.isExclusive())) ) { // A child resource of this collection is locked lockPaths.addElement(currentLock.path); } } if (!lockPaths.isEmpty()) { // One of the child paths was locked // We generate a multistatus error report Enumeration<String> lockPathsList = lockPaths.elements(); resp.setStatus(WebdavStatus.SC_CONFLICT); XMLWriter generatedXML = new XMLWriter(); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); while (lockPathsList.hasMoreElements()) { generatedXML.writeElement("D", "response", XMLWriter.OPENING); generatedXML.writeElement("D", "href", XMLWriter.OPENING); generatedXML.writeText(lockPathsList.nextElement()); generatedXML.writeElement("D", "href", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML .writeText("HTTP/1.1 " + WebdavStatus.SC_LOCKED + " " + WebdavStatus .getStatusText(WebdavStatus.SC_LOCKED)); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "response", XMLWriter.CLOSING); } generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); Writer writer = resp.getWriter(); writer.write(generatedXML.toString()); writer.close(); return; } boolean addLock = true; // Checking if there is already a shared lock on this path locksList = collectionLocks.elements(); while (locksList.hasMoreElements()) { LockInfo currentLock = locksList.nextElement(); if (currentLock.path.equals(lock.path)) { if (currentLock.isExclusive()) { resp.sendError(WebdavStatus.SC_LOCKED); return; } else { if (lock.isExclusive()) { resp.sendError(WebdavStatus.SC_LOCKED); return; } } currentLock.tokens.addElement(lockToken); lock = currentLock; addLock = false; } } if (addLock) { lock.tokens.addElement(lockToken); collectionLocks.addElement(lock); } } else { // Locking a single resource // Retrieving an already existing lock on that resource LockInfo presentLock = resourceLocks.get(lock.path); if (presentLock != null) { if ((presentLock.isExclusive()) || (lock.isExclusive())) { // If either lock is exclusive, the lock can't be // granted resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED); return; } else { presentLock.tokens.addElement(lockToken); lock = presentLock; } } else { lock.tokens.addElement(lockToken); resourceLocks.put(lock.path, lock); // Checking if a resource exists at this path exists = true; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; } if (!exists) { // "Creating" a lock-null resource int slash = lock.path.lastIndexOf('/'); String parentPath = lock.path.substring(0, slash); Vector<String> lockNulls = lockNullResources.get(parentPath); if (lockNulls == null) { lockNulls = new Vector<String>(); lockNullResources.put(parentPath, lockNulls); } lockNulls.addElement(lock.path); } // Add the Lock-Token header as by RFC 2518 8.10.1 // - only do this for newly created locks resp.addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">"); } } } if (lockRequestType == LOCK_REFRESH) { String ifHeader = req.getHeader("If"); if (ifHeader == null) ifHeader = ""; // Checking resource locks LockInfo toRenew = resourceLocks.get(path); Enumeration<String> tokenList = null; if (toRenew != null) { // At least one of the tokens of the locks must have been given tokenList = toRenew.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (ifHeader.indexOf(token) != -1) { toRenew.expiresAt = lock.expiresAt; lock = toRenew; } } } // Checking inheritable collection locks Enumeration<LockInfo> collectionLocksList = collectionLocks.elements(); while (collectionLocksList.hasMoreElements()) { toRenew = collectionLocksList.nextElement(); if (path.equals(toRenew.path)) { tokenList = toRenew.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (ifHeader.indexOf(token) != -1) { toRenew.expiresAt = lock.expiresAt; lock = toRenew; } } } } } // Set the status, then generate the XML response containing // the lock information XMLWriter generatedXML = new XMLWriter(); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "prop", XMLWriter.OPENING); generatedXML.writeElement("D", "lockdiscovery", XMLWriter.OPENING); lock.toXML(generatedXML); generatedXML.writeElement("D", "lockdiscovery", XMLWriter.CLOSING); generatedXML.writeElement("D", "prop", XMLWriter.CLOSING); resp.setStatus(WebdavStatus.SC_OK); resp.setContentType("text/xml; charset=UTF-8"); Writer writer = resp.getWriter(); writer.write(generatedXML.toString()); writer.close(); }
// in java/org/apache/catalina/servlets/CGIServlet.java
Override public void init(ServletConfig config) throws ServletException { super.init(config); // Set our properties from the initialization parameters if (getServletConfig().getInitParameter("debug") != null) debug = Integer.parseInt(getServletConfig().getInitParameter("debug")); cgiPathPrefix = getServletConfig().getInitParameter("cgiPathPrefix"); boolean passShellEnvironment = Boolean.valueOf(getServletConfig().getInitParameter("passShellEnvironment")).booleanValue(); if (passShellEnvironment) { shellEnv.putAll(System.getenv()); } if (getServletConfig().getInitParameter("executable") != null) { cgiExecutable = getServletConfig().getInitParameter("executable"); } if (getServletConfig().getInitParameter("executable-arg-1") != null) { List<String> args = new ArrayList<String>(); for (int i = 1;; i++) { String arg = getServletConfig().getInitParameter( "executable-arg-" + i); if (arg == null) { break; } args.add(arg); } cgiExecutableArgs = args; } if (getServletConfig().getInitParameter("parameterEncoding") != null) { parameterEncoding = getServletConfig().getInitParameter("parameterEncoding"); } if (getServletConfig().getInitParameter("stderrTimeout") != null) { stderrTimeout = Long.parseLong(getServletConfig().getInitParameter( "stderrTimeout")); } }
// in java/org/apache/catalina/servlets/CGIServlet.java
Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doGet(req, res); }
// in java/org/apache/catalina/servlets/CGIServlet.java
Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { CGIEnvironment cgiEnv = new CGIEnvironment(req, getServletContext()); if (cgiEnv.isValid()) { CGIRunner cgi = new CGIRunner(cgiEnv.getCommand(), cgiEnv.getEnvironment(), cgiEnv.getWorkingDirectory(), cgiEnv.getParameters()); //if POST, we need to cgi.setInput //REMIND: how does this interact with Servlet API 2.3's Filters?! if ("POST".equals(req.getMethod())) { cgi.setInput(req.getInputStream()); } cgi.setResponse(res); cgi.run(); } if (!cgiEnv.isValid()) { res.setStatus(404); } if (debug >= 10) { ServletOutputStream out = res.getOutputStream(); out.println("<HTML><HEAD><TITLE>$Name$</TITLE></HEAD>"); out.println("<BODY>$Header$<p>"); if (cgiEnv.isValid()) { out.println(cgiEnv.toString()); } else { out.println("<H3>"); out.println("CGI script not found or not specified."); out.println("</H3>"); out.println("<H4>"); out.println("Check the <b>HttpServletRequest "); out.println("<a href=\"#pathInfo\">pathInfo</a></b> "); out.println("property to see if it is what you meant "); out.println("it to be. You must specify an existant "); out.println("and executable file as part of the "); out.println("path-info."); out.println("</H4>"); out.println("<H4>"); out.println("For a good discussion of how CGI scripts "); out.println("work and what their environment variables "); out.println("mean, please visit the <a "); out.println("href=\"http://cgi-spec.golux.com\">CGI "); out.println("Specification page</a>."); out.println("</H4>"); } printServletEnvironment(out, req, res); out.println("</BODY></HTML>"); } }
// in java/org/apache/catalina/ha/session/JvmRouteBinderValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { if (getEnabled() && request.getContext() != null && request.getContext().getDistributable() && !request.isAsyncDispatching()) { // valve cluster can access manager - other cluster handle turnover // at host level - hopefully! Manager manager = request.getContext().getManager(); if (manager != null && ( (manager instanceof ClusterManager && getCluster() != null && getCluster().getManager(((ClusterManager)manager).getName()) != null) || (manager instanceof PersistentManager))) { handlePossibleTurnover(request); } } // Pass this request on to the next valve in our pipeline getNext().invoke(request, response); }
// in java/org/apache/catalina/ha/tcp/ReplicationValve.java
Override public void invoke(Request request, Response response) throws IOException, ServletException { long totalstart = 0; //this happens before the request if(doStatistics()) { totalstart = System.currentTimeMillis(); } if (primaryIndicator) { createPrimaryIndicator(request) ; } Context context = request.getContext(); boolean isCrossContext = context != null && context instanceof StandardContext && ((StandardContext) context).getCrossContext(); try { if(isCrossContext) { if(log.isDebugEnabled()) { log.debug(sm.getString("ReplicationValve.crossContext.add")); } //FIXME add Pool of Arraylists crossContextSessions.set(new ArrayList<DeltaSession>()); } getNext().invoke(request, response); if(context != null) { Manager manager = context.getManager(); if (manager != null && manager instanceof ClusterManager) { ClusterManager clusterManager = (ClusterManager) manager; CatalinaCluster containerCluster = (CatalinaCluster) getContainer().getCluster(); if (containerCluster == null) { if (log.isWarnEnabled()) { log.warn(sm.getString("ReplicationValve.nocluster")); } return; } // valve cluster can access manager - other cluster handle replication // at host level - hopefully! if(containerCluster.getManager(clusterManager.getName()) == null) { return ; } if(containerCluster.hasMembers()) { sendReplicationMessage(request, totalstart, isCrossContext, clusterManager, containerCluster); } else { resetReplicationRequest(request,isCrossContext); } } } } finally { // Array must be remove: Current master request send endAccess at recycle. // Don't register this request session again! if(isCrossContext) { if(log.isDebugEnabled()) { log.debug(sm.getString("ReplicationValve.crossContext.remove")); } // crossContextSessions.remove() only exist at Java 5 // register ArrayList at a pool crossContextSessions.set(null); } } }
// in java/org/apache/catalina/ssi/SSIFilter.java
Override public void init(FilterConfig config) throws ServletException { this.config = config; if (config.getInitParameter("debug") != null) { debug = Integer.parseInt(config.getInitParameter("debug")); } if (config.getInitParameter("contentType") != null) { contentTypeRegEx = Pattern.compile(config.getInitParameter("contentType")); } else { contentTypeRegEx = shtmlRegEx; } isVirtualWebappRelative = Boolean.parseBoolean(config.getInitParameter("isVirtualWebappRelative")); if (config.getInitParameter("expires") != null) expires = Long.valueOf(config.getInitParameter("expires")); allowExec = Boolean.parseBoolean(config.getInitParameter("allowExec")); if (debug > 0) config.getServletContext().log( "SSIFilter.init() SSI invoker started with 'debug'=" + debug); }
// in java/org/apache/catalina/ssi/SSIFilter.java
Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // cast once HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse res = (HttpServletResponse)response; // indicate that we're in SSI processing req.setAttribute(Globals.SSI_FLAG_ATTR, "true"); // setup to capture output ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream(); ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(config.getServletContext(),req, res, basos); // process remainder of filter chain chain.doFilter(req, responseIncludeWrapper); // we can't assume the chain flushed its output responseIncludeWrapper.flushOutputStreamOrWriter(); byte[] bytes = basos.toByteArray(); // get content type String contentType = responseIncludeWrapper.getContentType(); // is this an allowed type for SSI processing? if (contentTypeRegEx.matcher(contentType).matches()) { String encoding = res.getCharacterEncoding(); // set up SSI processing SSIExternalResolver ssiExternalResolver = new SSIServletExternalResolver(config.getServletContext(), req, res, isVirtualWebappRelative, debug, encoding); SSIProcessor ssiProcessor = new SSIProcessor(ssiExternalResolver, debug, allowExec); // prepare readers/writers Reader reader = new InputStreamReader(new ByteArrayInputStream(bytes), encoding); ByteArrayOutputStream ssiout = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(ssiout, encoding)); // do SSI processing long lastModified = ssiProcessor.process(reader, responseIncludeWrapper.getLastModified(), writer); // set output bytes writer.flush(); bytes = ssiout.toByteArray(); // override headers if (expires != null) { res.setDateHeader("expires", (new java.util.Date()).getTime() + expires.longValue() * 1000); } if (lastModified > 0) { res.setDateHeader("last-modified", lastModified); } res.setContentLength(bytes.length); Matcher shtmlMatcher = shtmlRegEx.matcher(responseIncludeWrapper.getContentType()); if (shtmlMatcher.matches()) { // Convert shtml mime type to ordinary html mime type but preserve // encoding, if any. String enc = shtmlMatcher.group(1); res.setContentType("text/html" + ((enc != null) ? enc : "")); } } // write output OutputStream out = null; try { out = res.getOutputStream(); } catch (IllegalStateException e) { // Ignore, will try to use a writer } if (out == null) { res.getWriter().write(new String(bytes)); } else { out.write(bytes); } }
// in java/org/apache/catalina/ssi/SSIServlet.java
Override public void init() throws ServletException { if (getServletConfig().getInitParameter("debug") != null) debug = Integer.parseInt(getServletConfig().getInitParameter("debug")); isVirtualWebappRelative = Boolean.parseBoolean(getServletConfig().getInitParameter("isVirtualWebappRelative")); if (getServletConfig().getInitParameter("expires") != null) expires = Long.valueOf(getServletConfig().getInitParameter("expires")); buffered = Boolean.parseBoolean(getServletConfig().getInitParameter("buffered")); inputEncoding = getServletConfig().getInitParameter("inputEncoding"); if (getServletConfig().getInitParameter("outputEncoding") != null) outputEncoding = getServletConfig().getInitParameter("outputEncoding"); allowExec = Boolean.parseBoolean( getServletConfig().getInitParameter("allowExec")); if (debug > 0) log("SSIServlet.init() SSI invoker started with 'debug'=" + debug); }
// in java/org/apache/catalina/ssi/SSIServlet.java
Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { if (debug > 0) log("SSIServlet.doGet()"); requestHandler(req, res); }
// in java/org/apache/catalina/ssi/SSIServlet.java
Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { if (debug > 0) log("SSIServlet.doPost()"); requestHandler(req, res); }
// in java/org/apache/catalina/connector/Request.java
Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { if (response.isCommitted()) { throw new IllegalStateException( sm.getString("coyoteRequest.authenticate.ise")); } return context.getAuthenticator().authenticate(this, response); }
// in java/org/apache/catalina/connector/Request.java
Override public void login(String username, String password) throws ServletException { if (getAuthType() != null || getRemoteUser() != null || getUserPrincipal() != null) { throw new ServletException( sm.getString("coyoteRequest.alreadyAuthenticated")); } if (context.getAuthenticator() == null) { throw new ServletException("no authenticator"); } context.getAuthenticator().login(username, password, this); }
// in java/org/apache/catalina/connector/Request.java
Override public void logout() throws ServletException { context.getAuthenticator().logout(this); }
// in java/org/apache/catalina/connector/Request.java
Override public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException { parseParts(); if (partsParseException != null) { if (partsParseException instanceof IOException) { throw (IOException) partsParseException; } else if (partsParseException instanceof IllegalStateException) { throw (IllegalStateException) partsParseException; } else if (partsParseException instanceof ServletException) { throw (ServletException) partsParseException; } } return parts; }
// in java/org/apache/catalina/connector/Request.java
Override public Part getPart(String name) throws IOException, IllegalStateException, ServletException { Collection<Part> c = getParts(); Iterator<Part> iterator = c.iterator(); while (iterator.hasNext()) { Part part = iterator.next(); if (name.equals(part.getName())) { return part; } } return null; }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { return request.authenticate(response); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public void login(String username, String password) throws ServletException { request.login(username, password); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public void logout() throws ServletException { request.logout(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Collection<Part> getParts() throws IllegalStateException, IOException, ServletException { return request.getParts(); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public Part getPart(String name) throws IllegalStateException, IOException, ServletException { return request.getPart(name); }
// in java/org/apache/catalina/connector/CometEventImpl.java
Override public void setTimeout(int timeout) throws IOException, ServletException, UnsupportedOperationException { if (request.getAttribute(Globals.COMET_TIMEOUT_SUPPORTED_ATTR) == Boolean.TRUE) { request.setAttribute(Globals.COMET_TIMEOUT_ATTR, Integer.valueOf(timeout)); if (request.isComet()) { request.setCometTimeout(timeout); } } else { throw new UnsupportedOperationException(); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; try { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<Void>() { @Override public Void run() throws ServletException, IOException { internalDoFilter(req,res); return null; } } ); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public Void run() throws ServletException, IOException { internalDoFilter(req,res); return null; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
private void internalDoFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { // Call the next filter if there is one if (pos < n) { ApplicationFilterConfig filterConfig = filters[pos++]; Filter filter = null; try { filter = filterConfig.getFilter(); support.fireInstanceEvent(InstanceEvent.BEFORE_FILTER_EVENT, filter, request, response); if (request.isAsyncSupported() && "false".equalsIgnoreCase( filterConfig.getFilterDef().getAsyncSupported())) { request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE); } if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; Principal principal = ((HttpServletRequest) req).getUserPrincipal(); Object[] args = new Object[]{req, res, this}; SecurityUtil.doAsPrivilege ("doFilter", filter, classType, args, principal); } else { filter.doFilter(request, response, this); } support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response); } catch (IOException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (ServletException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (RuntimeException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); } return; } // We fell off the end of the chain -- call the servlet instance try { if (ApplicationDispatcher.WRAP_SAME_OBJECT) { lastServicedRequest.set(request); lastServicedResponse.set(response); } support.fireInstanceEvent(InstanceEvent.BEFORE_SERVICE_EVENT, servlet, request, response); if (request.isAsyncSupported() && !support.getWrapper().isAsyncSupported()) { request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE); } // Use potentially wrapped request from this point if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) { if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; Principal principal = ((HttpServletRequest) req).getUserPrincipal(); Object[] args = new Object[]{req, res}; SecurityUtil.doAsPrivilege("service", servlet, classTypeUsedInService, args, principal); } else { servlet.service(request, response); } } else { servlet.service(request, response); } support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response); } catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); } finally { if (ApplicationDispatcher.WRAP_SAME_OBJECT) { lastServicedRequest.set(null); lastServicedResponse.set(null); } } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public void doFilterEvent(CometEvent event) throws IOException, ServletException { if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; try { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<Void>() { @Override public Void run() throws ServletException, IOException { internalDoFilterEvent(ev); return null; } } ); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
Override public Void run() throws ServletException, IOException { internalDoFilterEvent(ev); return null; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
private void internalDoFilterEvent(CometEvent event) throws IOException, ServletException { // Call the next filter if there is one if (pos < n) { ApplicationFilterConfig filterConfig = filters[pos++]; CometFilter filter = null; try { filter = (CometFilter) filterConfig.getFilter(); // FIXME: No instance listener processing for events for now /* support.fireInstanceEvent(InstanceEvent.BEFORE_FILTER_EVENT, filter, event); */ if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; Principal principal = ev.getHttpServletRequest().getUserPrincipal(); Object[] args = new Object[]{ev, this}; SecurityUtil.doAsPrivilege("doFilterEvent", filter, cometClassType, args, principal); } else { filter.doFilterEvent(event, this); } /*support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event);*/ } catch (IOException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (ServletException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (RuntimeException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); } return; } // We fell off the end of the chain -- call the servlet instance try { /* support.fireInstanceEvent(InstanceEvent.BEFORE_SERVICE_EVENT, servlet, request, response); */ if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; Principal principal = ev.getHttpServletRequest().getUserPrincipal(); Object[] args = new Object[]{ ev }; SecurityUtil.doAsPrivilege("event", servlet, classTypeUsedInEvent, args, principal); } else { ((CometProcessor) servlet).event(event); } /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response);*/ } catch (IOException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (ServletException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (RuntimeException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw new ServletException (sm.getString("filterChain.servlet"), e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Initialize local variables we may need boolean unavailable = false; Throwable throwable = null; // This should be a Request attribute... long t1=System.currentTimeMillis(); requestCount++; StandardWrapper wrapper = (StandardWrapper) getContainer(); Servlet servlet = null; Context context = (Context) wrapper.getParent(); // Check for the application being marked unavailable if (!context.getAvailable()) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardContext.isUnavailable")); unavailable = true; } // Check for the servlet being marked unavailable if (!unavailable && wrapper.isUnavailable()) { container.getLogger().info(sm.getString("standardWrapper.isUnavailable", wrapper.getName())); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } unavailable = true; } // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (UnavailableException e) { container.getLogger().error( sm.getString("standardWrapper.allocateException", wrapper.getName()), e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } } catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } // Identify if the request is Comet related now that the servlet has been allocated boolean comet = false; if (servlet instanceof CometProcessor && request.getAttribute( Globals.COMET_SUPPORTED_ATTR) == Boolean.TRUE) { comet = true; request.setComet(true); } MessageBytes requestPathMB = request.getRequestPathMB(); DispatcherType dispatcherType = DispatcherType.REQUEST; if (request.getDispatcherType()==DispatcherType.ASYNC) dispatcherType = DispatcherType.ASYNC; request.setAttribute (ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, dispatcherType); request.setAttribute (ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB); // Create the filter chain for this request ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance(); ApplicationFilterChain filterChain = factory.createFilterChain(request, wrapper, servlet); // Reset comet flag value after creating the filter chain request.setComet(false); // Call the filter chain for this request // NOTE: This also calls the servlet's service() method try { if ((servlet != null) && (filterChain != null)) { // Swallow output if needed if (context.getSwallowOutput()) { try { SystemLogHandler.startCapture(); if (request.isAsyncDispatching()) { //TODO SERVLET3 - async ((AsyncContextImpl)request.getAsyncContext()).doInternalDispatch(); } else if (comet) { filterChain.doFilterEvent(request.getEvent()); request.setComet(true); } else { filterChain.doFilter(request.getRequest(), response.getResponse()); } } finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } } } else { if (request.isAsyncDispatching()) { //TODO SERVLET3 - async ((AsyncContextImpl)request.getAsyncContext()).doInternalDispatch(); } else if (comet) { request.setComet(true); filterChain.doFilterEvent(request.getEvent()); } else { filterChain.doFilter (request.getRequest(), response.getResponse()); } } } } catch (ClientAbortException e) { throwable = e; exception(request, response, e); } catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing } catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } // Release the filter chain (if any) for this request if (filterChain != null) { if (request.isComet()) { // If this is a Comet request, then the same chain will be used for the // processing of all subsequent events. filterChain.reuse(); } else { filterChain.release(); } } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } // If this servlet has been marked permanently unavailable, // unload it and release this instance try { if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) { wrapper.unload(); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } long t2=System.currentTimeMillis(); long time=t2-t1; processingTime += time; if( time > maxTime) maxTime=time; if( time < minTime) minTime=time; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
Override public void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Initialize local variables we may need Throwable throwable = null; // This should be a Request attribute... long t1=System.currentTimeMillis(); // FIXME: Add a flag to count the total amount of events processed ? requestCount++; StandardWrapper wrapper = (StandardWrapper) getContainer(); if (wrapper == null) { // Context has been shutdown. Nothing to do here. return; } Servlet servlet = null; Context context = (Context) wrapper.getParent(); // Check for the application being marked unavailable boolean unavailable = !context.getAvailable() || wrapper.isUnavailable(); // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (UnavailableException e) { // The response is already committed, so it's not possible to do anything } catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } MessageBytes requestPathMB = request.getRequestPathMB(); request.setAttribute (ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, DispatcherType.REQUEST); request.setAttribute (ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB); // Get the current (unchanged) filter chain for this request ApplicationFilterChain filterChain = (ApplicationFilterChain) request.getFilterChain(); // Call the filter chain for this request // NOTE: This also calls the servlet's event() method try { if ((servlet != null) && (filterChain != null)) { // Swallow output if needed if (context.getSwallowOutput()) { try { SystemLogHandler.startCapture(); filterChain.doFilterEvent(request.getEvent()); } finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } } } else { filterChain.doFilterEvent(request.getEvent()); } } } catch (ClientAbortException e) { throwable = e; exception(request, response, e); } catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing } catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } // Release the filter chain (if any) for this request if (filterChain != null) { filterChain.reuse(); } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } // If this servlet has been marked permanently unavailable, // unload it and release this instance try { if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) { wrapper.unload(); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } long t2=System.currentTimeMillis(); long time=t2-t1; processingTime += time; if( time > maxTime) maxTime=time; if( time < minTime) minTime=time; }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
Filter getFilter() throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { // Return the existing filter instance, if any if (this.filter != null) return (this.filter); // Identify the class loader we will be using String filterClass = filterDef.getFilterClass(); this.filter = (Filter) getInstanceManager().newInstance(filterClass); initFilter(); return (this.filter); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
private void initFilter() throws ServletException { if (context instanceof StandardContext && context.getSwallowOutput()) { try { SystemLogHandler.startCapture(); filter.init(this); } finally { String capturedlog = SystemLogHandler.stopCapture(); if (capturedlog != null && capturedlog.length() > 0) { getServletContext().log(capturedlog); } } } else { filter.init(this); } // Expose filter via JMX registerJMX(); }
// in java/org/apache/catalina/core/ApplicationFilterConfig.java
void setFilterDef(FilterDef filterDef) throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException, InvocationTargetException, NamingException { this.filterDef = filterDef; if (filterDef == null) { // Release any previously allocated filter instance if (this.filter != null){ if (Globals.IS_SECURITY_ENABLED) { try{ SecurityUtil.doAsPrivilege("destroy", filter); } catch(java.lang.Exception ex){ context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex); } SecurityUtil.remove(filter); } else { filter.destroy(); } if (!context.getIgnoreAnnotations()) { try { ((StandardContext) context).getInstanceManager().destroyInstance(this.filter); } catch (Exception e) { Throwable t = ExceptionUtils .unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); context.getLogger().error("ApplicationFilterConfig.preDestroy", t); } } } this.filter = null; } else { // Allocate a new filter instance if necessary if (filterDef.getFilter() == null) { getFilter(); } } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends Filter> T createFilter(Class<T> c) throws ServletException { try { @SuppressWarnings("unchecked") T filter = (T) context.getInstanceManager().newInstance(c.getName()); return filter; } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends Servlet> T createServlet(Class<T> c) throws ServletException { try { @SuppressWarnings("unchecked") T servlet = (T) context.getInstanceManager().newInstance(c.getName()); context.dynamicServletCreated(servlet); return servlet; } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } }
// in java/org/apache/catalina/core/ApplicationContext.java
Override public <T extends EventListener> T createListener(Class<T> c) throws ServletException { try { @SuppressWarnings("unchecked") T listener = (T) context.getInstanceManager().newInstance(c.getName()); if (listener instanceof ServletContextListener || listener instanceof ServletContextAttributeListener || listener instanceof ServletRequestListener || listener instanceof ServletRequestAttributeListener || listener instanceof HttpSessionListener || listener instanceof HttpSessionAttributeListener) { return listener; } throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", listener.getClass().getName())); } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } }
// in java/org/apache/catalina/core/AsyncContextImpl.java
protected void doInternalDispatch() throws ServletException, IOException { if (log.isDebugEnabled()) { logDebug("intDispatch"); } try { dispatch.run(); if (!request.isAsync()) { fireOnComplete(); } } catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); } }
// in java/org/apache/catalina/core/StandardContextValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Disallow any direct access to resources under WEB-INF or META-INF MessageBytes requestPathMB = request.getRequestPathMB(); if ((requestPathMB.startsWithIgnoreCase("/META-INF/", 0)) || (requestPathMB.equalsIgnoreCase("/META-INF")) || (requestPathMB.startsWithIgnoreCase("/WEB-INF/", 0)) || (requestPathMB.equalsIgnoreCase("/WEB-INF"))) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Select the Wrapper to be used for this Request Wrapper wrapper = request.getWrapper(); if (wrapper == null || wrapper.isUnavailable()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Acknowledge the request try { response.sendAcknowledgement(); } catch (IOException ioe) { container.getLogger().error(sm.getString( "standardContextValve.acknowledgeException"), ioe); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (request.isAsyncSupported()) { request.setAsyncSupported(wrapper.getPipeline().isAsyncSupported()); } wrapper.getPipeline().getFirst().invoke(request, response); }
// in java/org/apache/catalina/core/StandardContextValve.java
Override public final void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Select the Wrapper to be used for this Request Wrapper wrapper = request.getWrapper(); wrapper.getPipeline().getFirst().event(request, response, event); }
// in java/org/apache/catalina/core/StandardEngineValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Select the Host to be used for this Request Host host = request.getHost(); if (host == null) { response.sendError (HttpServletResponse.SC_BAD_REQUEST, sm.getString("standardEngine.noHost", request.getServerName())); return; } if (request.isAsyncSupported()) { request.setAsyncSupported(host.getPipeline().isAsyncSupported()); } // Ask this Host to process this request host.getPipeline().getFirst().invoke(request, response); }
// in java/org/apache/catalina/core/StandardEngineValve.java
Override public final void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Ask this Host to process this request request.getHost().getPipeline().getFirst().event(request, response, event); }
// in java/org/apache/catalina/core/StandardHostValve.java
Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Select the Context to be used for this Request Context context = request.getContext(); if (context == null) { response.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, sm.getString("standardHost.noContext")); return; } // Bind the context CL to the current thread if( context.getLoader() != null ) { // Not started - it should check for availability first // This should eventually move to Engine, it's generic. if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( context.getLoader().getClassLoader()); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader (context.getLoader().getClassLoader()); } } if (request.isAsyncSupported()) { request.setAsyncSupported(context.getPipeline().isAsyncSupported()); } // Don't fire listeners during async processing // If a request init listener throws an exception, the request is // aborted boolean asyncAtStart = request.isAsync(); if (asyncAtStart || context.fireRequestInitEvent(request)) { // Ask this Context to process this request try { context.getPipeline().getFirst().invoke(request, response); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); throwable(request, response, t); } // If the request was async at the start and an error occurred then // the async error handling will kick-in and that will fire the // request destroyed event *after* the error handling has taken // place if (!(request.isAsync() || (asyncAtStart && request.getAttribute( RequestDispatcher.ERROR_EXCEPTION) != null))) { // Protect against NPEs if context was destroyed during a long // running request. if (context.getState().isAvailable()) { // Error page processing response.setSuspended(false); Throwable t = (Throwable) request.getAttribute( RequestDispatcher.ERROR_EXCEPTION); if (t != null) { throwable(request, response, t); } else { status(request, response); } context.fireRequestDestroyEvent(request); } } } // Access a session (if present) to update last accessed time, based on a // strict interpretation of the specification if (ACCESS_SESSION) { request.getSession(false); } // Restore the context classloader if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( StandardHostValve.class.getClassLoader()); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader (StandardHostValve.class.getClassLoader()); } }
// in java/org/apache/catalina/core/StandardHostValve.java
Override public final void event(Request request, Response response, CometEvent event) throws IOException, ServletException { // Select the Context to be used for this Request Context context = request.getContext(); // Bind the context CL to the current thread if( context.getLoader() != null ) { // Not started - it should check for availability first // This should eventually move to Engine, it's generic. Thread.currentThread().setContextClassLoader (context.getLoader().getClassLoader()); } // Ask this Context to process this request context.getPipeline().getFirst().event(request, response, event); // Error page processing response.setSuspended(false); Throwable t = (Throwable) request.getAttribute( RequestDispatcher.ERROR_EXCEPTION); if (t != null) { throwable(request, response, t); } else { status(request, response); } // Access a session (if present) to update last accessed time, based on a // strict interpretation of the specification if (ACCESS_SESSION) { request.getSession(false); } // Restore the context classloader Thread.currentThread().setContextClassLoader (StandardHostValve.class.getClassLoader()); }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public String[] getServletMethods() throws ServletException { instance = loadServlet(); Class<? extends Servlet> servletClazz = instance.getClass(); if (!javax.servlet.http.HttpServlet.class.isAssignableFrom( servletClazz)) { return DEFAULT_SERVLET_METHODS; } HashSet<String> allow = new HashSet<String>(); allow.add("TRACE"); allow.add("OPTIONS"); Method[] methods = getAllDeclaredMethods(servletClazz); for (int i=0; methods != null && i<methods.length; i++) { Method m = methods[i]; if (m.getName().equals("doGet")) { allow.add("GET"); allow.add("HEAD"); } else if (m.getName().equals("doPost")) { allow.add("POST"); } else if (m.getName().equals("doPut")) { allow.add("PUT"); } else if (m.getName().equals("doDelete")) { allow.add("DELETE"); } } String[] methodNames = new String[allow.size()]; return allow.toArray(methodNames); }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public Servlet allocate() throws ServletException { // If we are currently unloading this servlet, throw an exception if (unloading) throw new ServletException (sm.getString("standardWrapper.unloading", getName())); boolean newInstance = false; // If not SingleThreadedModel, return the same instance every time if (!singleThreadModel) { // Load and initialize our instance if necessary if (instance == null) { synchronized (this) { if (instance == null) { try { if (log.isDebugEnabled()) log.debug("Allocating non-STM instance"); instance = loadServlet(); if (!singleThreadModel) { // For non-STM, increment here to prevent a race // condition with unload. Bug 43683, test case // #3 newInstance = true; countAllocated.incrementAndGet(); } } catch (ServletException e) { throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); } } } } if (!instanceInitialized) { initServlet(instance); } if (singleThreadModel) { if (newInstance) { // Have to do this outside of the sync above to prevent a // possible deadlock synchronized (instancePool) { instancePool.push(instance); nInstances++; } } } else { if (log.isTraceEnabled()) log.trace(" Returning non-STM instance"); // For new instances, count will have been incremented at the // time of creation if (!newInstance) { countAllocated.incrementAndGet(); } return (instance); } } synchronized (instancePool) { while (countAllocated.get() >= nInstances) { // Allocate a new instance if possible, or else wait if (nInstances < maxInstances) { try { instancePool.push(loadServlet()); nInstances++; } catch (ServletException e) { throw e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); } } else { try { instancePool.wait(); } catch (InterruptedException e) { // Ignore } } } if (log.isTraceEnabled()) log.trace(" Returning allocated STM instance"); countAllocated.incrementAndGet(); return instancePool.pop(); } }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public void deallocate(Servlet servlet) throws ServletException { // If not SingleThreadModel, no action is required if (!singleThreadModel) { countAllocated.decrementAndGet(); return; } // Unlock and free this instance synchronized (instancePool) { countAllocated.decrementAndGet(); instancePool.push(servlet); instancePool.notify(); } }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public synchronized void load() throws ServletException { instance = loadServlet(); if (!instanceInitialized) { initServlet(instance); } if (isJspServlet) { StringBuilder oname = new StringBuilder(getDomain()); oname.append(":type=JspMonitor,name="); oname.append(getName()); oname.append(getWebModuleKeyProperties()); try { jspMonitorON = new ObjectName(oname.toString()); Registry.getRegistry(null, null) .registerComponent(instance, jspMonitorON, null); } catch( Exception ex ) { log.info("Error registering JSP monitoring with jmx " + instance); } } }
// in java/org/apache/catalina/core/StandardWrapper.java
public synchronized Servlet loadServlet() throws ServletException { // Nothing to do if we already have an instance or an instance pool if (!singleThreadModel && (instance != null)) return instance; PrintStream out = System.out; if (swallowOutput) { SystemLogHandler.startCapture(); } Servlet servlet; try { long t1=System.currentTimeMillis(); // Complain if no servlet class has been specified if (servletClass == null) { unavailable(null); throw new ServletException (sm.getString("standardWrapper.notClass", getName())); } InstanceManager instanceManager = ((StandardContext)getParent()).getInstanceManager(); try { servlet = (Servlet) instanceManager.newInstance(servletClass); } catch (ClassCastException e) { unavailable(null); // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.notServlet", servletClass), e); } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); } if (multipartConfigElement == null) { MultipartConfig annotation = servlet.getClass().getAnnotation(MultipartConfig.class); if (annotation != null) { multipartConfigElement = new MultipartConfigElement(annotation); } } processServletSecurityAnnotation(servlet.getClass()); // Special handling for ContainerServlet instances if ((servlet instanceof ContainerServlet) && (isContainerProvidedServlet(servletClass) || ((Context) getParent()).getPrivileged() )) { ((ContainerServlet) servlet).setWrapper(this); } classLoadTime=(int) (System.currentTimeMillis() -t1); if (servlet instanceof SingleThreadModel) { if (instancePool == null) { instancePool = new Stack<Servlet>(); } singleThreadModel = true; } initServlet(servlet); fireContainerEvent("load", this); loadTime=System.currentTimeMillis() -t1; } finally { if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } } return servlet; }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public void servletSecurityAnnotationScan() throws ServletException { if (getServlet() == null) { Class<?> clazz = null; try { clazz = getParent().getLoader().getClassLoader().loadClass( getServletClass()); processServletSecurityAnnotation(clazz); } catch (ClassNotFoundException e) { // Safe to ignore. No class means no annotations to process } } else { if (servletSecurityAnnotationScanRequired) { processServletSecurityAnnotation(getServlet().getClass()); } } }
// in java/org/apache/catalina/core/StandardWrapper.java
private synchronized void initServlet(Servlet servlet) throws ServletException { if (instanceInitialized && !singleThreadModel) return; // Call the initialization method of this servlet try { instanceSupport.fireInstanceEvent(InstanceEvent.BEFORE_INIT_EVENT, servlet); if( Globals.IS_SECURITY_ENABLED) { Object[] args = new Object[]{(facade)}; SecurityUtil.doAsPrivilege("init", servlet, classType, args); args = null; } else { servlet.init(facade); } instanceInitialized = true; instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet); } catch (UnavailableException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); unavailable(f); throw f; } catch (ServletException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw f; } catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); } }
// in java/org/apache/catalina/core/StandardWrapper.java
Override public synchronized void unload() throws ServletException { // Nothing to do if we have never loaded the instance if (!singleThreadModel && (instance == null)) return; unloading = true; // Loaf a while if the current instance is allocated // (possibly more than once if non-STM) if (countAllocated.get() > 0) { int nRetries = 0; long delay = unloadDelay / 20; while ((nRetries < 21) && (countAllocated.get() > 0)) { if ((nRetries % 10) == 0) { log.info(sm.getString("standardWrapper.waiting", countAllocated.toString())); } try { Thread.sleep(delay); } catch (InterruptedException e) { // Ignore } nRetries++; } } if (instanceInitialized) { PrintStream out = System.out; if (swallowOutput) { SystemLogHandler.startCapture(); } // Call the servlet destroy() method try { instanceSupport.fireInstanceEvent (InstanceEvent.BEFORE_DESTROY_EVENT, instance); if( Globals.IS_SECURITY_ENABLED) { SecurityUtil.doAsPrivilege("destroy", instance); SecurityUtil.remove(instance); } else { instance.destroy(); } instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance); // Annotation processing if (!((Context) getParent()).getIgnoreAnnotations()) { ((StandardContext)getParent()).getInstanceManager().destroyInstance(instance); } } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); } finally { // Write captured output if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } } } // Deregister the destroyed instance instance = null; if (isJspServlet && jspMonitorON != null ) { Registry.getRegistry(null, null).unregisterComponent(jspMonitorON); } if (singleThreadModel && (instancePool != null)) { try { while (!instancePool.isEmpty()) { Servlet s = instancePool.pop(); if (Globals.IS_SECURITY_ENABLED) { SecurityUtil.doAsPrivilege("destroy", s); SecurityUtil.remove(instance); } else { s.destroy(); } // Annotation processing if (!((Context) getParent()).getIgnoreAnnotations()) { ((StandardContext)getParent()).getInstanceManager().destroyInstance(s); } } } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); } instancePool = null; nInstances = 0; } singleThreadModel = false; unloading = false; fireContainerEvent("unload", this); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
Override public Void run() throws ServletException, IOException { DispatcherType type = DispatcherType.INCLUDE; if (request.getDispatcherType()==DispatcherType.ASYNC) type = DispatcherType.ASYNC; doInclude(request,response,type); return null; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
Override public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (Globals.IS_SECURITY_ENABLED) { try { PrivilegedForward dp = new PrivilegedForward(request,response); AccessController.doPrivileged(dp); } catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; } } else { doForward(request,response); } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void doForward(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Reset any output that has been buffered, but keep headers/cookies if (response.isCommitted()) { throw new IllegalStateException (sm.getString("applicationDispatcher.forward.ise")); } try { response.resetBuffer(); } catch (IllegalStateException e) { throw e; } // Set up to handle the specified request and response State state = new State(request, response, false); if (WRAP_SAME_OBJECT) { // Check SRV.8.2 / SRV.14.2.5.1 compliance checkSameObjects(request, response); } wrapResponse(state); // Handle an HTTP named dispatcher forward if ((servletPath == null) && (pathInfo == null)) { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); HttpServletRequest hrequest = state.hrequest; wrequest.setRequestURI(hrequest.getRequestURI()); wrequest.setContextPath(hrequest.getContextPath()); wrequest.setServletPath(hrequest.getServletPath()); wrequest.setPathInfo(hrequest.getPathInfo()); wrequest.setQueryString(hrequest.getQueryString()); processRequest(request,response,state); } // Handle an HTTP path-based forward else { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); String contextPath = context.getPath(); HttpServletRequest hrequest = state.hrequest; if (hrequest.getAttribute( RequestDispatcher.FORWARD_REQUEST_URI) == null) { wrequest.setAttribute(RequestDispatcher.FORWARD_REQUEST_URI, hrequest.getRequestURI()); wrequest.setAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH, hrequest.getContextPath()); wrequest.setAttribute(RequestDispatcher.FORWARD_SERVLET_PATH, hrequest.getServletPath()); wrequest.setAttribute(RequestDispatcher.FORWARD_PATH_INFO, hrequest.getPathInfo()); wrequest.setAttribute(RequestDispatcher.FORWARD_QUERY_STRING, hrequest.getQueryString()); } wrequest.setContextPath(contextPath); wrequest.setRequestURI(requestURI); wrequest.setServletPath(servletPath); wrequest.setPathInfo(pathInfo); if (queryString != null) { wrequest.setQueryString(queryString); wrequest.setQueryParams(queryString); } processRequest(request,response,state); } // This is not a real close in order to support error processing if (wrapper.getLogger().isDebugEnabled() ) wrapper.getLogger().debug(" Disabling the response for futher output"); if (response instanceof ResponseFacade) { ((ResponseFacade) response).finish(); } else { // Servlet SRV.6.2.2. The Request/Response may have been wrapped // and may no longer be instance of RequestFacade if (wrapper.getLogger().isDebugEnabled()){ wrapper.getLogger().debug( " The Response is vehiculed using a wrapper: " + response.getClass().getName() ); } // Close anyway try { PrintWriter writer = response.getWriter(); writer.close(); } catch (IllegalStateException e) { try { ServletOutputStream stream = response.getOutputStream(); stream.close(); } catch (IllegalStateException f) { // Ignore } catch (IOException f) { // Ignore } } catch (IOException e) { // Ignore } } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void processRequest(ServletRequest request, ServletResponse response, State state) throws IOException, ServletException { DispatcherType disInt = (DispatcherType) request.getAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR); if (disInt != null) { boolean doInvoke = true; if (context.getFireRequestListenersOnForwards() && !context.fireRequestInitEvent(request)) { doInvoke = false; } if (doInvoke) { if (disInt != DispatcherType.ERROR) { state.outerRequest.setAttribute (ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); state.outerRequest.setAttribute (ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, DispatcherType.FORWARD); invoke(state.outerRequest, response, state); } else { invoke(state.outerRequest, response, state); } if (context.getFireRequestListenersOnForwards()) { context.fireRequestDestroyEvent(request); } } } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
Override public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (Globals.IS_SECURITY_ENABLED) { try { PrivilegedInclude dp = new PrivilegedInclude(request,response); AccessController.doPrivileged(dp); } catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; } } else { DispatcherType type = DispatcherType.INCLUDE; if (request.getDispatcherType()==DispatcherType.ASYNC) type = DispatcherType.ASYNC; doInclude(request,response,type); } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void doInclude(ServletRequest request, ServletResponse response, DispatcherType type) throws ServletException, IOException { // Set up to handle the specified request and response State state = new State(request, response, true); if (WRAP_SAME_OBJECT) { // Check SRV.8.2 / SRV.14.2.5.1 compliance checkSameObjects(request, response); } // Create a wrapped response to use for this request wrapResponse(state); // Handle an HTTP named dispatcher include if (name != null) { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); wrequest.setAttribute(Globals.NAMED_DISPATCHER_ATTR, name); if (servletPath != null) wrequest.setServletPath(servletPath); wrequest.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, type); wrequest.setAttribute( ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); invoke(state.outerRequest, state.outerResponse, state); } // Handle an HTTP path based include else { ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); String contextPath = context.getPath(); if (requestURI != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_REQUEST_URI, requestURI); if (contextPath != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH, contextPath); if (servletPath != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH, servletPath); if (pathInfo != null) wrequest.setAttribute(RequestDispatcher.INCLUDE_PATH_INFO, pathInfo); if (queryString != null) { wrequest.setAttribute(RequestDispatcher.INCLUDE_QUERY_STRING, queryString); wrequest.setQueryParams(queryString); } wrequest.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, type); wrequest.setAttribute( ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); invoke(state.outerRequest, state.outerResponse, state); } }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void invoke(ServletRequest request, ServletResponse response, State state) throws IOException, ServletException { // Checking to see if the context classloader is the current context // classloader. If it's not, we're saving it, and setting the context // classloader to the Context classloader ClassLoader oldCCL = Thread.currentThread().getContextClassLoader(); ClassLoader contextClassLoader = context.getLoader().getClassLoader(); if (oldCCL != contextClassLoader) { Thread.currentThread().setContextClassLoader(contextClassLoader); } else { oldCCL = null; } // Initialize local variables we may need HttpServletResponse hresponse = state.hresponse; Servlet servlet = null; IOException ioException = null; ServletException servletException = null; RuntimeException runtimeException = null; boolean unavailable = false; // Check for the servlet being marked unavailable if (wrapper.isUnavailable()) { wrapper.getLogger().warn( sm.getString("applicationDispatcher.isUnavailable", wrapper.getName())); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) hresponse.setDateHeader("Retry-After", available); hresponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm .getString("applicationDispatcher.isUnavailable", wrapper .getName())); unavailable = true; } // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); servletException = e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servlet = null; } // Get the FilterChain Here ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance(); ApplicationFilterChain filterChain = factory.createFilterChain(request, wrapper,servlet); // Call the service() method for the allocated servlet instance try { support.fireInstanceEvent(InstanceEvent.BEFORE_DISPATCH_EVENT, servlet, request, response); // for includes/forwards if ((servlet != null) && (filterChain != null)) { filterChain.doFilter(request, response); } // Servlet Service Method is called by the FilterChain support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); } catch (ClientAbortException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); ioException = e; } catch (IOException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); ioException = e; } catch (UnavailableException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); servletException = e; wrapper.unavailable(e); } catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause); } servletException = e; } catch (RuntimeException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); runtimeException = e; } // Release the filter chain (if any) for this request try { if (filterChain != null) filterChain.release(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e); // FIXME: Exception handling needs to be similar to what is in the StandardWrapperValue } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = e; } catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); } // Reset the old context class loader if (oldCCL != null) Thread.currentThread().setContextClassLoader(oldCCL); // Unwrap request/response if needed // See Bugzilla 30949 unwrapRequest(state); unwrapResponse(state); // Recycle request if necessary (also BZ 30949) recycleRequestWrapper(state); // Rethrow an exception if one was thrown by the invoked servlet if (ioException != null) throw ioException; if (servletException != null) throw servletException; if (runtimeException != null) throw runtimeException; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
private void checkSameObjects(ServletRequest appRequest, ServletResponse appResponse) throws ServletException { ServletRequest originalRequest = ApplicationFilterChain.getLastServicedRequest(); ServletResponse originalResponse = ApplicationFilterChain.getLastServicedResponse(); // Some forwards, eg from valves will not set original values if (originalRequest == null || originalResponse == null) { return; } boolean same = false; ServletRequest dispatchedRequest = appRequest; //find the request that was passed into the service method while (originalRequest instanceof ServletRequestWrapper && ((ServletRequestWrapper) originalRequest).getRequest()!=null ) { originalRequest = ((ServletRequestWrapper) originalRequest).getRequest(); } //compare with the dispatched request while (!same) { if (originalRequest.equals(dispatchedRequest)) { same = true; } if (!same && dispatchedRequest instanceof ServletRequestWrapper) { dispatchedRequest = ((ServletRequestWrapper) dispatchedRequest).getRequest(); } else { break; } } if (!same) { throw new ServletException(sm.getString( "applicationDispatcher.specViolation.request")); } same = false; ServletResponse dispatchedResponse = appResponse; //find the response that was passed into the service method while (originalResponse instanceof ServletResponseWrapper && ((ServletResponseWrapper) originalResponse).getResponse() != null ) { originalResponse = ((ServletResponseWrapper) originalResponse).getResponse(); } //compare with the dispatched response while (!same) { if (originalResponse.equals(dispatchedResponse)) { same = true; } if (!same && dispatchedResponse instanceof ServletResponseWrapper) { dispatchedResponse = ((ServletResponseWrapper) dispatchedResponse).getResponse(); } else { break; } } if (!same) { throw new ServletException(sm.getString( "applicationDispatcher.specViolation.response")); } }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { return this._getHttpServletRequest().authenticate(response); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public void login(String username, String password) throws ServletException { this._getHttpServletRequest().login(username, password); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public void logout() throws ServletException { this._getHttpServletRequest().logout(); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public Collection<Part> getParts() throws IllegalStateException, IOException, ServletException { return this._getHttpServletRequest().getParts(); }
// in java/javax/servlet/http/HttpServletRequestWrapper.java
Override public Part getPart(String name) throws IllegalStateException, IOException, ServletException { return this._getHttpServletRequest().getPart(name); }
// in java/javax/servlet/http/HttpServlet.java
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_get_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { NoBodyResponse response = new NoBodyResponse(resp); doGet(req, response); response.setContentLength(); }
// in java/javax/servlet/http/HttpServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_post_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_put_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String protocol = req.getProtocol(); String msg = lStrings.getString("http.method_delete_not_supported"); if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } }
// in java/javax/servlet/http/HttpServlet.java
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Method[] methods = getAllDeclaredMethods(this.getClass()); boolean ALLOW_GET = false; boolean ALLOW_HEAD = false; boolean ALLOW_POST = false; boolean ALLOW_PUT = false; boolean ALLOW_DELETE = false; boolean ALLOW_TRACE = true; boolean ALLOW_OPTIONS = true; for (int i=0; i<methods.length; i++) { Method m = methods[i]; if (m.getName().equals("doGet")) { ALLOW_GET = true; ALLOW_HEAD = true; } if (m.getName().equals("doPost")) ALLOW_POST = true; if (m.getName().equals("doPut")) ALLOW_PUT = true; if (m.getName().equals("doDelete")) ALLOW_DELETE = true; } String allow = null; if (ALLOW_GET) allow=METHOD_GET; if (ALLOW_HEAD) if (allow==null) allow=METHOD_HEAD; else allow += ", " + METHOD_HEAD; if (ALLOW_POST) if (allow==null) allow=METHOD_POST; else allow += ", " + METHOD_POST; if (ALLOW_PUT) if (allow==null) allow=METHOD_PUT; else allow += ", " + METHOD_PUT; if (ALLOW_DELETE) if (allow==null) allow=METHOD_DELETE; else allow += ", " + METHOD_DELETE; if (ALLOW_TRACE) if (allow==null) allow=METHOD_TRACE; else allow += ", " + METHOD_TRACE; if (ALLOW_OPTIONS) if (allow==null) allow=METHOD_OPTIONS; else allow += ", " + METHOD_OPTIONS; resp.setHeader("Allow", allow); }
// in java/javax/servlet/http/HttpServlet.java
protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int responseLength; String CRLF = "\r\n"; StringBuilder buffer = new StringBuilder("TRACE ").append(req.getRequestURI()) .append(" ").append(req.getProtocol()); Enumeration<String> reqHeaderEnum = req.getHeaderNames(); while( reqHeaderEnum.hasMoreElements() ) { String headerName = reqHeaderEnum.nextElement(); buffer.append(CRLF).append(headerName).append(": ") .append(req.getHeader(headerName)); } buffer.append(CRLF); responseLength = buffer.length(); resp.setContentType("message/http"); resp.setContentLength(responseLength); ServletOutputStream out = resp.getOutputStream(); out.print(buffer.toString()); out.close(); return; }
// in java/javax/servlet/http/HttpServlet.java
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod(); if (method.equals(METHOD_GET)) { long lastModified = getLastModified(req); if (lastModified == -1) { // servlet doesn't support if-modified-since, no reason // to go through further expensive logic doGet(req, resp); } else { long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE); if (ifModifiedSince < (lastModified / 1000 * 1000)) { // If the servlet mod time is later, call doGet() // Round down to the nearest second for a proper compare // A ifModifiedSince of -1 will always be less maybeSetLastModified(resp, lastModified); doGet(req, resp); } else { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } } } else if (method.equals(METHOD_HEAD)) { long lastModified = getLastModified(req); maybeSetLastModified(resp, lastModified); doHead(req, resp); } else if (method.equals(METHOD_POST)) { doPost(req, resp); } else if (method.equals(METHOD_PUT)) { doPut(req, resp); } else if (method.equals(METHOD_DELETE)) { doDelete(req, resp); } else if (method.equals(METHOD_OPTIONS)) { doOptions(req,resp); } else if (method.equals(METHOD_TRACE)) { doTrace(req,resp); } else { // // Note that this means NO servlet supports whatever // method was requested, anywhere on this server. // String errMsg = lStrings.getString("http.method_not_implemented"); Object[] errArgs = new Object[1]; errArgs[0] = method; errMsg = MessageFormat.format(errMsg, errArgs); resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg); } }
// in java/javax/servlet/http/HttpServlet.java
Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request; HttpServletResponse response; try { request = (HttpServletRequest) req; response = (HttpServletResponse) res; } catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); } service(request, response); }
// in java/javax/servlet/GenericServlet.java
Override public void init(ServletConfig config) throws ServletException { this.config = config; this.init(); }
// in java/javax/servlet/GenericServlet.java
public void init() throws ServletException { // NOOP by default }
22
            
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (ServletException e) { throw e; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
catch (ServletException e) { throw new IOException("Couldn't include file: " + originalPath + " because of ServletException: " + e.getMessage()); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ServletException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.init", listenerClass.getName()), e); }
// in java/org/apache/catalina/core/StandardContext.java
catch (ServletException e) { getLogger().error(sm.getString("standardWrapper.loadException", getName()), StandardWrapper.getRootCause(e)); // NOTE: load errors (including a servlet that throws // UnavailableException from tht init() method) are NOT // fatal to application startup }
// in java/org/apache/catalina/core/StandardContext.java
catch (ServletException e) { // TODO: Log error ok = false; break; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { throw e; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { throw e; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw f; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { getServletContext().log(sm.getString ("standardWrapper.unloadException", getName()), e); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause); } servletException = e; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (ServletException e) { wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = e; }
14
            
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (ServletException ex) { if(options.getDevelopment()) { throw handleJspException(ex); } throw ex; }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (ServletException e) { throw e; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
catch (ServletException e) { throw new IOException("Couldn't include file: " + originalPath + " because of ServletException: " + e.getMessage()); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { /* if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (ServletException e) { /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw e; }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (ServletException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.init", listenerClass.getName()), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { throw e; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException e) { throw e; }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (ServletException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw f; }
1
checked (Domain) SizeException
public abstract static class SizeException extends FileUploadException {

        private static final long serialVersionUID = -8776225574705254126L;

        /**
         * The actual size of the request.
         */
        private final long actual;

        /**
         * The maximum permitted size of the request.
         */
        private final long permitted;

        /**
         * Creates a new instance.
         * @param message The detail message.
         * @param actual The actual number of bytes in the request.
         * @param permitted The requests size limit, in bytes.
         */
        protected SizeException(String message, long actual, long permitted) {
            super(message);
            this.actual = actual;
            this.permitted = permitted;
        }

        /**
         * Retrieves the actual size of the request.
         *
         * @return The actual size of the request.
         */
        public long getActualSize() {
            return actual;
        }

        /**
         * Retrieves the permitted size of the request.
         *
         * @return The permitted size of the request.
         */
        public long getPermittedSize() {
            return permitted;
        }
    }
0 0 0 1
            
// in java/org/apache/catalina/connector/Request.java
catch (FileUploadBase.SizeException e) { checkSwallowInput(); partsParseException = new IllegalStateException(e); }
0 0
checked (Domain) SizeLimitExceededException
public static class SizeLimitExceededException
            extends SizeException {
        /** The exceptions UID, for serializing an instance.
         */
        private static final long serialVersionUID = -2474893167098052828L;

        /**
         * Constructs a <code>SizeExceededException</code> with
         * the specified detail message, and actual and permitted sizes.
         *
         * @param message   The detail message.
         * @param actual    The actual request size.
         * @param permitted The maximum permitted request size.
         */
        public SizeLimitExceededException(String message, long actual,
                long permitted) {
            super(message, actual, permitted);
        }
    }
1 0 0 0 0 0
checked (Domain) SkipPageException
public class SkipPageException extends JspException {

    private static final long serialVersionUID = 1L;

    /**
     * Creates a SkipPageException with no message.
     */
    public SkipPageException() {
        super();
    }

    /**
     * Creates a SkipPageException with the provided message.
     *
     * @param message
     *            the detail message
     */
    public SkipPageException(String message) {
        super(message);
    }

    /**
     * Creates a SkipPageException with the provided message and root cause.
     *
     * @param message
     *            the detail message
     * @param rootCause
     *            the originating cause of this exception
     */
    public SkipPageException(String message, Throwable rootCause) {
        super(message, rootCause);
    }

    /**
     * Creates a SkipPageException with the provided root cause.
     *
     * @param rootCause
     *            the originating cause of this exception
     */
    public SkipPageException(Throwable rootCause) {
        super(rootCause);
    }
}
0 0 0 0 0 0
unknown (Lib) SocketException 2
            
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
protected void handShake() throws IOException { if( ssl.getWantClientAuth() ) { log.debug(sm.getString("jsseSupport.noCertWant")); } else { ssl.setNeedClientAuth(true); } if (ssl.getEnabledCipherSuites().length == 0) { // Handshake is never going to be successful. // Assume this is because handshakes are disabled log.warn(sm.getString("jsseSupport.serverRenegDisabled")); session.invalidate(); ssl.close(); return; } InputStream in = ssl.getInputStream(); int oldTimeout = ssl.getSoTimeout(); ssl.setSoTimeout(1000); byte[] b = new byte[1]; listener.reset(); ssl.startHandshake(); int maxTries = 60; // 60 * 1000 = example 1 minute time out for (int i = 0; i < maxTries; i++) { if (log.isTraceEnabled()) log.trace("Reading for try #" + i); try { int read = in.read(b); if (read > 0) { // Shouldn't happen as all input should have been swallowed // before trying to do the handshake. If it does, something // went wrong so lets bomb out now. throw new SSLException( sm.getString("jsseSupport.unexpectedData")); } } catch(SSLException sslex) { log.info(sm.getString("jsseSupport.clientCertError"), sslex); throw sslex; } catch (IOException e) { // ignore - presumably the timeout } if (listener.completed) { break; } } ssl.setSoTimeout(oldTimeout); if (listener.completed == false) { throw new SocketException("SSL Cert handshake timeout"); } }
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
Override public Socket acceptSocket(ServerSocket socket) throws IOException { SSLSocket asock = null; try { asock = (SSLSocket)socket.accept(); } catch (SSLException e){ throw new SocketException("SSL handshake error" + e.toString()); } return asock; }
1
            
// in java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
catch (SSLException e){ throw new SocketException("SSL handshake error" + e.toString()); }
3
            
// in java/org/apache/tomcat/util/net/SocketProperties.java
public void setProperties(Socket socket) throws SocketException{ if (rxBufSize != null) socket.setReceiveBufferSize(rxBufSize.intValue()); if (txBufSize != null) socket.setSendBufferSize(txBufSize.intValue()); if (ooBInline !=null) socket.setOOBInline(ooBInline.booleanValue()); if (soKeepAlive != null) socket.setKeepAlive(soKeepAlive.booleanValue()); if (performanceConnectionTime != null && performanceLatency != null && performanceBandwidth != null) socket.setPerformancePreferences( performanceConnectionTime.intValue(), performanceLatency.intValue(), performanceBandwidth.intValue()); if (soReuseAddress != null) socket.setReuseAddress(soReuseAddress.booleanValue()); if (soLingerOn != null && soLingerTime != null) socket.setSoLinger(soLingerOn.booleanValue(), soLingerTime.intValue()); if (soTimeout != null && soTimeout.intValue() >= 0) socket.setSoTimeout(soTimeout.intValue()); if (tcpNoDelay != null) socket.setTcpNoDelay(tcpNoDelay.booleanValue()); if (soTrafficClass != null) socket.setTrafficClass(soTrafficClass.intValue()); }
// in java/org/apache/tomcat/util/net/SocketProperties.java
public void setProperties(ServerSocket socket) throws SocketException{ if (rxBufSize != null) socket.setReceiveBufferSize(rxBufSize.intValue()); if (performanceConnectionTime != null && performanceLatency != null && performanceBandwidth != null) socket.setPerformancePreferences( performanceConnectionTime.intValue(), performanceLatency.intValue(), performanceBandwidth.intValue()); if (soReuseAddress != null) socket.setReuseAddress(soReuseAddress.booleanValue()); if (soTimeout != null && soTimeout.intValue() >= 0) socket.setSoTimeout(soTimeout.intValue()); }
// in java/org/apache/catalina/tribes/transport/nio/NioSender.java
private void completeConnect() throws SocketException { //we connected, register ourselves for writing setConnected(true); connecting = false; setRequestCount(0); setConnectTime(System.currentTimeMillis()); if (socketChannel!=null) { socketChannel.socket().setSendBufferSize(getTxBufSize()); socketChannel.socket().setReceiveBufferSize(getRxBufSize()); socketChannel.socket().setSoTimeout((int)getTimeout()); socketChannel.socket().setSoLinger(getSoLingerOn(),getSoLingerOn()?getSoLingerTime():0); socketChannel.socket().setTcpNoDelay(getTcpNoDelay()); socketChannel.socket().setKeepAlive(getSoKeepAlive()); socketChannel.socket().setReuseAddress(getSoReuseAddress()); socketChannel.socket().setOOBInline(getOoBInline()); socketChannel.socket().setSoLinger(getSoLingerOn(),getSoLingerTime()); socketChannel.socket().setTrafficClass(getSoTrafficClass()); } else if (dataChannel!=null) { dataChannel.socket().setSendBufferSize(getUdpTxBufSize()); dataChannel.socket().setReceiveBufferSize(getUdpRxBufSize()); dataChannel.socket().setSoTimeout((int)getTimeout()); dataChannel.socket().setReuseAddress(getSoReuseAddress()); dataChannel.socket().setTrafficClass(getSoTrafficClass()); } }
2
            
// in java/org/apache/coyote/AbstractProtocol.java
catch(java.net.SocketException e) { // SocketExceptions are normal getLog().debug(sm.getString( "ajpprotocol.proto.socketexception.debug"), e); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (SocketException s) { //error here is common if the client has reset the connection if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.err.unexpected"), s); } // Close the socket return false; }
0 0
unknown (Lib) SocketTimeoutException 6
            
// in java/org/apache/coyote/http11/InternalAprInputBuffer.java
protected boolean fill() throws IOException { int nRead = 0; if (parsingHeader) { if (lastValid == buf.length) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.EAGAIN) { return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } else { if (buf.length - end < 4500) { // In this case, the request header was really large, so we allocate a // brand new one; the old one will get GCed when subsequent requests // clear all references buf = new byte[buf.length]; end = 0; } pos = end; lastValid = pos; bbuf.clear(); nRead = Socket.recvbb(socket, 0, buf.length - lastValid); if (nRead > 0) { bbuf.limit(nRead); bbuf.get(buf, pos, nRead); lastValid = pos + nRead; } else { if ((-nRead) == Status.ETIMEDOUT || (-nRead) == Status.TIMEUP) { throw new SocketTimeoutException(sm.getString("iib.failedread")); } else if (nRead == 0) { // APR_STATUS_IS_EOF, since native 1.1.22 return false; } else { throw new IOException(sm.getString("iib.failedread")); } } } return (nRead > 0); }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int write(ByteBuffer buf, NioChannel socket, long writeTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int written = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) && buf.hasRemaining()) { if (keycount > 0) { //only write if we were registered for a write int cnt = socket.write(buf); //write the data if (cnt == -1) throw new EOFException(); written += cnt; if (cnt > 0) { time = System.currentTimeMillis(); //reset our timeout timer continue; //we successfully wrote, try again without a selector } } try { if ( att.getWriteLatch()==null || att.getWriteLatch().getCount()==0) att.startWriteLatch(1); poller.add(att,SelectionKey.OP_WRITE,reference); if (writeTimeout < 0) { att.awaitWriteLatch(Long.MAX_VALUE,TimeUnit.MILLISECONDS); } else { att.awaitWriteLatch(writeTimeout,TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getWriteLatch()!=null && att.getWriteLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetWriteLatch(); } if (writeTimeout > 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= writeTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_WRITE); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return written; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
public int read(ByteBuffer buf, NioChannel socket, long readTimeout) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyReference reference = new KeyReference(); KeyAttachment att = (KeyAttachment) key.attachment(); int read = 0; boolean timedout = false; int keycount = 1; //assume we can read long time = System.currentTimeMillis(); //start the timeout timer try { while(!timedout) { if (keycount > 0) { //only read if we were registered for a read read = socket.read(buf); if (read == -1) throw new EOFException(); if (read > 0) break; } try { if ( att.getReadLatch()==null || att.getReadLatch().getCount()==0) att.startReadLatch(1); poller.add(att,SelectionKey.OP_READ, reference); if (readTimeout < 0) { att.awaitReadLatch(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } else { att.awaitReadLatch(readTimeout, TimeUnit.MILLISECONDS); } }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getReadLatch()!=null && att.getReadLatch().getCount()> 0) { //we got interrupted, but we haven't received notification from the poller. keycount = 0; }else { //latch countdown has happened keycount = 1; att.resetReadLatch(); } if (readTimeout >= 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= readTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_READ); if (timedout && reference.key!=null) { poller.cancelKey(reference.key); } reference.key = null; } return read; }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int write(ByteBuffer buf, NioChannel socket, Selector selector, long writeTimeout, boolean block) throws IOException { if ( SHARED && block ) { return blockingSelector.write(buf,socket,writeTimeout); } SelectionKey key = null; int written = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) && buf.hasRemaining() ) { int cnt = 0; if ( keycount > 0 ) { //only write if we were registered for a write cnt = socket.write(buf); //write the data if (cnt == -1) throw new EOFException(); written += cnt; if (cnt > 0) { time = System.currentTimeMillis(); //reset our timeout timer continue; //we successfully wrote, try again without a selector } if (cnt==0 && (!block)) break; //don't block } if ( selector != null ) { //register OP_WRITE to the selector if (key==null) key = socket.getIOChannel().register(selector, SelectionKey.OP_WRITE); else key.interestOps(SelectionKey.OP_WRITE); keycount = selector.select(writeTimeout); } if (writeTimeout > 0 && (selector == null || keycount == 0) ) timedout = (System.currentTimeMillis()-time)>=writeTimeout; }//while if ( timedout ) throw new SocketTimeoutException(); } finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } } return written; }
// in java/org/apache/tomcat/util/net/NioSelectorPool.java
public int read(ByteBuffer buf, NioChannel socket, Selector selector, long readTimeout, boolean block) throws IOException { if ( SHARED && block ) { return blockingSelector.read(buf,socket,readTimeout); } SelectionKey key = null; int read = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) ) { int cnt = 0; if ( keycount > 0 ) { //only read if we were registered for a read cnt = socket.read(buf); if (cnt == -1) throw new EOFException(); read += cnt; if (cnt > 0) continue; //read some more if (cnt==0 && (read>0 || (!block) ) ) break; //we are done reading } if ( selector != null ) {//perform a blocking read //register OP_WRITE to the selector if (key==null) key = socket.getIOChannel().register(selector, SelectionKey.OP_READ); else key.interestOps(SelectionKey.OP_READ); keycount = selector.select(readTimeout); } if (readTimeout > 0 && (selector == null || keycount == 0) ) timedout = (System.currentTimeMillis()-time)>=readTimeout; }//while if ( timedout ) throw new SocketTimeoutException(); } finally { if (key != null) { key.cancel(); if (selector != null) selector.selectNow();//removes the key from this selector } } return read; }
0 0 4
            
// in java/org/apache/tomcat/spdy/NetSupportSocket.java
catch (SocketTimeoutException ex) { return 0; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (SocketTimeoutException sx) { // Ignore: Normal condition }
// in java/org/apache/catalina/tribes/group/interceptors/TcpFailureDetector.java
catch ( SocketTimeoutException sx) { //do nothing, we couldn't connect }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (SocketTimeoutException x ) { //do nothing, this is normal, we don't want to block forever //since the receive thread is the same thread //that does membership expiration }
0 0
unknown (Lib) StringIndexOutOfBoundsException 0 0 0 4
            
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should not occur System.err.println(e); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid signature: " + signature, e); }
// in java/javax/servlet/http/HttpUtils.java
catch (StringIndexOutOfBoundsException e) { String rest = s.substring(i); sb.append(rest); if (rest.length()==2) i++; }
2
            
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); }
// in java/org/apache/tomcat/util/bcel/classfile/Utility.java
catch (StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid signature: " + signature, e); }
2
checked (Lib) Throwable 0 0 4
            
// in java/org/apache/naming/factory/webservices/ServiceProxy.java
Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (portQNameClass.equals(method)) { return getProxyPortQNameClass(args); } if (portClass.equals(method)) { return getProxyPortClass(args); } try { return method.invoke(service, args); } catch (InvocationTargetException ite) { throw ite.getTargetException(); } }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("getConnection".equals(method.getName()) && (args==null || args.length==0)) { args = new String[] {username,password}; method = getConnection; } else if ("unwrap".equals(method.getName())) { return unwrap((Class<?>)args[0]); } try { return method.invoke(ds,args); }catch (Throwable t) { if (t instanceof InvocationTargetException && t.getCause() != null) { throw t.getCause(); } else { throw t; } } }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
private Object invokeMethod(ApplicationContext appContext, final String methodName, Object[] params) throws Throwable{ try{ Method method = objectCache.get(methodName); if (method == null){ method = appContext.getClass() .getMethod(methodName, classCache.get(methodName)); objectCache.put(methodName, method); } return executeMethod(method,appContext,params); } catch (Exception ex){ handleException(ex); return null; } finally { params = null; } }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
private void handleException(Exception ex) throws Throwable { Throwable realException; if (ex instanceof PrivilegedActionException) { ex = ((PrivilegedActionException) ex).getException(); } if (ex instanceof InvocationTargetException) { realException = ex.getCause(); if (realException == null) { realException = ex; } } else { realException = ex; } throw realException; }
305
            
// in java/org/apache/jasper/runtime/JspFactoryImpl.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.fatal("Exception initializing page context", ex); return null; }
// in java/org/apache/jasper/compiler/ImplicitTagLibraryInfo.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/jasper/compiler/ParserController.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/jasper/compiler/Localizer.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); t.printStackTrace(); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/jasper/compiler/TldLocationsCache.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/jasper/compiler/JspReader.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.error("Exception parsing file ", ex); // Pop state being constructed: popFile(); err.jspError("jsp.error.file.cannot.read", file); }
// in java/org/apache/jasper/compiler/JspRuntimeContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); jsw.getServletContext().log("Background compile failed", t); }
// in java/org/apache/jasper/servlet/JspCServletContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (null); }
// in java/org/apache/jasper/servlet/JspCServletContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); url = null; }
// in java/org/apache/jasper/servlet/JspCServletContext.java
catch (Throwable t2) { ExceptionUtils.handleThrowable(t2); }
// in java/org/apache/jasper/servlet/JspCServletContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (null); }
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); // Need to localize this. log.warn("Failed to load engineOptionsClass", e); // Use the default Options implementation options = new EmbeddedServletOptions(config, context); }
// in java/org/apache/jasper/servlet/JspServlet.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException(e); }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
catch (Throwable t) { if (t instanceof InvocationTargetException && t.getCause() != null) { throw t.getCause(); } else { throw t; } }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(Throwable t) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(Throwable t) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/juli/logging/DirectJDKLog.java
catch( Throwable t ) { }
// in java/org/apache/juli/logging/DirectJDKLog.java
catch( Throwable t ) { // maybe it wasn't included - the ugly default will be used. }
// in java/org/apache/coyote/AbstractProtocol.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); // any other exception or error is odd. Here we log it // with "ERROR" level, so it will show up even on // less-than-verbose logs. getLog().error(sm.getString("ajpprotocol.proto.error"), e); }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpAprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpNioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; }
// in java/org/apache/coyote/ajp/AbstractAjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/ajp/AjpProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; }
// in java/org/apache/coyote/http11/Http11AprProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/Http11NioProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), t); } // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug(sm.getString( "http11processor.request.prepare"), t); } // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString( "http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.finish"), t); // 500 - Internal Server Error // Can't add a 500 to the access log since that has already been // written in the Adapter.service method. response.setStatus(500); error = true; }
// in java/org/apache/coyote/http11/AbstractHttp11Processor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.response.finish"), t); error = true; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error t.printStackTrace(); response.setStatus(500); adapter.log(request, response, 0); error = true; }
// in java/org/apache/coyote/spdy/SpdyProcessor.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; }
// in java/org/apache/tomcat/jni/SSLExt.java
catch (Throwable t) { t.printStackTrace(); return -1; }
// in java/org/apache/tomcat/jni/SSLExt.java
catch (Throwable t) { // ignore return false; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable e) { apr.reset(); e.printStackTrace(); throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable t) { throw new IOException(t); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable e) { e.printStackTrace(); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable t) { log.log(Level.SEVERE, "endpoint.poll.error", t); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable t) { t.printStackTrace(); if (pollTime > FALLBACK_POLL_TIME) { pollTime = FALLBACK_POLL_TIME; } }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable t) { throw new IOException(t); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable t) { t.printStackTrace(); // no error handler yet reset(); notifyError(t, false); return; }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable e) { log.log(Level.SEVERE, this + " error ", e); reset(); // no notifyIO - just did it. }
// in java/org/apache/tomcat/jni/Library.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } String name = System.mapLibraryName(NAMES[i]); String path = System.getProperty("java.library.path"); String sep = System.getProperty("path.separator"); String [] paths = path.split(sep); for (int j=0; j<paths.length; j++) { java.io.File fd = new java.io.File(paths[j] , name); if (fd.exists()) { t.printStackTrace(); } } if ( i > 0) err.append(", "); err.append(t.getMessage()); }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { t.printStackTrace(); trace("< onData-ERROR() " + lastChannel); abort("Error processing socket" + t); return CLOSE; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { abort("Error handling frame"); t.printStackTrace(); return CLOSE; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { log.log(Level.SEVERE, "Error parsing head SYN_STREAM", t); abort("Error reading headers " + t); return CLOSE; }
// in java/org/apache/tomcat/spdy/SpdyConnection.java
catch (Throwable t) { log.info("Error parsing head SYN_STREAM" + t); abort("Error reading headers " + t); return CLOSE; }
// in java/org/apache/tomcat/spdy/SpdyContext.java
catch (Throwable t) { // ignore, openssl not supported }
// in java/org/apache/tomcat/spdy/SpdyContext.java
catch (Throwable t) { // ignore, npn not supported }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch (Throwable x) { ExceptionUtils.handleThrowable(x); log.error("",x); continue; }
// in java/org/apache/tomcat/util/net/NioBlockingSelector.java
catch ( Throwable t ) { log.error("",t); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); System.err.println(oomParachuteMsg); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { log.error("",t); } catch (Throwable tt) { ExceptionUtils.handleThrowable(t); } // Tell to close the socket return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable tt) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable oomt ) { try { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.accept.fail"), t); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable x ) { log.error("",x); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); if (log.isDebugEnabled()) log.error("",e); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable x) { ExceptionUtils.handleThrowable(x); log.error("",x); continue; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("",t); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable t ) { log.error("",t); cancelledKey(sk, SocketStatus.ERROR); return false; }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (OutOfMemoryError oom) { try { oomParachuteData = null; socket.getPoller().cancelledKey(key,SocketStatus.ERROR); releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); }
// in java/org/apache/tomcat/util/net/NioEndpoint.java
catch ( Throwable t ) { log.error("",t); socket.getPoller().cancelledKey(key,SocketStatus.ERROR); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { if (step == 2) { log.debug(sm.getString("endpoint.err.handshake"), t); } else { log.debug(sm.getString("endpoint.err.unexpected"), t); } } // Tell to close the socket return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (running) { String msg = sm.getString("endpoint.accept.fail"); if (t instanceof Error) { Error e = (Error) t; if (e.getError() == 233) { // Not an error on HP-UX so log as a warning // so it can be filtered out on that platform // See bug 50273 log.warn(msg, t); } else { log.error(msg, t); } } else { log.error(msg, t); } } }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.poll.error"), t); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.poll.error"), t); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.accept.fail"), t); }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.err.handshake"), t); } // Tell to close the socket state = SocketState.CLOSED; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.err.unexpected"), t); // Close the socket return false; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/JIoEndpoint.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; }
// in java/org/apache/tomcat/util/net/jsse/JSSESupport.java
catch( Throwable t ) { log.debug(sm.getString("jsseSupport.clientCertError"), t); return null; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/tomcat/util/modeler/Registry.java
catch( Throwable t ) { log.error( "Error unregistering mbean ", t); }
// in java/org/apache/tomcat/util/digester/Digester.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); LogFactory.getLog("org.apache.tomcat.util.digester.Digester"). error("Unable to load property source["+className+"].",t); }
// in java/org/apache/el/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte004) { if (jjtc004) { jjtree.clearNodeScope(jjtn004); jjtc004 = false; } else { jjtree.popNode(); } if (jjte004 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte004;} } if (jjte004 instanceof ParseException) { {if (true) throw (ParseException)jjte004;} } {if (true) throw (Error)jjte004;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString( "contextConfig.authenticatorInstantiate", authenticatorName), t); ok = false; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), t); return null; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/TldConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployDescriptor.error", contextXml.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployWar.error", war.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployDir.error", dir.getAbsolutePath()), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString ("hostConfig.context.remove", app.name), t); }
// in java/org/apache/catalina/startup/HostConfig.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString ("hostConfig.context.remove", app.name), t); }
// in java/org/apache/catalina/startup/CatalinaProperties.java
catch (Throwable t) { handleThrowable(t); }
// in java/org/apache/catalina/startup/CatalinaProperties.java
catch (Throwable t) { handleThrowable(t); }
// in java/org/apache/catalina/startup/CatalinaProperties.java
catch (Throwable t) { handleThrowable(t); }
// in java/org/apache/catalina/startup/CatalinaProperties.java
catch (Throwable t) { handleThrowable(t); error = t; }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/ExpandWar.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/startup/Catalina.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This will fail on JDK 1.2. Ignoring, as Tomcat can run // fine without the shutdown hook. }
// in java/org/apache/catalina/startup/Catalina.java
catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.error(sm.getString("catalina.shutdownHookFail"), ex); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (Throwable t) { handleThrowable(t); log.error("Class loader creation threw exception", t); System.exit(1); }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (Throwable t) { handleThrowable(t); t.printStackTrace(); return; }
// in java/org/apache/catalina/startup/Bootstrap.java
catch (Throwable t) { // Unwrap the Exception for clearer error reporting if (t instanceof InvocationTargetException && t.getCause() != null) { t = t.getCause(); } handleThrowable(t); t.printStackTrace(); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Class loader creation threw exception", t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Exception creating instance of " + className, t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Exception locating main() method", t); System.exit(1); }
// in java/org/apache/catalina/startup/Tool.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error("Exception calling main() method", t); System.exit(1); }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch(Throwable t) { // Ignore }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in class " + clazz.getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not clean fields for class " + clazz.getName(), t); } }
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in object instance of class " + instance.getClass().getName(), t); } }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This is likely a dual registration log.info("Dual registration of jndi stream handler: " + t.getMessage()); }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error( "LifecycleException ", t ); throw new LifecycleException("start: ", t); }
// in java/org/apache/catalina/realm/UserDatabaseRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); containerLog.error(sm.getString("userDatabaseRealm.lookup", resourceName), e); database = null; }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("jaasRealm.unexpectedError"), e); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("jaasRealm.unexpectedError"), e); return (null); }
// in java/org/apache/catalina/realm/JAASRealm.java
catch( Throwable t) { log.error( "error ", t); return null; }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Error getting attribute " + oname + " " + attName, t); continue; }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); sb.append("NON-STRINGABLE VALUE"); }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/mbeans/MBeanDumper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/StatusTransformer.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.install[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.reload[" + cn.getDisplayName() + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.resources[" + type + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); return; }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.resources[" + type + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log("ManagerServlet.serverinfo",t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.sessions[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log(sm.getString("managerServlet.startFailed", displayPath), t); writer.println(smClient.getString("managerServlet.startFailed", displayPath)); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.stop[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.undeploy[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/manager/ManagerServlet.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/tribes/group/GroupChannel.java
catch ( Throwable x ) { clazz = MessageDispatchInterceptor.class; }
// in java/org/apache/catalina/tribes/io/BufferPool.java
catch ( Throwable x ) { log.warn("Unable to initilize BufferPool, not pooling XByteBuffer objects:"+x.getMessage()); if ( log.isDebugEnabled() ) log.debug("Unable to initilize BufferPool, not pooling XByteBuffer objects:",x); }
// in java/org/apache/catalina/tribes/transport/nio/NioReplicationTask.java
catch ( Throwable t ) {}
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } log.error("Unable to process request in NioReceiver", t); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } log.error("Unable to receive broadcast message.",t); }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardManager.managerLoad"), t); }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardManager.managerUnload"), t); }
// in java/org/apache/catalina/session/StandardManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/JDBCStore.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionCreated", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent( "afterSessionDestroyed", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.sessionEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t){ manager.getContainer().getLogger().error (sm.getString("standardSession.bindingEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); manager.getContainer().getLogger().error (sm.getString("standardSession.bindingEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { if (unbound != null) { context.fireContainerEvent( "afterSessionAttributeReplaced", listener); } else { context.fireContainerEvent("afterSessionAttributeAdded", listener); } } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/session/StandardSession.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { context.fireContainerEvent("afterSessionAttributeRemoved", listener); } catch (Exception e) { // Ignore } manager.getContainer().getLogger().error (sm.getString("standardSession.attributeEvent"), t); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (Throwable tt) { ExceptionUtils.handleThrowable(tt); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/valves/ErrorReportValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("status.setContentType", t); } }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("accessLogValve.rotateFail"), e); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.info(sm.getString("accessLogValve.closeFail"), e); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); init = "127.0.0.1"; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* Log error */ return "-"; }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); value = "localhost"; }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardLoginFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); }
// in java/org/apache/catalina/authenticator/FormAuthenticator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardErrorFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("deltaManager.managerLoad"), t); }
// in java/org/apache/catalina/ha/session/DeltaManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOn.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new LifecycleException( "ClusterSingleSignOn exception during clusterLoad " + t); }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
catch (Throwable ignore) { ExceptionUtils.handleThrowable(ignore); }
// in java/org/apache/catalina/ssi/ResponseIncludeWrapper.java
catch (Throwable ignore) { ExceptionUtils.handleThrowable(ignore); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("coyoteRequest.sessionEndAccessFail"), t); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); }
// in java/org/apache/catalina/connector/Request.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (!(t instanceof IOException)) { log.error(sm.getString("coyoteAdapter.service"), t); } error = true; return false; }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); success = false; log.error(sm.getString("coyoteAdapter.service"), t); }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("coyoteAdapter.accesslogFail"), t); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error(sm.getString("aprListener.sslInit"), t); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.info(sm.getString("aprListener.aprDestroy")); }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.info(sm.getString("aprListener.aprInit", System.getProperty("java.library.path"))); return; }
// in java/org/apache/catalina/core/AprLifecycleListener.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } }
// in java/org/apache/catalina/core/StandardHost.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString( "standardHost.invalidErrorReportValveClass", errorValve), t); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (null); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.fireContainerEvent("afterContextAttributeRemoved", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); }
// in java/org/apache/catalina/core/ApplicationContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (replaced) context.fireContainerEvent("afterContextAttributeReplaced", listener); else context.fireContainerEvent("afterContextAttributeAdded", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); }
// in java/org/apache/catalina/core/ContainerBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Exception invoking periodic operation: ", t); }
// in java/org/apache/catalina/core/DefaultInstanceManager.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/JasperListener.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // Should not occur, obviously log.warn("Couldn't initialize Jasper", t); }
// in java/org/apache/catalina/core/StandardServer.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(t); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch(Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof MalformedURLException){ throw (MalformedURLException)t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch(Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage(), t); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); throwable(request, response, t); }
// in java/org/apache/catalina/core/StandardHostValve.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); // Report our failure to process this custom page container.getLogger().error("Exception Processing " + errorPage, t); return (false); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); this.charsetMapper = new CharsetMapper(); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.filterStart", name), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.applicationListener", listeners[i]), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextInitialized", listener); getLogger().error (sm.getString("standardContext.listenerStart", instances[i].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextDestroyed", listener); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardContext.resourcesStart"), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardContext.resourcesStop"), t); ok = false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[i].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/StandardContext.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[j].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; }
// in java/org/apache/catalina/core/StandardPipeline.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (false); }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servlet = null; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e); // FIXME: Exception handling needs to be similar to what is in the StandardWrapperValue }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); servletException = new ServletException (sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e); }
// in java/org/apache/catalina/util/CharsetMapper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new IllegalArgumentException(t.toString()); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.startFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.stopFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/util/ExtensionValidator.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
// in java/org/apache/catalina/util/ServerInfo.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); }
126
            
// in java/org/apache/jasper/servlet/JspServlet.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException(e); }
// in java/org/apache/naming/factory/ResourceEnvFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/DataSourceLinkFactory.java
catch (Throwable t) { if (t instanceof InvocationTargetException && t.getCause() != null) { throw t.getCause(); } else { throw t; } }
// in java/org/apache/naming/factory/ResourceFactory.java
catch(Throwable t) { NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(Throwable t) { NamingException ex = new NamingException ("Could not load resource factory class"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/EjbFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/naming/factory/TransactionFactory.java
catch(Throwable t) { if (t instanceof NamingException) throw (NamingException) t; NamingException ex = new NamingException ("Could not create resource factory instance"); ex.initCause(t); throw ex; }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable e) { apr.reset(); e.printStackTrace(); throw new IOException(e); }
// in java/org/apache/tomcat/jni/socket/AprSocketContext.java
catch (Throwable t) { throw new IOException(t); }
// in java/org/apache/tomcat/jni/socket/AprSocket.java
catch (Throwable t) { throw new IOException(t); }
// in java/org/apache/tomcat/jni/Library.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } String name = System.mapLibraryName(NAMES[i]); String path = System.getProperty("java.library.path"); String sep = System.getProperty("path.separator"); String [] paths = path.split(sep); for (int j=0; j<paths.length; j++) { java.io.File fd = new java.io.File(paths[j] , name); if (fd.exists()) { t.printStackTrace(); } } if ( i > 0) err.append(", "); err.append(t.getMessage()); }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/SimpleCharStream.java
catch (Throwable t) { throw new Error(t.getMessage()); }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte004) { if (jjtc004) { jjtree.clearNodeScope(jjtn004); jjtc004 = false; } else { jjtree.popNode(); } if (jjte004 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte004;} } if (jjte004 instanceof ParseException) { {if (true) throw (ParseException)jjte004;} } {if (true) throw (Error)jjte004;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte003) { if (jjtc003) { jjtree.clearNodeScope(jjtn003); jjtc003 = false; } else { jjtree.popNode(); } if (jjte003 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte003;} } if (jjte003 instanceof ParseException) { {if (true) throw (ParseException)jjte003;} } {if (true) throw (Error)jjte003;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/el/parser/ELParser.java
catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error( "LifecycleException ", t ); throw new LifecycleException("start: ", t); }
// in java/org/apache/catalina/realm/JDBCRealm.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
// in java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } log.error("Unable to process request in NioReceiver", t); }
// in java/org/apache/catalina/tribes/membership/McastServiceImpl.java
catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } log.error("Unable to receive broadcast message.",t); }
// in java/org/apache/catalina/valves/JDBCAccessLogValve.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new SQLException(e.getMessage(), e); }
// in java/org/apache/catalina/ha/authenticator/ClusterSingleSignOn.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new LifecycleException( "ClusterSingleSignOn exception during clusterLoad " + t); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, request, response, e); throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); /*if (filter != null) support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT, filter, event, e);*/ throw new ServletException (sm.getString("filterChain.filter"), e); }
// in java/org/apache/catalina/core/ApplicationFilterChain.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); /* support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, servlet, request, response, e); */ throw new ServletException (sm.getString("filterChain.servlet"), e); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch(Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof MalformedURLException){ throw (MalformedURLException)t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch(Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage(), t); }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Exception ex){ try { handleException(ex); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; }
// in java/org/apache/catalina/core/ApplicationContextFacade.java
catch (Throwable t){ ExceptionUtils.handleThrowable(t); throw new RuntimeException(t.getMessage()); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { ExceptionUtils.handleThrowable(e); throw new ServletException (sm.getString("standardWrapper.allocate"), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); unavailable(null); // Added extra log statement for Bugzilla 36630: // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 if(log.isDebugEnabled()) { log.debug(sm.getString("standardWrapper.instantiate", servletClass), e); } // Restore the context ClassLoader throw new ServletException (sm.getString("standardWrapper.instantiate", servletClass), e); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable f) { ExceptionUtils.handleThrowable(f); getServletContext().log("StandardWrapper.Throwable", f ); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException (sm.getString("standardWrapper.initException", getName()), f); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instanceSupport.fireInstanceEvent (InstanceEvent.AFTER_DESTROY_EVENT, instance, t); instance = null; instancePool = null; nInstances = 0; fireContainerEvent("unload", this); unloading = false; throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); instancePool = null; nInstances = 0; unloading = false; fireContainerEvent("unload", this); throw new ServletException (sm.getString("standardWrapper.destroyException", getName()), t); }
// in java/org/apache/catalina/util/CharsetMapper.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); throw new IllegalArgumentException(t.toString()); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.startFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.stopFail",toString()), t); }
// in java/org/apache/catalina/util/LifecycleBase.java
catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); }
5
unknown (Lib) TokenMgrError 4
            
// in java/org/apache/tomcat/util/http/parser/HttpParserTokenManager.java
public void SwitchTo(int lexState) { if (lexState >= 2 || lexState < 0) throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); else curLexState = lexState; }
// in java/org/apache/tomcat/util/http/parser/HttpParserTokenManager.java
public Token getNextToken() { Token matchedToken; int curPos = 0; EOFLoop : for (;;) { try { curChar = input_stream.BeginToken(); } catch(java.io.IOException e) { jjmatchedKind = 0; matchedToken = jjFillToken(); return matchedToken; } switch(curLexState) { case 0: jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_0(); break; case 1: jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_1(); break; } if (jjmatchedKind != 0x7fffffff) { if (jjmatchedPos + 1 < curPos) input_stream.backup(curPos - jjmatchedPos - 1); matchedToken = jjFillToken(); if (jjnewLexState[jjmatchedKind] != -1) curLexState = jjnewLexState[jjmatchedKind]; return matchedToken; } int error_line = input_stream.getEndLine(); int error_column = input_stream.getEndColumn(); String error_after = null; boolean EOFSeen = false; try { input_stream.readChar(); input_stream.backup(1); } catch (java.io.IOException e1) { EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; } if (!EOFSeen) { input_stream.backup(1); error_after = curPos <= 1 ? "" : input_stream.GetImage(); } throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); } }
// in java/org/apache/el/parser/ELParserTokenManager.java
public void SwitchTo(int lexState) { if (lexState >= 2 || lexState < 0) throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); else curLexState = lexState; }
// in java/org/apache/el/parser/ELParserTokenManager.java
public Token getNextToken() { Token matchedToken; int curPos = 0; EOFLoop : for (;;) { try { curChar = input_stream.BeginToken(); } catch(java.io.IOException e) { jjmatchedKind = 0; matchedToken = jjFillToken(); return matchedToken; } switch(curLexState) { case 0: jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_0(); break; case 1: try { input_stream.backup(0); while (curChar <= 32 && (0x100002600L & (1L << curChar)) != 0L) curChar = input_stream.BeginToken(); } catch (java.io.IOException e1) { continue EOFLoop; } jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_1(); if (jjmatchedPos == 0 && jjmatchedKind > 56) { jjmatchedKind = 56; } break; } if (jjmatchedKind != 0x7fffffff) { if (jjmatchedPos + 1 < curPos) input_stream.backup(curPos - jjmatchedPos - 1); if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) { matchedToken = jjFillToken(); if (jjnewLexState[jjmatchedKind] != -1) curLexState = jjnewLexState[jjmatchedKind]; return matchedToken; } else { if (jjnewLexState[jjmatchedKind] != -1) curLexState = jjnewLexState[jjmatchedKind]; continue EOFLoop; } } int error_line = input_stream.getEndLine(); int error_column = input_stream.getEndColumn(); String error_after = null; boolean EOFSeen = false; try { input_stream.readChar(); input_stream.backup(1); } catch (java.io.IOException e1) { EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; } if (!EOFSeen) { input_stream.backup(1); error_after = curPos <= 1 ? "" : input_stream.GetImage(); } throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); } }
0 0 0 0 0
unknown (Lib) TransformerException 0 0 0 1
            
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (TransformerException e) { throw new ServletException("XSL transformer error", e); }
1
            
// in java/org/apache/catalina/servlets/DefaultServlet.java
catch (TransformerException e) { throw new ServletException("XSL transformer error", e); }
0
unknown (Lib) URISyntaxException 0 0 0 5
            
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
catch (URISyntaxException e) { // Wrap the exception and re-throw IOException ioe = new IOException(); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (URISyntaxException e) { log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName())); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (URISyntaxException e) { log.error(sm.getString("contextConfig.fileUrl", url), e); }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch ( URISyntaxException e ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); }
// in java/org/apache/catalina/core/StandardServer.java
catch (URISyntaxException e) { // Ignore }
2
            
// in java/org/apache/tomcat/util/scan/StandardJarScanner.java
catch (URISyntaxException e) { // Wrap the exception and re-throw IOException ioe = new IOException(); ioe.initCause(e); throw ioe; }
// in java/org/apache/catalina/realm/JNDIRealm.java
catch ( URISyntaxException e ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); }
0
unknown (Lib) UTFDataFormatException 3
            
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
private void expectedByte(int position, int count) throws UTFDataFormatException { throw new UTFDataFormatException( Localizer.getMessage("jsp.error.xml.expectedByte", Integer.toString(position), Integer.toString(count))); }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
private void invalidByte(int position, int count) throws UTFDataFormatException { throw new UTFDataFormatException( Localizer.getMessage("jsp.error.xml.invalidByte", Integer.toString(position), Integer.toString(count))); }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
private void invalidSurrogate(int uuuuu) throws UTFDataFormatException { throw new UTFDataFormatException( Localizer.getMessage("jsp.error.xml.invalidHighSurrogate", Integer.toHexString(uuuuu))); }
0 3
            
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
private void expectedByte(int position, int count) throws UTFDataFormatException { throw new UTFDataFormatException( Localizer.getMessage("jsp.error.xml.expectedByte", Integer.toString(position), Integer.toString(count))); }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
private void invalidByte(int position, int count) throws UTFDataFormatException { throw new UTFDataFormatException( Localizer.getMessage("jsp.error.xml.invalidByte", Integer.toString(position), Integer.toString(count))); }
// in java/org/apache/jasper/xmlparser/UTF8Reader.java
private void invalidSurrogate(int uuuuu) throws UTFDataFormatException { throw new UTFDataFormatException( Localizer.getMessage("jsp.error.xml.invalidHighSurrogate", Integer.toHexString(uuuuu))); }
0 0 0
checked (Domain) UnavailableException
public class UnavailableException extends ServletException {

    private static final long serialVersionUID = 1L;

    private final Servlet servlet; // what's unavailable
    private final boolean permanent; // needs admin action?
    private final int seconds; // unavailability estimate

    /**
     * @param servlet
     *            the <code>Servlet</code> instance that is unavailable
     * @param msg
     *            a <code>String</code> specifying the descriptive message
     * @deprecated As of Java Servlet API 2.2, use
     *             {@link #UnavailableException(String)} instead.
     */
    @SuppressWarnings("dep-ann")
    // Spec API does not use @Deprecated
    public UnavailableException(Servlet servlet, String msg) {
        super(msg);
        this.servlet = servlet;
        permanent = true;
        this.seconds = 0;
    }

    /**
     * @param seconds
     *            an integer specifying the number of seconds the servlet
     *            expects to be unavailable; if zero or negative, indicates that
     *            the servlet can't make an estimate
     * @param servlet
     *            the <code>Servlet</code> that is unavailable
     * @param msg
     *            a <code>String</code> specifying the descriptive message,
     *            which can be written to a log file or displayed for the user.
     * @deprecated As of Java Servlet API 2.2, use
     *             {@link #UnavailableException(String, int)} instead.
     */
    @SuppressWarnings("dep-ann")
    // Spec API does not use @Deprecated
    public UnavailableException(int seconds, Servlet servlet, String msg) {
        super(msg);
        this.servlet = servlet;
        if (seconds <= 0)
            this.seconds = -1;
        else
            this.seconds = seconds;
        permanent = false;
    }
4
            
// in java/org/apache/catalina/manager/host/HostManagerServlet.java
Override public void init() throws ServletException { // Ensure that our ContainerServlet properties have been set if ((wrapper == null) || (context == null)) throw new UnavailableException (sm.getString("hostManagerServlet.noWrapper")); // Set our properties from the initialization parameters String value = null; try { value = getServletConfig().getInitParameter("debug"); debug = Integer.parseInt(value); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } }
// in java/org/apache/catalina/manager/ManagerServlet.java
Override public void init() throws ServletException { // Ensure that our ContainerServlet properties have been set if ((wrapper == null) || (context == null)) throw new UnavailableException( sm.getString("managerServlet.noWrapper")); // Set our properties from the initialization parameters String value = null; try { value = getServletConfig().getInitParameter("debug"); debug = Integer.parseInt(value); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } // Acquire global JNDI resources if available Server server = ((Engine)host.getParent()).getService().getServer(); if (server != null) { global = server.getGlobalNamingContext(); } // Calculate the directory into which we will be deploying applications versioned = (File) getServletContext().getAttribute (ServletContext.TEMPDIR); // Identify the appBase of the owning Host of this Context // (if any) deployed = ((Host) context.getParent()).getAppBaseFile(); configBase = new File(context.getCatalinaBase(), "conf"); Container container = context; Container host = null; Container engine = null; while (container != null) { if (container instanceof Host) host = container; if (container instanceof Engine) engine = container; container = container.getParent(); } if (engine != null) { configBase = new File(configBase, engine.getName()); } if (host != null) { configBase = new File(configBase, host.getName()); } // Note: The directory must exist for this to work. // Log debugging messages as necessary if (debug >= 1) { log("init: Associated with Deployer '" + oname + "'"); if (global != null) { log("init: Global resources are available"); } } }
// in java/org/apache/catalina/servlets/DefaultServlet.java
Override public void init() throws ServletException { if (getServletConfig().getInitParameter("debug") != null) debug = Integer.parseInt(getServletConfig().getInitParameter("debug")); if (getServletConfig().getInitParameter("input") != null) input = Integer.parseInt(getServletConfig().getInitParameter("input")); if (getServletConfig().getInitParameter("output") != null) output = Integer.parseInt(getServletConfig().getInitParameter("output")); listings = Boolean.parseBoolean(getServletConfig().getInitParameter("listings")); if (getServletConfig().getInitParameter("readonly") != null) readOnly = Boolean.parseBoolean(getServletConfig().getInitParameter("readonly")); if (getServletConfig().getInitParameter("sendfileSize") != null) sendfileSize = Integer.parseInt(getServletConfig().getInitParameter("sendfileSize")) * 1024; fileEncoding = getServletConfig().getInitParameter("fileEncoding"); globalXsltFile = getServletConfig().getInitParameter("globalXsltFile"); contextXsltFile = getServletConfig().getInitParameter("contextXsltFile"); localXsltFile = getServletConfig().getInitParameter("localXsltFile"); readmeFile = getServletConfig().getInitParameter("readmeFile"); if (getServletConfig().getInitParameter("useAcceptRanges") != null) useAcceptRanges = Boolean.parseBoolean(getServletConfig().getInitParameter("useAcceptRanges")); // Sanity check on the specified buffer sizes if (input < 256) input = 256; if (output < 256) output = 256; if (debug > 0) { log("DefaultServlet.init: input buffer size=" + input + ", output buffer size=" + output); } // Load the proxy dir context. resources = (ProxyDirContext) getServletContext() .getAttribute(Globals.RESOURCES_ATTR); if (resources == null) { try { resources = (ProxyDirContext) new InitialContext() .lookup(RESOURCES_JNDI_NAME); } catch (NamingException e) { // Failed throw new ServletException("No resources", e); } } if (resources == null) { throw new UnavailableException("No resources"); } }
// in java/org/apache/catalina/servlets/WebdavServlet.java
Override public void init() throws ServletException { super.init(); if (getServletConfig().getInitParameter("secret") != null) secret = getServletConfig().getInitParameter("secret"); if (getServletConfig().getInitParameter("maxDepth") != null) maxDepth = Integer.parseInt( getServletConfig().getInitParameter("maxDepth")); if (getServletConfig().getInitParameter("allowSpecialPaths") != null) allowSpecialPaths = Boolean.parseBoolean( getServletConfig().getInitParameter("allowSpecialPaths")); // Load the MD5 helper used to calculate signatures. try { md5Helper = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new UnavailableException("No MD5"); } }
1
            
// in java/org/apache/catalina/servlets/WebdavServlet.java
catch (NoSuchAlgorithmException e) { throw new UnavailableException("No MD5"); }
0 7
            
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error( sm.getString("standardWrapper.allocateException", wrapper.getName()), e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { // The response is already committed, so it's not possible to do anything }
// in java/org/apache/catalina/core/StandardWrapperValve.java
catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (UnavailableException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); unavailable(f); throw f; }
// in java/org/apache/catalina/core/ApplicationDispatcher.java
catch (UnavailableException e) { support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response); wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e); servletException = e; wrapper.unavailable(e); }
2
            
// in java/org/apache/jasper/servlet/JspServletWrapper.java
catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError (HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); }
// in java/org/apache/catalina/core/StandardWrapper.java
catch (UnavailableException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); unavailable(f); throw f; }
0
unknown (Lib) UnknownHostException 0 0 1
            
// in java/org/apache/catalina/tribes/transport/AbstractSender.java
public void setDestination(Member destination) throws UnknownHostException { this.destination = destination; this.address = InetAddress.getByAddress(destination.getHost()); this.port = destination.getPort(); this.udpPort = destination.getUdpPort(); }
6
            
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (UnknownHostException exc) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Unable to resolve host name:" + value); ok = false; }
// in java/org/apache/tomcat/util/IntrospectionUtils.java
catch (UnknownHostException exc) { if (log.isDebugEnabled()) log.debug("IntrospectionUtils: Unable to resolve host name:" + object); }
// in java/org/apache/catalina/ant/jmx/JMXAccessorTask.java
catch (UnknownHostException exc) { if (isEcho()) handleErrorOutput("Unable to resolve host name:" + value); }
// in java/org/apache/catalina/manager/HTMLManagerServlet.java
catch (UnknownHostException e) { args[6] = "-"; args[7] = "-"; }
// in java/org/apache/catalina/manager/StatusManagerServlet.java
catch (UnknownHostException e) { args[6] = "-"; args[7] = "-"; }
// in java/org/apache/catalina/tribes/transport/nio/ParallelNioSender.java
catch ( UnknownHostException x ) { if (cx == null) cx = new ChannelException("Unable to setup NioSender.", x); cx.addFaultyMember(destination[i], x); }
0 0
unknown (Lib) UnmappableCharacterException 0 0 0 1
            
// in java/org/apache/catalina/websocket/StreamInbound.java
catch (UnmappableCharacterException uce) { // Invalid UTF-8 closeOutboundConnection(Constants.STATUS_BAD_DATA, null); return SocketState.CLOSED; }
0 0
unknown (Lib) UnsatisfiedLinkError 3
            
// in java/org/apache/tomcat/jni/Library.java
public static boolean initialize(String libraryName) throws Exception { if (_instance == null) { if (libraryName == null) _instance = new Library(); else _instance = new Library(libraryName); TCN_MAJOR_VERSION = version(0x01); TCN_MINOR_VERSION = version(0x02); TCN_PATCH_VERSION = version(0x03); TCN_IS_DEV_VERSION = version(0x04); APR_MAJOR_VERSION = version(0x11); APR_MINOR_VERSION = version(0x12); APR_PATCH_VERSION = version(0x13); APR_IS_DEV_VERSION = version(0x14); APR_SIZEOF_VOIDP = size(1); APR_PATH_MAX = size(2); APRMAXHOSTLEN = size(3); APR_MAX_IOVEC_SIZE = size(4); APR_MAX_SECS_TO_LINGER = size(5); APR_MMAP_THRESHOLD = size(6); APR_MMAP_LIMIT = size(7); APR_HAVE_IPV6 = has(0); APR_HAS_SHARED_MEMORY = has(1); APR_HAS_THREADS = has(2); APR_HAS_SENDFILE = has(3); APR_HAS_MMAP = has(4); APR_HAS_FORK = has(5); APR_HAS_RANDOM = has(6); APR_HAS_OTHER_CHILD = has(7); APR_HAS_DSO = has(8); APR_HAS_SO_ACCEPTFILTER = has(9); APR_HAS_UNICODE_FS = has(10); APR_HAS_PROC_INVOKED = has(11); APR_HAS_USER = has(12); APR_HAS_LARGE_FILES = has(13); APR_HAS_XTHREAD_FILES = has(14); APR_HAS_OS_UUID = has(15); APR_IS_BIGENDIAN = has(16); APR_FILES_AS_SOCKETS = has(17); APR_CHARSET_EBCDIC = has(18); APR_TCP_NODELAY_INHERITED = has(19); APR_O_NONBLOCK_INHERITED = has(20); if (APR_MAJOR_VERSION < 1) { throw new UnsatisfiedLinkError("Unsupported APR Version (" + aprVersionString() + ")"); } if (!APR_HAS_THREADS) { throw new UnsatisfiedLinkError("Missing APR_HAS_THREADS"); } } return initialize(); }
0 0 2
            
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (UnsatisfiedLinkError e) { throw new Exception(sm.getString("endpoint.init.notavail")); }
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (UnsatisfiedLinkError e) { // Ignore }
1
            
// in java/org/apache/tomcat/util/net/AprEndpoint.java
catch (UnsatisfiedLinkError e) { throw new Exception(sm.getString("endpoint.init.notavail")); }
0
unknown (Lib) UnsupportedCallbackException 2
            
// in java/org/apache/catalina/realm/JAASCallbackHandler.java
Override public void handle(Callback callbacks[]) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof NameCallback) { if (realm.getContainer().getLogger().isTraceEnabled()) realm.getContainer().getLogger().trace(sm.getString("jaasCallback.username", username)); ((NameCallback) callbacks[i]).setName(username); } else if (callbacks[i] instanceof PasswordCallback) { final char[] passwordcontents; if (password != null) { passwordcontents = password.toCharArray(); } else { passwordcontents = new char[0]; } ((PasswordCallback) callbacks[i]).setPassword (passwordcontents); } else if (callbacks[i] instanceof TextInputCallback) { TextInputCallback cb = ((TextInputCallback) callbacks[i]); if (cb.getPrompt().equals("nonce")) { cb.setText(nonce); } else if (cb.getPrompt().equals("nc")) { cb.setText(nc); } else if (cb.getPrompt().equals("cnonce")) { cb.setText(cnonce); } else if (cb.getPrompt().equals("qop")) { cb.setText(qop); } else if (cb.getPrompt().equals("realmName")) { cb.setText(realmName); } else if (cb.getPrompt().equals("md5a2")) { cb.setText(md5a2); } else if (cb.getPrompt().equals("authMethod")) { cb.setText(authMethod); } else { throw new UnsupportedCallbackException(callbacks[i]); } } else { throw new UnsupportedCallbackException(callbacks[i]); } } }
0 1
            
// in java/org/apache/catalina/realm/JAASCallbackHandler.java
Override public void handle(Callback callbacks[]) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof NameCallback) { if (realm.getContainer().getLogger().isTraceEnabled()) realm.getContainer().getLogger().trace(sm.getString("jaasCallback.username", username)); ((NameCallback) callbacks[i]).setName(username); } else if (callbacks[i] instanceof PasswordCallback) { final char[] passwordcontents; if (password != null) { passwordcontents = password.toCharArray(); } else { passwordcontents = new char[0]; } ((PasswordCallback) callbacks[i]).setPassword (passwordcontents); } else if (callbacks[i] instanceof TextInputCallback) { TextInputCallback cb = ((TextInputCallback) callbacks[i]); if (cb.getPrompt().equals("nonce")) { cb.setText(nonce); } else if (cb.getPrompt().equals("nc")) { cb.setText(nc); } else if (cb.getPrompt().equals("cnonce")) { cb.setText(cnonce); } else if (cb.getPrompt().equals("qop")) { cb.setText(qop); } else if (cb.getPrompt().equals("realmName")) { cb.setText(realmName); } else if (cb.getPrompt().equals("md5a2")) { cb.setText(md5a2); } else if (cb.getPrompt().equals("authMethod")) { cb.setText(authMethod); } else { throw new UnsupportedCallbackException(callbacks[i]); } } else { throw new UnsupportedCallbackException(callbacks[i]); } } }
1
            
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (UnsupportedCallbackException e) { throw new LoginException(e.toString()); }
1
            
// in java/org/apache/catalina/realm/JAASMemoryLoginModule.java
catch (UnsupportedCallbackException e) { throw new LoginException(e.toString()); }
0
unknown (Lib) UnsupportedClassVersionError 1
            
// in java/org/apache/catalina/loader/WebappClassLoader.java
protected Class<?> findClassInternal(String name) throws ClassNotFoundException { if (!validate(name)) throw new ClassNotFoundException(name); String tempPath = name.replace('.', '/'); String classPath = tempPath + ".class"; ResourceEntry entry = null; if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, classPath); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, classPath); } if (entry == null) throw new ClassNotFoundException(name); Class<?> clazz = entry.loadedClass; if (clazz != null) return clazz; synchronized (this) { clazz = entry.loadedClass; if (clazz != null) return clazz; if (entry.binaryContent == null) throw new ClassNotFoundException(name); // Looking up the package String packageName = null; int pos = name.lastIndexOf('.'); if (pos != -1) packageName = name.substring(0, pos); Package pkg = null; if (packageName != null) { pkg = getPackage(packageName); // Define the package (if null) if (pkg == null) { try { if (entry.manifest == null) { definePackage(packageName, null, null, null, null, null, null, null); } else { definePackage(packageName, entry.manifest, entry.codeBase); } } catch (IllegalArgumentException e) { // Ignore: normal error due to dual definition of package } pkg = getPackage(packageName); } } if (securityManager != null) { // Checking sealing if (pkg != null) { boolean sealCheck = true; if (pkg.isSealed()) { sealCheck = pkg.isSealed(entry.codeBase); } else { sealCheck = (entry.manifest == null) || !isPackageSealed(packageName, entry.manifest); } if (!sealCheck) throw new SecurityException ("Sealing violation loading " + name + " : Package " + packageName + " is sealed."); } } try { clazz = defineClass(name, entry.binaryContent, 0, entry.binaryContent.length, new CodeSource(entry.codeBase, entry.certificates)); } catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); } entry.loadedClass = clazz; entry.binaryContent = null; entry.source = null; entry.codeBase = null; entry.manifest = null; entry.certificates = null; } return clazz; }
1
            
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); }
0 1
            
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); }
1
            
// in java/org/apache/catalina/loader/WebappClassLoader.java
catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); }
0
unknown (Lib) UnsupportedEncodingException 1
            
// in java/org/apache/tomcat/util/buf/B2CConverter.java
public static Charset getCharset(String enc) throws UnsupportedEncodingException{ // Encoding names should all be ASCII String lowerCaseEnc = enc.toLowerCase(Locale.US); Charset charset = encodingToCharsetCache.get(lowerCaseEnc); if (charset == null) { // Pre-population of the cache means this must be invalid throw new UnsupportedEncodingException( sm.getString("b2cConverter.unknownEncoding", enc)); } return charset; }
0 28
            
// in java/org/apache/jasper/tagplugins/jstl/Util.java
public String getString() throws UnsupportedEncodingException { if (isWriterUsed) return sw.toString(); else if (isStreamUsed) { if (this.charEncoding != null && !this.charEncoding.equals("")) return bos.toString(charEncoding); else return bos.toString("ISO-8859-1"); } else return ""; // target didn't write anything }
// in java/org/apache/jasper/compiler/SmapUtil.java
void addSDE() throws UnsupportedEncodingException, IOException { copy(4 + 2 + 2); // magic min/maj version int constantPoolCountPos = genPos; int constantPoolCount = readU2(); if (log.isDebugEnabled()) log.debug("constant pool count: " + constantPoolCount); writeU2(constantPoolCount); // copy old constant pool return index of SDE symbol, if found sdeIndex = copyConstantPool(constantPoolCount); if (sdeIndex < 0) { // if "SourceDebugExtension" symbol not there add it writeUtf8ForSDE(); // increment the countantPoolCount sdeIndex = constantPoolCount; ++constantPoolCount; randomAccessWriteU2(constantPoolCountPos, constantPoolCount); if (log.isDebugEnabled()) log.debug("SourceDebugExtension not found, installed at: " + sdeIndex); } else { if (log.isDebugEnabled()) log.debug("SourceDebugExtension found at: " + sdeIndex); } copy(2 + 2 + 2); // access, this, super int interfaceCount = readU2(); writeU2(interfaceCount); if (log.isDebugEnabled()) log.debug("interfaceCount: " + interfaceCount); copy(interfaceCount * 2); copyMembers(); // fields copyMembers(); // methods int attrCountPos = genPos; int attrCount = readU2(); writeU2(attrCount); if (log.isDebugEnabled()) log.debug("class attrCount: " + attrCount); // copy the class attributes, return true if SDE attr found (not copied) if (!copyAttrs(attrCount)) { // we will be adding SDE and it isn't already counted ++attrCount; randomAccessWriteU2(attrCountPos, attrCount); if (log.isDebugEnabled()) log.debug("class attrCount incremented"); } writeAttrForSDE(sdeIndex); }
// in java/org/apache/jasper/compiler/SmapUtil.java
int copyConstantPool(int constantPoolCount) throws UnsupportedEncodingException, IOException { int sdeIndex = -1; // copy const pool index zero not in class file for (int i = 1; i < constantPoolCount; ++i) { int tag = readU1(); writeU1(tag); switch (tag) { case 7 : // Class case 8 : // String if (log.isDebugEnabled()) log.debug(i + " copying 2 bytes"); copy(2); break; case 9 : // Field case 10 : // Method case 11 : // InterfaceMethod case 3 : // Integer case 4 : // Float case 12 : // NameAndType if (log.isDebugEnabled()) log.debug(i + " copying 4 bytes"); copy(4); break; case 5 : // Long case 6 : // Double if (log.isDebugEnabled()) log.debug(i + " copying 8 bytes"); copy(8); i++; break; case 1 : // Utf8 int len = readU2(); writeU2(len); byte[] utf8 = readBytes(len); String str = new String(utf8, "UTF-8"); if (log.isDebugEnabled()) log.debug(i + " read class attr -- '" + str + "'"); if (str.equals(nameSDE)) { sdeIndex = i; } writeBytes(utf8); break; default : throw new IOException("unexpected tag: " + tag); } } return sdeIndex; }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, 1, 1, 4096); }
// in java/org/apache/tomcat/util/http/parser/SimpleCharStream.java
public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, startline, startcolumn, 4096); }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
Override public String getString(final String charset) throws UnsupportedEncodingException { return new String(get(), charset); }
// in java/org/apache/tomcat/util/http/fileupload/ByteArrayOutputStream.java
public String toString(String enc) throws UnsupportedEncodingException { return new String(toByteArray(), enc); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
public static Charset getCharset(String enc) throws UnsupportedEncodingException{ // Encoding names should all be ASCII String lowerCaseEnc = enc.toLowerCase(Locale.US); Charset charset = encodingToCharsetCache.get(lowerCaseEnc); if (charset == null) { // Pre-population of the cache means this must be invalid throw new UnsupportedEncodingException( sm.getString("b2cConverter.unknownEncoding", enc)); } return charset; }
// in java/org/apache/el/parser/SimpleCharStream.java
public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); }
// in java/org/apache/el/parser/SimpleCharStream.java
public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, 1, 1, 4096); }
// in java/org/apache/el/parser/SimpleCharStream.java
public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, startline, startcolumn, 4096); }
// in java/org/apache/catalina/realm/RealmBase.java
protected Charset getDigestCharset() throws UnsupportedEncodingException { if (digestEncoding == null) { return B2CConverter.ISO_8859_1; } else { return B2CConverter.getCharset(getDigestEncoding()); } }
// in java/org/apache/catalina/servlets/CGIServlet.java
protected void setupFromRequest(HttpServletRequest req) throws UnsupportedEncodingException { boolean isIncluded = false; // Look to see if this request is an include if (req.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI) != null) { isIncluded = true; } if (isIncluded) { this.contextPath = (String) req.getAttribute( RequestDispatcher.INCLUDE_CONTEXT_PATH); this.servletPath = (String) req.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); this.pathInfo = (String) req.getAttribute( RequestDispatcher.INCLUDE_PATH_INFO); } else { this.contextPath = req.getContextPath(); this.servletPath = req.getServletPath(); this.pathInfo = req.getPathInfo(); } // If getPathInfo() returns null, must be using extension mapping // In this case, pathInfo should be same as servletPath if (this.pathInfo == null) { this.pathInfo = this.servletPath; } // If the request method is GET, POST or HEAD and the query string // does not contain an unencoded "=" this is an indexed query. // The parsed query string becomes the command line parameters // for the cgi command. if (req.getMethod().equals("GET") || req.getMethod().equals("POST") || req.getMethod().equals("HEAD")) { String qs; if (isIncluded) { qs = (String) req.getAttribute( RequestDispatcher.INCLUDE_QUERY_STRING); } else { qs = req.getQueryString(); } if (qs != null && qs.indexOf("=") == -1) { StringTokenizer qsTokens = new StringTokenizer(qs, "+"); while ( qsTokens.hasMoreTokens() ) { cmdLineParameters.add(URLDecoder.decode(qsTokens.nextToken(), parameterEncoding)); } } } }
// in java/org/apache/catalina/connector/Request.java
Override public void setCharacterEncoding(String enc) throws UnsupportedEncodingException { if (usingReader) { return; } // Ensure that the specified encoding is valid byte buffer[] = new byte[1]; buffer[0] = (byte) 'a'; // Confirm that the encoding name is valid B2CConverter.getCharset(enc); // Save the validated encoding coyoteRequest.setCharacterEncoding(enc); }
// in java/org/apache/catalina/connector/RequestFacade.java
Override public void setCharacterEncoding(String env) throws java.io.UnsupportedEncodingException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } request.setCharacterEncoding(env); }
// in java/org/apache/catalina/core/ApplicationPart.java
public String getString(String encoding) throws UnsupportedEncodingException { return fileItem.getString(encoding); }
// in java/org/apache/catalina/util/RequestUtil.java
public static void parseParameters(Map<String,String[]> map, byte[] data, String encoding) throws UnsupportedEncodingException { Charset charset = B2CConverter.getCharset(encoding); if (data != null && data.length > 0) { int ix = 0; int ox = 0; String key = null; String value = null; while (ix < data.length) { byte c = data[ix++]; switch ((char) c) { case '&': value = new String(data, 0, ox, charset); if (key != null) { putMapEntry(map, key, value); key = null; } ox = 0; break; case '=': if (key == null) { key = new String(data, 0, ox, charset); ox = 0; } else { data[ox++] = c; } break; case '+': data[ox++] = (byte)' '; break; case '%': data[ox++] = (byte)((convertHexDigit(data[ix++]) << 4) + convertHexDigit(data[ix++])); break; default: data[ox++] = c; } } //The last value does not end in '&'. So save it now. if (key != null) { value = new String(data, 0, ox, charset); putMapEntry(map, key, value); } } }
// in java/javax/servlet/http/HttpServlet.java
Override public PrintWriter getWriter() throws UnsupportedEncodingException { if (writer == null) { OutputStreamWriter w; w = new OutputStreamWriter(noBody, getCharacterEncoding()); writer = new PrintWriter(w); } return writer; }
// in java/javax/servlet/ServletRequestWrapper.java
Override public void setCharacterEncoding(String enc) throws java.io.UnsupportedEncodingException { this.request.setCharacterEncoding(enc); }
36
            
// in java/org/apache/jasper/runtime/JspRuntimeLibrary.java
catch (java.io.UnsupportedEncodingException ex) { // Use the default encoding? writer = new OutputStreamWriter(buf); }
// in java/org/apache/jasper/compiler/JspUtil.java
catch (UnsupportedEncodingException ex) { err.jspError("jsp.error.unsupported.encoding", encoding); }
// in java/org/apache/jasper/compiler/Compiler.java
catch (UnsupportedEncodingException ex) { errDispatcher.jspError("jsp.error.needAlternateJavaEncoding", javaEncoding); }
// in java/org/apache/juli/FileHandler.java
catch (UnsupportedEncodingException ex) { // Ignore }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/tomcat/util/http/Parameters.java
catch (UnsupportedEncodingException e) { return DEFAULT_CHARSET; }
// in java/org/apache/tomcat/util/http/fileupload/MultipartStream.java
catch (UnsupportedEncodingException e) { // Fall back to platform default if specified encoding is not // supported. headers = baos.toString(); }
// in java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java
catch (UnsupportedEncodingException e) { return new String(rawdata); }
// in java/org/apache/tomcat/util/buf/B2CConverter.java
catch (UnsupportedEncodingException e) { // Impossible. All JVMs must support these. e.printStackTrace(); }
// in java/org/apache/el/parser/ELParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/el/parser/ELParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/catalina/startup/ContextConfig.java
catch (UnsupportedEncodingException e) { // Should never happen with UTF-8 // If it does - ignore & return null }
// in java/org/apache/catalina/loader/WebappLoader.java
catch (UnsupportedEncodingException uee) { // Impossible. All JVMs are required to support UTF-8. }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/ant/JMXSetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/ResourcesTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JMXGetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/AbstractCatalinaCommandTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JKStatusUpdateTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JMXQueryTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/valves/AccessLogValve.java
catch (UnsupportedEncodingException ex) { log.error(sm.getString( "accessLogValve.unsupportedEncoding", encoding), ex); }
// in java/org/apache/catalina/valves/ExtendedAccessLogValve.java
catch (UnsupportedEncodingException e) { // Should never happen - all JVMs are required to support UTF-8 return null; }
// in java/org/apache/catalina/ssi/SSIServletExternalResolver.java
catch (UnsupportedEncodingException e) { retVal = queryString; }
// in java/org/apache/catalina/connector/Request.java
catch (UnsupportedEncodingException e) { // Ignore }
// in java/org/apache/catalina/connector/Request.java
catch (UnsupportedEncodingException uee) { try { value = part.getString(Parameters.DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { // Should not be possible } }
// in java/org/apache/catalina/connector/Request.java
catch (UnsupportedEncodingException e) { // Should not be possible }
// in java/org/apache/catalina/connector/CoyoteAdapter.java
catch (UnsupportedEncodingException e1) { log.warn(sm.getString("coyoteAdapter.parsePathParam", enc)); }
// in java/org/apache/catalina/util/RequestUtil.java
catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.parseParameters.uee", encoding), uee); } }
// in java/org/apache/catalina/util/RequestUtil.java
catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee); } }
// in java/org/apache/catalina/util/RequestUtil.java
catch (UnsupportedEncodingException uee) { if (log.isDebugEnabled()) { log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee); } return null; }
// in java/javax/servlet/http/HttpUtils.java
catch (java.io.UnsupportedEncodingException e) { // XXX function should accept an encoding parameter & throw this // exception. Otherwise throw something expected. throw new IllegalArgumentException(e.getMessage(), e); }
// in java/javax/el/ExpressionFactory.java
catch (UnsupportedEncodingException e) { // Should never happen with UTF-8 // If it does - ignore & return null }
15
            
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/tomcat/util/http/parser/HttpParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/el/parser/ELParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/el/parser/ELParser.java
catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/realm/RealmBase.java
catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); }
// in java/org/apache/catalina/ant/JMXSetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/ResourcesTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JMXGetTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/AbstractCatalinaCommandTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JKStatusUpdateTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/DeployTask.java
catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); }
// in java/org/apache/catalina/ant/JMXQueryTask.java
catch (UnsupportedEncodingException e) { throw new BuildException ("Invalid 'charset' attribute: " + getCharset()); }
// in java/javax/servlet/http/HttpUtils.java
catch (java.io.UnsupportedEncodingException e) { // XXX function should accept an encoding parameter & throw this // exception. Otherwise throw something expected. throw new IllegalArgumentException(e.getMessage(), e); }
8
runtime (Lib) UnsupportedOperationException 17
            
// in java/org/apache/el/lang/VariableMapperFactory.java
Override public ValueExpression setVariable(String variable, ValueExpression expression) { throw new UnsupportedOperationException("Cannot Set Variables on Factory"); }
// in java/org/apache/el/parser/SimpleNode.java
Override public Class<?> getType(EvaluationContext ctx) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/el/parser/SimpleNode.java
Override public Object getValue(EvaluationContext ctx) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/el/parser/SimpleNode.java
Override public Object invoke(EvaluationContext ctx, Class<?>[] paramTypes, Object[] paramValues) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/el/parser/SimpleNode.java
Override public MethodInfo getMethodInfo(EvaluationContext ctx, Class<?>[] paramTypes) throws ELException { throw new UnsupportedOperationException(); }
// in java/org/apache/catalina/ant/DeployTask.java
Override public void execute() throws BuildException { super.execute(); if (path == null) { throw new BuildException ("Must specify 'path' attribute"); } if ((war == null) && (localWar == null) && (config == null) && (tag == null)) { throw new BuildException ("Must specify either 'war', 'localWar', 'config', or 'tag' attribute"); } // Building an input stream on the WAR to upload, if any BufferedInputStream stream = null; String contentType = null; int contentLength = -1; if (war != null) { if (war.startsWith("file:")) { try { URL url = new URL(war); URLConnection conn = url.openConnection(); contentLength = conn.getContentLength(); stream = new BufferedInputStream (conn.getInputStream(), 1024); } catch (IOException e) { throw new BuildException(e); } } else { try { FileInputStream fsInput = new FileInputStream(war); long size = fsInput.getChannel().size(); if (size > Integer.MAX_VALUE) throw new UnsupportedOperationException( "DeployTask does not support WAR files " + "greater than 2 Gb"); contentLength = (int) size; stream = new BufferedInputStream(fsInput, 1024); } catch (IOException e) { throw new BuildException(e); } } contentType = "application/octet-stream"; } // Building URL StringBuilder sb = new StringBuilder("/deploy?path="); try { sb.append(URLEncoder.encode(this.path, getCharset())); if ((war == null) && (config != null)) { sb.append("&config="); sb.append(URLEncoder.encode(config, getCharset())); } if ((war == null) && (localWar != null)) { sb.append("&war="); sb.append(URLEncoder.encode(localWar, getCharset())); } if (update) { sb.append("&update=true"); } if (tag != null) { sb.append("&tag="); sb.append(URLEncoder.encode(tag, getCharset())); } } catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); } execute(sb.toString(), stream, contentType, contentLength); }
// in java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
Override public Object clone() { throw new UnsupportedOperationException("This operation is not valid on a replicated map"); }
// in java/org/apache/catalina/ha/deploy/FarmWarDeployer.java
public void cleanDeployDir() { throw new java.lang.UnsupportedOperationException(sm.getString( "farmWarDeployer.notImplemented", "cleanDeployDir()")); }
// in java/org/apache/catalina/connector/CometEventImpl.java
Override public void setTimeout(int timeout) throws IOException, ServletException, UnsupportedOperationException { if (request.getAttribute(Globals.COMET_TIMEOUT_SUPPORTED_ATTR) == Boolean.TRUE) { request.setAttribute(Globals.COMET_TIMEOUT_ATTR, Integer.valueOf(timeout)); if (request.isComet()) { request.setCometTimeout(timeout); } } else { throw new UnsupportedOperationException(); } }
// in java/javax/servlet/jsp/tagext/TagAdapter.java
Override public void setPageContext(PageContext pc) { throw new UnsupportedOperationException( "Illegal to invoke setPageContext() on TagAdapter wrapper"); }
// in java/javax/servlet/jsp/tagext/TagAdapter.java
Override public void setParent(Tag parentTag) { throw new UnsupportedOperationException( "Illegal to invoke setParent() on TagAdapter wrapper"); }
// in java/javax/servlet/jsp/tagext/TagAdapter.java
Override public int doStartTag() throws JspException { throw new UnsupportedOperationException( "Illegal to invoke doStartTag() on TagAdapter wrapper"); }
// in java/javax/servlet/jsp/tagext/TagAdapter.java
Override public int doEndTag() throws JspException { throw new UnsupportedOperationException( "Illegal to invoke doEndTag() on TagAdapter wrapper"); }
// in java/javax/servlet/jsp/tagext/TagAdapter.java
Override public void release() { throw new UnsupportedOperationException( "Illegal to invoke release() on TagAdapter wrapper"); }
// in java/javax/el/CompositeELResolver.java
Override public void remove() { throw new UnsupportedOperationException(); }
0 1
            
// in java/org/apache/catalina/connector/CometEventImpl.java
Override public void setTimeout(int timeout) throws IOException, ServletException, UnsupportedOperationException { if (request.getAttribute(Globals.COMET_TIMEOUT_SUPPORTED_ATTR) == Boolean.TRUE) { request.setAttribute(Globals.COMET_TIMEOUT_ATTR, Integer.valueOf(timeout)); if (request.isComet()) { request.setCometTimeout(timeout); } } else { throw new UnsupportedOperationException(); } }
2
            
// in java/javax/el/MapELResolver.java
catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); }
// in java/javax/el/ListELResolver.java
catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); }
2
            
// in java/javax/el/MapELResolver.java
catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); }
// in java/javax/el/ListELResolver.java
catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); }
2
unknown (Lib) ZipException 1
            
// in java/org/apache/catalina/startup/ExpandWar.java
public static String expand(Host host, URL war, String pathname) throws IOException { // Make sure that there is no such directory already existing File docBase = new File(host.getAppBaseFile(), pathname); if (docBase.exists()) { // War file is already installed return (docBase.getAbsolutePath()); } // Create the new document base directory docBase.mkdir(); // Expand the WAR into the new document base directory String canonicalDocBasePrefix = docBase.getCanonicalPath(); if (!canonicalDocBasePrefix.endsWith(File.separator)) { canonicalDocBasePrefix += File.separator; } JarURLConnection juc = (JarURLConnection) war.openConnection(); juc.setUseCaches(false); JarFile jarFile = null; InputStream input = null; boolean success = false; try { jarFile = juc.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String name = jarEntry.getName(); File expandedFile = new File(docBase, name); if (!expandedFile.getCanonicalPath().startsWith( canonicalDocBasePrefix)) { // Trying to expand outside the docBase // Throw an exception to stop the deployment throw new IllegalArgumentException( sm.getString("expandWar.illegalPath",war, name, expandedFile.getCanonicalPath(), canonicalDocBasePrefix)); } int last = name.lastIndexOf('/'); if (last >= 0) { File parent = new File(docBase, name.substring(0, last)); if (!parent.mkdirs() && !parent.isDirectory()) { throw new IOException( sm.getString("expandWar.createFailed", parent)); } } if (name.endsWith("/")) { continue; } input = jarFile.getInputStream(jarEntry); if(null == input) throw new ZipException(sm.getString("expandWar.missingJarEntry", jarEntry.getName())); // Bugzilla 33636 expand(input, expandedFile); long lastModified = jarEntry.getTime(); if ((lastModified != -1) && (lastModified != 0)) { expandedFile.setLastModified(lastModified); } input.close(); input = null; } success = true; } catch (IOException e) { throw e; } finally { if (!success) { // If something went wrong, delete expanded dir to keep things // clean deleteDir(docBase); } if (input != null) { try { input.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } input = null; } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } jarFile = null; } } // Return the absolute path to our new document base directory return (docBase.getAbsolutePath()); }
0 0 1
            
// in java/org/apache/naming/resources/WARDirContext.java
catch (ZipException e) { throw new IOException(e.getMessage(), e); }
1
            
// in java/org/apache/naming/resources/WARDirContext.java
catch (ZipException e) { throw new IOException(e.getMessage(), e); }
0

Miscellanous Metrics

nF = Number of Finally 325
nF = Number of Try-Finally (without catch) 157
Number of Methods with Finally (nMF) 302 / 14752 (2%)
Number of Finally with a Continue 0
Number of Finally with a Return 0
Number of Finally with a Throw 1
Number of Finally with a Break 0
Number of different exception types thrown 85
Number of Domain exception types thrown 31
Number of different exception types caught 116
Number of Domain exception types caught 22
Number of exception declarations in signatures 3953
Number of different exceptions types declared in method signatures 66
Number of library exceptions types declared in method signatures 49
Number of Domain exceptions types declared in method signatures 17
Number of Catch with a continue 17
Number of Catch with a return 274
Number of Catch with a Break 13
nbIf = Number of If 16700
nbFor = Number of For 1647
Number of Method with an if 5264 / 14752
Number of Methods with a for 1153 / 14752
Number of Method starting with a try 188 / 14752 (1.3%)
Number of Expressions 163629
Number of Expressions in try 26148 (16%)